Filters There are two configurations, one kind of annotation is done by a custom configuration class by setting
assumed here that the scene is, define a filter, filter all requests, if there is no username parameter information to redirect login_page to the login page, if it is released with a username
(value = "/ *" ) // WebFilter annotation tells the spring it is a filter @Component // the Component annotation indicates that this is a component, you need to create an instance of a public class the implements the Filter { @Override public void the init (FilterConfig FilterConfig ) throws ServletException { System.out.println ( "the init, the service starts is called" ); }
@Override publicvoiddoFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; String path = req.getRequestURI(); HttpSession session = req.getSession(); if (req.getParameter("username") != null){ // 放行 chain.doFilter(request, response); }else { System.out.println(path); if (path.equals("/login_page")) { // 如果本身访问的是登录页面,直接放行 the chain.doFilter (Request, Response); } the else { // No username, a non-access login page redirected to a login page the HttpServletResponse RESP = (the HttpServletResponse) Response; resp.sendRedirect ( "login_page" ); } }
}
@Override public void the destroy () { System.out.println ( "the destroy, in time to stop the service program will be called" ); } }
Code configuration
1. Do not use annotations in fitler implementation class
@Bean ( "Bean1" ) public FilterRegistrationBean registerFilter1 () { // create a filter register bean objects FilterRegistrationBean Bean1 = new new FilterRegistrationBean (); // set the object to configure a filter bean1.setFilter ( new new secondFilter ()); // add the filter rules to filter url bean1.addUrlPatterns ( "/ *" ); // set the priority level, a number of the first filter performs execution bean1.setOrder ( . 1 ); return Bean1; } }