开发者

Spring interceptor/filter

开发者 https://www.devze.com 2023-04-06 13:55 出处:网络
I need to write an interceptor/filter in my spring-jersey application, which will check every request for session and on success it will pass a code to respective controller. Passing this code is imp,

I need to write an interceptor/filter in my spring-jersey application, which will check every request for session and on success it will pass a code to respective controller. Passing this code is imp, because based on the code controller will decide fur开发者_开发技巧ther action.

Q: 1) Is this possible to write this kind of login filter in Spring? How? 2) Is this possible to pass some code to controller from interceptor? How?


We need to implement ContainerRequestFilter interface for creating Jersey filter. Following is the code sample for intercepting and modifying a request using jersey filter:

import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import javax.ws.rs.core.MultivaluedMap;
import org.apache.log4j.Logger;

/**
 *
 * @author arnav
 */
public class MyAppFilter implements ContainerRequestFilter{


   public ContainerRequest filter(ContainerRequest request) {

      MultivaluedMap<String, String> headers = request.getRequestHeaders();

      headers.add("code", "MY_APP_CODE");
      request.setHeaders((InBoundHeaders)headers);

      return request;
   }
}

After adding this class, we need to register this filter for our web application. So now we will add following lines in our web.xml:

<servlet>
      ..........
      ..........   
      <init-param>
         <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
         <param-value>package.MyAppFilter</param-value>
      </init-param> 
</servlet>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号