Use header in addition to method to route request to annotated method

前端 未结 2 988
北荒
北荒 2021-01-15 12:49

I wonder if it\'s possible with JAX-RS to route a request using an header in addition to the HTTP method. In fact, I can\'t find out the way to do that.

I thought ab

2条回答
  •  有刺的猬
    2021-01-15 13:43

    Just throw in another option. You can also use Sub-resource locators, which give us some control over the chosen resource (and is part of the JAX-RS spec). For example

    @Path("contacts")
    public class ContactsResource {
    
        @Path("/")
        public AbstractHeaderResource doSomething(@HeaderParam("X-Header") String xHeader) {
            if ("RequiredValue".equals(xHeader)) {
                return new WithHeaderResource();
            }
            return new WithOutHeaderResource();
        }
    
        public static abstract class AbstractHeaderResource {
            @POST
            @Consumes(MediaType.APPLICATION_JSON)
            public abstract Response doSometing(Contact contact);
        }
    
        public static class WithHeaderResource extends AbstractHeaderResource {
            @Override
            public Response doSometing(Contact contact) {
                return Response.ok("*** With Header ***").build();
            }
        }
    
        public static class WithOutHeaderResource extends AbstractHeaderResource {
            @Override
            public Response doSometing(Contact contact) {
                return Response.ok("*** WithOut Header ***").build();
            }
        }
    }
    

    Test

    C:\>curl -v -X POST  
             -d "{\"name\":\"Peeskillet\"}" 
             -H "X-Header:RequiredValue" 
             -H "Content-Type:application/json"
             http://localhost:8080/contacts 
    
    *** With Header ****
    
    C:\>curl -v -X POST  
             -d "{\"name\":\"Peeskillet\"}"  
             -H "Content-Type:application/json"
             http://localhost:8080/contacts 
    
    *** WithOut Header ****
    

    The resource methods don't have to accept the same parameter type. I did it just for brevity. You can have the sub resource classes extend an empty abstract class or interface (just for typing), and create the methods however you want

提交回复
热议问题