1, create an interceptor LoginInterceptor and implement HandlerInterceptor

The role of @ Component

<bean ID ="" class=""/> <bean ID ="" class=""/> <bean ID ="" class="" > <bean ID ="" class="" >Copy the code

package com.sgcc.epri.basis.config; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class LoginInterceptor implements HandlerInterceptor {/** ** Preprocess; /** * Preprocess; False indicates that the process is interrupted. */ @override public Boolean preHandle(HttpServletRequest Request, HttpServletResponse Response, Throws Exception {system.out.println (" Start intercepting.........") ); // Return false; } /** * postprocessing callback method to implement the postprocessing of the controller, */ @override public void postHandle(HttpServletRequest Request, HttpServletRequest request, HttpServletResponse response, Object handler, Throws Exception {// TODO auto-generated method stub} /** * Callback when the entire request is processed * In performance monitoring, we can record the end time and output the elapsed time. * We can also do some resource cleaning, like finally in try-catch-finally. */ @override public void afterCompletion(HttpServletRequest Request, HttpServletResponse Response, Object handler, Exception ex) throws Exception { // TODO Auto-generated method stub } }Copy the code

2. Create a configuration class to introduce interceptors

@ the role of the Configuration

From Spring3.0, @configuration is used to define a Configuration class that can replace an XML Configuration file. The annotated class contains one or more methods annotated by @bean. These methods will be AnnotationConfigApplicationContext or AnnotationConfigWebApplicationContext scanned, and used to construct the bean definition, initialize the Spring container.Copy the code

package com.sgcc.epri.basis.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; @Configuration public class MvcInterceptorConfig extends WebMvcConfigurationSupport { @Autowired private LoginInterceptor loginInterceptor; @override protected void addInterceptors(InterceptorRegistry registry) {// add a chain of interceptors // addPathPatterns // excludePathPatterns Users exclude interceptionregistry. AddInterceptor (loginInterceptor).addPathPatterns("/**") .excludePathPatterns("/demo","/test"); super.addInterceptors(registry); }}Copy the code

registry.addInterceptor(loginInterceptor).addPathPatterns(“/**”).excludePathPatterns(“/demo”,”/test”);

It means to intercept all requests, but let go of the /demo and /test requests

However, we will not directly write the method of release here, each modification of the code operation is very redundant and non-standard.

3. Write the no-intercept method to the configuration file

Application. yml Configures the permit address

# Permission verification URL whitelist, the path of the back-end interface that can be accessed without login and authorization # (use comma to separated multiple lines) End with "\" permitted- URL: "/demo,\ /test"Copy the code

Get the contents of this configuration in the configuration class

@Value("${permitted-url}")
private String permittedUrl;
Copy the code

Change the code before the comment to the content

List<String> permittedUrls =new ArrayList<String>() ;
        for(String permitted :permittedUrl.split(",") ) {
            permittedUrls.add(permitted) ;
        }   

registry.addInterceptor(loginInterceptor).addPathPatterns("/**").excludePathPatterns(permittedUrls);
Copy the code

The full code is as follows

package com.sgcc.epri.basis.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.util.ArrayList; import java.util.List; @Configuration public class MvcInterceptorConfig extends WebMvcConfigurationSupport { @Autowired private LoginInterceptor loginInterceptor; @Value("${permitted-url}") private String permittedUrl; @override protected void addInterceptors(InterceptorRegistry registry) {// add a chain of interceptors // addPathPatterns /*registry. AddInterceptor (loginInterceptor).addPathPatterns("/**") .excludePathPatterns("/demo","/test"); super.addInterceptors(registry); List<String> permittedUrls =new ArrayList<String>(); for(String permitted :permittedUrl.split(",") ) { permittedUrls.add(permitted) ; } registry.addInterceptor(loginInterceptor).addPathPatterns("/**").excludePathPatterns(permittedUrls); }}Copy the code

4, test,

To test this, start by accessing a random method that you want to intercept

The console outputs the intercept log without executing the following method

Let’s revisit the decentralized method

The access is successful and the test is over, but the methods of direct release are destined to be minimal, and the main thing is the verification after interception

5, the interceptor’s custom business validation function

In the above LoginInterceptor class, we only write an output and all return false, the code here needs to be defined according to different requirements, my requirement is that the interceptor method will carry the phone number, we match the user information, match the user’s business data will be displayed, If there is no or no mobile phone number, the sample data will be displayed, so there will only be release in my requirements. But it can also be assumed that if there is matching data, the verification is successful; if there is no, the verification fails, and error information will be returned. This depends on their respective business requirements.

/** * return value: true; False indicates that the process is interrupted. */ @override public Boolean preHandle(HttpServletRequest Request, HttpServletResponse Response, String loginPhone = request.getParameter("loginPhone"); String loginPhone = request.getParameter("loginPhone"); If (loginPhone! = null && !" ".equals(loginPhone)){ String consId = demoService.getConsId(); request.getSession().setAttribute("consId",consId); return true; }else{ request.getSession().setAttribute("consId","0"); return true; }}Copy the code

So now that we’ve all set true, we’re going to try to see if the interceptor that was intercepted can pass, and at this point the interceptor is set.

There may also be many ways to verify whether the user is expired, no interception is required if the user is not expired, or automatically update the active state when accessing. These may need to verify the session and cache more, depending on the business requirements. The following is our previous interception request, including PC and small program interception. Because the session PC landed already stored primarily for use in small programs do check token, incomplete is not verify the existence of the enterprise id and but we demand enterprise id is the platform to, so is to obtain the enterprise id is already exist so directly returns true, if is a separate system need to verify

response.setContentType("text/plain; charset=UTF-8"); response.setCharacterEncoding("utf-8"); JSONObject json = JSONObject.parseObject(String.valueOf(request.getSession().getAttribute("consInfo"))); // Get user information if (json! = null) {// Verify that the enterprise ID exists return true; }else { String token = request.getParameter("token"); // Obtain the passed token system.err.println (token); if (token! =null&&!" Request.getsession ().setAttribute("token", token); System.err.println(request.getSession().getAttribute("token")); ResponseParam responseParam = userInterface.login(request,response); if ("200".equals(String.valueOf(responseParam.getStatus()))) { return true; }else { JSONObject data = new JSONObject(); data.put("status", 500); Data.put ("message", "user invalid "); data.put("sessionExpired", true); response.getWriter().write(data.toString()); return false; } } JSONObject data = new JSONObject(); data.put("status", 500); Data.put ("message", "user invalid "); data.put("sessionExpired", true); response.getWriter().write(data.toString()); return false; }Copy the code

\