This is the 20th day of my participation in Gwen Challenge

Interceptors in SpringMVC

There are many scenarios where interceptors are used, such as login authentication, identity authorization, unified exception handling, and unified log handling, which can be easily implemented using interceptors.

Introduction and simple use of SpringMVC interceptor

Introduction to SpringMVC interceptor

1) SpringMVC Interceptor implements relevant business processing before and after each request processing, similar to Filter in servlet.

2) The SpringMVC Interceptor intercepts requests through the HandlerInterceptor.

3) Defining an Interceptor in SpringMVC is very simple. There are four main ways:

  • Spring implementation of HandlerInterceptor interface; (This method is used in this chapter)
  • Inherited implementation HandlerInterceptor interface classes, such as the Spring has been HandlerInterceptor interface provided by the abstract class HandlerInterceptorAdapter;
  • Spring implementation of WebRequestInterceptor interface;
  • Inherit the class that implements the WebRequestInterceptor;

2. Define interceptors

The interceptors used in this section are used to implement the HandlerIntercepter interface, create LoginInterceptor class, implement the HandlerInterceptor interface and rewrite the three methods inside.

Public class LoginInterceptor implements HandlerInterceptor {//Handler is called before implementation. Login authentication, identity authorization // If the return value is true, the system permits the login. @override public Boolean preHandle(HttpServletRequest Request, HttpServletResponse Response, Object handler) throws Exception { return false; } // Enter Handler to start executing and call // before returning ModelAndView: Operating on the ModelAndView object, you can pass the common model data to the foreground, @override public void postHandle(HttpServletRequest Request, HttpServletResponse Response, Object handler, ModelAndView ModelAndView) throws Exception {} // Call after executing Handler // Application scenarios: @override public void afterCompletion(HttpServletRequest Request, HttpServletResponse Response, Object handler, Exception ex) throws Exception { } }Copy the code

3. Configure interceptors

SpringMVC interceptors are bound to HandlerMapping, meaning that if intercepts are configured in a HandlerMapping, the interceptors are used by HandlerMapping successful HandlerMapping.

1) Configuration for a single HandlerMapping

Only processors found through the processor mapper can use the interceptor.

If you now have two processor mappers: one has a processor interceptor set and the other does not, the interceptor cannot be used if the processor found through the second mapper.

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
	<property name="interceptors">
		<list>
			<ref bean="interceptor" />
		</list>
	</property>
</bean>
<bean id="interceptor" class="xxx.xxx.xxx.interceptor.MyHandlerInterceptor" />
Copy the code

2) Global interceptor configuration

SpringMVC’s global interceptor configuration actually injects configured interceptors into each initialized HandlerMapping

<! < MVC :interceptors> <! Public interceptors can block all requests, And there can be multiple - > < bean class = "XXX. XXX. XXX. The interceptor. MyHandlerInterceptor1" / > < bean class="xxx.xxx.xxx.interceptor.MyHandlerInterceptor2" /> <! < MVC :interceptor> <! - / * * said all the URL and a URL path - > < MVC: mapping path = "/ test / * *" / > <! - specific request interceptor can only have one - > < bean class = "XXX, XXX XXX. The interceptor. MyHandlerInterceptor3" / > < / MVC: interceptor > </mvc:interceptors>Copy the code

Note here: If there are multiple interceptors, the interceptor configured at the top in springMVC.xml has the highest priority.

Third, interceptor login authentication demo

Here, interceptor is used to simulate login authentication. It only simulates the general process of login authentication, and does not realize real authentication. The purpose is to let readers understand the specific application of interceptor.

1. Specific requirements

  • Interceptor to access the request URL interception verification;
  • If the requested URL is a public address (a URL that can be accessed without a login, specifically the request URL that protects the login field), pass is enabled. If the user session exists, the device permits the session.
  • If the user session does not exist, the login page is displayed.

2, login JSP page: login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; Charset = utf-8 "> < title > login page < / title > < / head > < body > < form action =" ${pageContext. Request. ContextPath} / login" Method ="post"> <table align="center" border="1" cellspacing="0"> <tr> <td> < input type = "text" name = "username" / > < / td > < / tr > < tr > < td > secret code: < input type = "text" name = "password" / > < / td > < / tr > < tr > < td > < input type = "submit" value = "login" / > < / td > < / tr > < / table > < / form > </body> </html>Copy the code

3, LoginController. Java

@controller public class LoginController {/** * display the loginPage * @return */ @requestmapping ("/loginPage") public String loginPage() { return "login/login"; } /** * login * @param session * @param username * @param password * @return */ @requestMapping ("/login") public String Login (HttpSession session, String username, String password) {// Save user information to session. Session. setAttribute("username", username); Return "redirect:/queryItem"; } @requestMapping ("/logout") public String logout(HttpSession session) {// Delete session session session. Return "redirect:/loginPage"; // redirect to the loginPage. }}Copy the code

loginInterceptor.java

public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object Handler) throws Exception {// Obtain the requestURI. String requestURI = Request.getrequestURI (); System.out.println(requestURI); // 1. If the requested URL is a public address (a URL that can be accessed without login), permit is enabled. if (requestURI.indexOf("login") > -1) { return true; } // 2. If the user session exists, the system permits it. Object username = request.getSession().getAttribute("username"); if (username ! = null && ! username.equals("")) { return true; } // 3. If the user session does not exist, the login page is displayed. response.sendRedirect("/loginPage"); return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }Copy the code

Here, only the preHandle method is used for login authentication. The logic is relatively clear and the annotation is very clear.

5. Interceptor configuration: springMVC. XML

<! < MVC :interceptors> <! < MVC :interceptor> <! - / * * said all the URL and a URL path - > < MVC: mapping path = "/ * *" / > < bean class = "top. Alanshelby. Interceptor. LoginInterceptor" / > </mvc:interceptor> </mvc:interceptors>Copy the code

This completes a simple interceptor, which is pretty simple.

Four, summary

Interceptor is an indispensable application in daily development, here the most commonly used way to achieve interceptor is to implement HandlerInterceptor interface, I must manually implement a simple demo, so that I really understand the use of interceptor