SpringBoot Interceptor

In actual development, there are always such scenarios, such as intercepting the ip address of the request, or returning the same data in all requests, if each method writes the same data, it can be achieved, but as the project grows larger , the repeated code will be more and more, so in this case we can use the interceptor to achieve.

I have been studying thymeleaf recently, and I feel that this is very useful, so this article also chooses to use it in combination.

Create a new project, the pom file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.dalaoyang</groupId>
    <artifactId>springboot_interceptor</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot_interceptor</name>
    <description>springboot_interceptor</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.15</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

Create a new interceptor CommonInterceptor that inherits HandlerInterceptorAdapter. Let me tell you, there are three interceptors that are often used in inheriting HandlerInterceptorAdapter:
1.preHandle is called before
the business processor processes the request 2.postHandle is executed after the business processor processes the request and before the view is generated
3.afterCompletion is in Called when DispatcherServlet has completely processed the request

This article uses postHandle, the code is as follows:

package com.dalaoyang.interceptor;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaoyang.interceptor
 * @email [email protected]
 * @date 2018/4/27
 */
@Component
public class CommonInterceptor extends HandlerInterceptorAdapter {
    Logger logger = Logger.getLogger(CommonInterceptor.class);



    //preHandle在业务处理器处理请求之前被调用,
    //postHandle在业务处理器处理请求执行完成后,生成视图之前执行
    //afterCompletion在DispatcherServlet完全处理完请求后被调用
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        logger.info("请求ip:"+request.getRemoteAddr());
        logger.info("请求的方法:"+request.getMethod());
        ModelMap modelMap = modelAndView.getModelMap();
        modelMap.addAttribute("title","dalaoyang");
    }
}

Inherit WebMvcConfigurerAdapter in the startup class to add interceptors to the project, the code is as follows:

package com.dalaoyang;

import com.dalaoyang.interceptor.CommonInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
public class SpringbootInterceptorApplication extends WebMvcConfigurerAdapter {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootInterceptorApplication.class, args);
    }

    @Autowired
    CommonInterceptor commonInterceptor;

    // 增加拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(commonInterceptor);
    }
}

IndexController is responsible for jumping, the code is as follows:

package com.dalaoyang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author dalaoyang
 * @Description
 * @project springboot_learn
 * @package com.dalaaoyang.controller
 * @email [email protected]
 * @date 2018/4/27
 */

@Controller
public class IndexController {

    @RequestMapping("/")
    public String index(Model model){
        model.addAttribute("content","hi , dalaoyang !");
        return "index";
    }
}

Create a new index.html under templates, where content is the content returned by the controller, and title is the content returned in the interceptor. The code is as follows:

<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title th:text="${title}"></title>
</head>
<body>
<p th:text="${content}"></p>
</body>
</html>

Start the project, visit http://localhost:8888/ , the console is as follows:

Take a look at the page:

Source code download: Da Lao Yang Code Cloud

Personal website: https://dalaoyang.cn

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324971217&siteId=291194637