Compare the difference between interceptors and filters. Multiple interceptors can be configured, the methods to be executed before, during and after the interception can be defined, and the code of business components can be called.
Interceptors are more flexible to use, and interceptors are recommended.
The first step is to create a new interceptor class
public class LoginInterceptor implements HandlerInterceptor{ /** * Execute this method before calling. */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //Get the request URL String uri = request.getRequestURI(); //URL: login.jsp is public; this demo is publicly accessible except for login.jsp, other URLs are intercepted and controlled if(uri.indexOf("login")>=0){ return true; } //get session HttpSession session = request.getSession(); String username = (String)session.getAttribute("username"); if(username != null){ return true; } //If the conditions are not met, jump to the login interface request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response); return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // TODO Auto-generated method stub System.out.println("==================>>执行postHandle"); } /** * This method is called after handler execution is complete. */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TODO Auto-generated method stub System.out.println("==================>>执行afterCompletion"); } }
Configure the interceptor
<!-- 5 interceptor configuration --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.soecode.lyf.interceptor.LoginInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>
The second step is to write the login controller
@Controller public class LoginController { @RequestMapping(value="/login",method = RequestMethod.POST) public String login(HttpSession session,String username,String password,Model model){ session.setAttribute("username", username); model.addAttribute("username", username); return "redirect:book/list"; } @RequestMapping(value="/logout",method = RequestMethod.POST) public String logout(HttpSession session){ session.invalidate(); return "redirect:/WEB-INF/jsp/login.jsp"; } }
The third step test.
Request the book reservation page and jump to the login interface.
After entering the account number, submit the login, and successfully enter the page