拦截器
1.编写一个拦截器实现HandlerInterceptor接口
2.拦截器注册到容器中(实现WebMvcConfigurerAdapter的addInterceptors)
3.指定拦截规则(如果是拦截所有,静态资源也会被拦截)
InterceptorConfig代码
package com.xt.cn.springboot.interceptor.config;
import com.xt.cn.springboot.interceptor.interceptor.LogCostInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter{
@Override
public void addInterceptors(InterceptorRegistry registry){
//registry.addInterceptor(new LogCostInterceptor()).addPathPatterns("/**");
registry.addInterceptor(new LogCostInterceptor()).addPathPatterns("/test1");
registry.addInterceptor(new LogCostInterceptor()).addPathPatterns("/test2");
super.addInterceptors(registry);
}
}
LogCostInterceptor代码
package com.xt.cn.springboot.interceptor.interceptor; 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; import java.io.PrintWriter; import java.util.Enumeration; public class LogCostInterceptor implements HandlerInterceptor { long start = System.currentTimeMillis(); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { /*HttpSession session = request.getSession(); session.setAttribute("user","zhangsan"); session.setAttribute("pwd",123456); Enumeration<String> attributeNames = session.getAttributeNames(); while (attributeNames.hasMoreElements()){ String k = attributeNames.nextElement(); System.out.println(k+"--"+session.getAttribute(k)); }*/ String userName = request.getParameter("username"); System.out.println("请求执行之前:userName="+userName + "111"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { String userName = request.getParameter("username"); System.out.println("请求执行之后:userName="+userName + "222"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
Test1Controller代码
package com.xt.cn.springboot.interceptor.controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; @RestController public class Test1Controller { @GetMapping("/test1") public String test(HttpServletRequest request, String username) { System.out.println("controller中username=" + username); System.out.println("请求头中的Cookie信息:" + request.getHeader("Cookie")); return "123"; } @GetMapping("/test2") public String test2(HttpServletRequest request) { return "123"; } }