springBoot拦截器
基本步骤
- 创建controller
package com.hzc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/student")
public class StudentController {
@RequestMapping("/show")
@ResponseBody
public String show(){
return "interceptor...";
}
@RequestMapping("/login")
public String login(Model model, String username){
model.addAttribute("username",username);
return "index";
}
}
- 自定义拦截器类,实现HandlerInterceptor接口。
package com.hzc.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 StudentInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String username = (String) request.getSession().getAttribute("username");
if(username == null){
response.getWriter().write("username is null");
return false;
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
- 注册拦截器,创建一个拦截器核心配置类并继承WebMvcConfigurer
package com.hzc.config;
import com.hzc.interceptor.StudentInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
//拦截的方法
String[] pathPattern = {"/student/show"};
//不拦截的方法
String[] excludePathPattern = {"/student/login"};
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new StudentInterceptor())
.addPathPatterns(pathPattern)
.excludePathPatterns(excludePathPattern);
}
}
4.测试。