手头上有对所有请求做权限认证的需求,必须要在执行rest方法之前判断用户是否是登录状态,也就是要判断session存不存在,这里使用ContainerRequestFilter,从名字上也能看出来它是一个过滤器,会将所有请求拦截下来,之后做什么处理就随我们拉。
首先是web.xml配置:
<servlet> <servlet-name>Jersey REST Service</servlet-name> <servlet-class> com.sun.jersey.spi.container.servlet.ServletContainer </servlet-class> <init-param> <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name> <!-- 如果想加入多个拦截器,请用;隔开 --> <param-value>com.my.webservice.TestRequestFilter</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey REST Service</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>
下面是具体代码:
public class TestRequestFilter implements ContainerRequestFilter{ @Context private HttpServletRequest servletRequest; @Context private HttpServletResponse servletResponse; @Override public ContainerRequest filter(ContainerRequest creq) { System.out.println("TestRequestFilter Request:" + creq); if(!servletRequest.getRequestURL().toString().endsWith("/login") && !servletRequest.getMethod().equals("OPTIONS")){ Response response = Response.ok(new ErrorJSON(99, "error")).status(401).type(MediaType.APPLICATION_JSON).build(); throw new WebApplicationException(response); // Throw new UnAuthorized } return creq; } }