I have learned filters before, but the filters are for servlets and are used in springmvc and spring boots. They don’t feel very useful in terms of functions.
Let’s learn about interceptors here.
1. The order of execution of the interceptor
1. Contents
2. Interceptor
In the interceptor, I added three (First, Two, Third), but the contents are almost the same.
package org.elvin.boot.interceptor;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class FirstInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { System.out.println("FirstInterceptor preHandle"); return true; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("FirstInterceptor postHandle"); } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { System.out.println("FirstInterceptor afterCompletion"); }}preHandle returns true before the following execution will continue.
Interceptor registration:
package org.elvin.boot.interceptor;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configurationpublic class RegisterInterceptor extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new FirstInterceptor()); registry.addInterceptor(new TwoInterceptor()); registry.addInterceptor(new ThirdInterceptor()); super.addInterceptors(registry); }}In order to verify the execution order, thymeleaf is used here, and then the properties I passed in the background were accessed in the foreground. When accessing, the information will be printed to the console
package org.elvin.boot.pojo;public class Book { private String name ; public String getName() { System.out.println("view : Book'name is " + name); return name; } public void setName(String name) { this.name = name; }}Controller:
package org.elvin.boot.Controller;import org.elvin.boot.pojo.Book;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping("first")public class FirstController { private String controllerPath = "first/"; @GetMapping("index") public String index(Model model){ System.out.println("controller : FirstController index doing..."); Book book = new Book(); book.setName("spring boot"); model.addAttribute("book", book); return controllerPath + "index"; }}View:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" /> <title>Title</title></head><body> <h1 th:text="${book.name}"></h1></body></html>When accessing localhost:8080/first/index, response information will be output on the console.
In this way, the execution order of a single interceptor can be seen.
1. The preHandle method executed before the controller method is executed
2. Execute the controller action method
3. After executing the action, before parsing the view (if any), execute the postthandle method of the interceptor
4. Analyze the view
5. After parsing, execute the afterCompletion method
When multiple interceptors are registered, the execution order is as shown in the figure.
2. Interceptor implements permission verification
Similarly, add permission interceptor first
package org.elvin.boot.interceptor;import org.elvin.boot.annotation.NoLogin;import org.springframework.util.StringUtils;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handle) throws Exception { HandlerMethod method = (HandlerMethod ) handle; Class<?> controllerType = method.getBeanType(); if(method.getMethodAnnotation(NoLogin.class) != null || controllerType.getAnnotation(NoLogin.class) != null){ return true; } HttpSession session = request.getSession(); String token = (String)session.getAttribute("token"); if(!StringUtils.isEmpty(token)){ return true; } response.sendRedirect("/login/index"); return false; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { }}Then register the permission interceptor
package org.elvin.boot.interceptor;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.InterceptorRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configurationpublic class RegisterInterceptor extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginInterceptor()); super.addInterceptors(registry); }}Add a login controller to the controller, provide login page and logout method
package org.elvin.boot.Controller;import org.elvin.boot.annotation.NoLogin;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;@NoLogin@Controller@RequestMapping("login")public class LoginController { @Autowired private HttpServletRequest request; @Autowired private HttpServletResponse response; private String controllerPath = "login/"; //@NoLogin @GetMapping("index") public String index(){ HttpSession session = request.getSession(); session.setAttribute("token", "token"); return controllerPath + "index"; } //@NoLogin @PostMapping("checkOut") @ResponseBody public String checkOut(){ HttpSession session = request.getSession(); session.setAttribute("token", null); return "ok"; }}Here I have made a login-free annotation, which can be added to the Controller or to the action.
package org.elvin.boot.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.TYPE, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface NoLogin {}No content is needed in the annotation.
Login page (The login page here is just for logout, so after visiting this page, it means that the login is successful).
<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head> <meta charset="UTF-8"/> <title>Title</title></head><body><div> <input type="button" value="Logout" id="checkOut"/></div><script th:src="@{/js/jquery-1.11.1.js}"></script><script th:inline="javascript"> $(function () { $(".container").delegate("#checkOut", "click", function () { $.ajax({ url: [[@{/login/checkOut}]], type: 'post', data: {}, success: function (res) { if (res == "ok") { alert("Logout successful"); } } }); }); }); });</script></body></html>Results demonstration method:
In the browser, first open the http://localhost:8080/login/index page, and then access the http://localhost:8080/first/index page in the new tab.
You will find that when accessing first/index, you can access it.
At this time, in the login/index page, click the logout button, refresh the first/index page, and you will jump to the login page directly.
The above example explanation of string boot and custom interceptor is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.