简体   繁体   中英

Calling a Filter before a Servlet from REST Webservice

I have written a REST web service method setToken(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("token") String token) , HeaderFilter and SampleServlet . Below is the web service class `@Path("/service") public class Service {

/*@Context 
private ServletContext servletContext; 

@Context
private HttpServletRequest request;

@Context
private HttpServletResponse response;*/


@Path("/val/{token}")   
@GET
@Produces("application/xml")
public String setToken(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("token") String token) throws ServletException, IOException {
    String value=token;
    if(request==null){
        System.out.println("Request null");
    }
    System.out.println("Token: " + value);
    if(request!=null){
        request.setAttribute("param", value);
        Wrapper requestWrapper = new Wrapper(request);
        requestWrapper.addHeader("Authorization", token);
        request.getRequestDispatcher("/secure").include(requestWrapper, response);
    }
    return "<token>"+ "<value>"+value+" token value"+"</value>" + "</token>";
}

}`

From the setToken web service method am calling SampleServlet using request.getRequestDispatcher("/secure").include(request, response); and the URL am using is http://localhost:8080/xxxx/xxxx/service/val/zzzz . zzzz is the value to be passed. The URL pattern for HeaderFilter and SampleServlet is /secure. Now the problem is HeaderFilter is not being called and directly 'SampleServlet' is called. Am I doing anything wrong???? Kindly help me get through this.

The URL pattern for HeaderFilter and SampleServlet is /secure. Now the problem is HeaderFilter is not being called and directly 'SampleServlet' is called.

By default Filters are invoked only for requests originating from the web. They are not invoked for internal 'includes' and 'forwards'. To change the default behaviour and have the filter invoked, you will have to specify that in your filter-mapping element of web.xml

<filter-mapping>
   <filter-name>myfilter</filter-name>
   <url-pattern>/secure</url-pattern>
   <dispatcher>FORWARD</dispatcher>
   <dispatcher>INCLUDE</dispatcher>
   <dispatcher>REQUEST</dispatcher>
</filter-mapping>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM