directory

1. Inherits the WebMvcConfigurerAdapter abstract class to register interceptors with SpringBoot

Address code to intercept detection

Support for cross-domain code

2. Implement HandlerInterceptor interface to write a custom interceptor

Introduction:

3. Write the testController class

Log Execution Sequence


 

1. Inherits the WebMvcConfigurerAdapter abstract class to register interceptors with SpringBoot

package com.supermap.interceptor;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/** ** listener registration unit **@author yushen
 *
 */
@SpringBootConfiguration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

	@Autowired
	private TokenInterceptor tokenInterceptor;// Custom Token interceptor

	// Register interceptors
	@Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor).addPathPatterns("/ * *");
        super.addInterceptors(registry);
    }
 
	// Support cross-domain requests
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/ * *")
        .allowedOrigins("*")
        .allowCredentials(true)
        .allowedMethods("GET"."POST"."DELETE"."PUT")
        .maxAge(3600);
		super.addCorsMappings(registry); }}Copy the code

 

Address code to intercept detection

registry.addInterceptor(tokenInterceptor).addPathPatterns("/ * *");
Copy the code

 

Support for cross-domain code

registry.addMapping("/ * *")
        .allowedOrigins("*")
        .allowCredentials(true)
        .allowedMethods("GET"."POST"."DELETE"."PUT")
        .maxAge(3600);
Copy the code

 

2. Implement HandlerInterceptor interface to write a custom interceptor

package com.supermap.interceptor;

import com.supermap.uitl.UserListUitlCache;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/** * Custom interceptor **@author yushen
 *
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

	private final static Log logger = LogFactory.getLog(TokenInterceptor.class);

	// Inject the Redis utility class
	@Autowired
	private UserListUitlCache redisUtilsTwo;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		try {
			 logger.info("Enter the interceptor!"); 
                     return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false; }}@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub}}Copy the code
  • For example, when the user accesses the login address, the user takes out the token to verify it in Redis. If the login address is not accessed, the token does not prompt the user who has not logged in, go to login
  • If the user accesses the login login directly, the login token is saved in redis. If the login fails, the user returns a failure
  • If you want to log in, you can put the token in redis as the key, and the username as the value

ok

 

Introduction:

The preHandle method returns true if you go down and return false. You can return information in Response

  • preHandle

A preprocessing callback method that implements processor preprocessing (such as a login check) with a third parameter for the responding processor (such as a specific Controller implementation); Return value: true to continue the process (such as calling the next interceptor or processor); False indicates that the process is interrupted (such as failed login check) and will not continue to call other interceptors or processors. In this case, we need to generate a response through response.

  • postHandle

Post-processing callback method that implements post-processing by the processor (but before rendering the view), at which point we can process model data or view through modelAndView (modelAndView objects), which may also be null.

  • afterCompletion

A callback method is used when the view is rendered. For example, in performance monitoring, we can record the end time and output the elapsed time. We can also do some resource cleaning, similar to finally in try-catch-finally. But only afterCompletion is called for the interceptor in the handler execution chain where preHandle returns true.

 

3. Write the testController class

 

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.supermap.provider.test.service.impl.DeptServiceImpl;
import com.supermap.vo.Dept;

@RestController
public class testController {
	
	private final Log logger =LogFactory.getLog(DeptController.class);
	
	@RequestMapping(value="/getStr")
	public String getStr(a){
        logger.info("Enter the control floor.");
		return "hello"; }}Copy the code

 

Log Execution Sequence

Enter the interceptor. Enter the control floorCopy the code

 

Ok to complete