1. 需求背景
需要对某个请求url进行拦截,模拟是否可以进入某一个接口,如果拦截需要返回数据false,别问我为何不用intercept拦截器。
2. web.xml
<filter>
<filter-name>restfulFilter</filter-name>
<filter-class>com.jeenotes.utils.filter.RestfulFilter</filter-class> 过滤器路径
</filter> <filter-mapping>
<filter-name>restfulFilter</filter-name>
<url-pattern>/aaa/*</url-pattern> aaa表示拦截的url,如果你想拦截所有,直接/*即可。
</filter-mapping>
3. 自定义的Filter
public class RestfulFilter implements Filter { private AAAService aaaService; @Override
public void init(FilterConfig filterConfig) throws ServletException {
} @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
//由于filter 优先级要高,所以直接@Autowired引入service是不存在的
//如下是
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
ServletContext sc = req.getSession().getServletContext();
//如下是创建service过程
XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
//aaaServiceImpl 是aaaService实现类
if(cxt != null && cxt.getBean("aaaServiceImpl") != null && aaaService == null)
aaaService = (AAAService) cxt.getBean("aaaServiceImpl"); //此处是逻辑 if(成功){
chain.doFilter(request, response); //进入请求的url
}else{
req.getRequestDispatcher("/xxx某某url").forward(request,response);//跳转自己指定的url
} } @Override
public void destroy() {
} }
要跳转的/xxx某某url
@RequestMapping(value = "/getEntranceStatus", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
public String getEntranceStatus(HttpServletRequest request){ //此处就是返回一个false }