1. Requirement Background
You need to intercept a request url to simulate whether you can enter a certain interface. If the interception needs to return false data, don't ask me why I don't use the intercept interceptor.
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 represents the intercepted url, if you want to intercept all, just /*. </ filter-mapping >
3. Custom 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 {
//Because the filter priority is high, the direct @Autowired introduction of service does not exist
//The following is HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse resp = (HttpServletResponse)response; ServletContext sc = req.getSession().getServletContext();
//The following is the process of creating service XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc); //aaaServiceImpl is the aaaService implementation class if(cxt != null && cxt.getBean("aaaServiceImpl") != null && aaaService == null) aaaService = (AAAService) cxt.getBean("aaaServiceImpl"); // here is the logic if(success){ chain.doFilter(request, response); //Enter the requested url }else{ req.getRequestDispatcher("/xxx url").forward(request,response);//Jump to the url specified by yourself } } @Override public void destroy() { } }
/xxx url to jump to
@RequestMapping(value = "/getEntranceStatus", method = RequestMethod.GET, produces = "text/html;charset=UTF-8") public String getEntranceStatus(HttpServletRequest request){ // here is to return a false }