Using a default method for unmatched REST methods

2019-03-31 00:40发布

问题:

I know this is not quite "restful" but, I want to learn if and how I can handle all requests which do not match any of the methods in my REST resource (I want to proxy these requests to another server). For example, it could be a method like:

@GET 
@Path("*") 
public Response defaultMethod(@Context HttpServletRequest request, @Context HttpServletResponse response) 
{ 
    // do proxying here 
} 

how can I achieve this?

BR,

SerkanC

回答1:

@Path("/{default: .*}")

This works for:

  • http://example.com/someUnexpectedPath
  • http://example.com/someUnexpectedPath/withAdditionalSubPaths
  • http://example.com/someUnexpectedPath/withAdditionalSubPaths?andParams=whatever


回答2:

One possible option would be to define a custom 404 mapping. Since 404s handles all unmatched requests it should catch all undefined urls.

I added the following this to my web.xml file

 <error-page>
    <error-code>404</error-code>
    <location>/error/404</location>
  </error-page>

Where location is the path you want to direct the request to. Then just define that the call as normal.



标签: rest jersey