在做一些项目还没有用到一些比较深入的技术经行鉴权拦截的时候,可以简单的通过编写一个自定义拦截器来进行鉴权。通过SpringBoot拦截器进行拦截的三个步骤:
1.编写自定翻译拦截器继承HandlerInterceptor接口
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//登陆成功之后,应该拿的到用户的session
Object loginUser = request.getSession().getAttribute("loginUser");
//没有登陆
if(loginUser==null){
request.setAttribute("msg","请先登录后重试!");
//如果没有session既没登陆成功则转发请求
request.getRequestDispatcher("/index.html").forward(request,response);
//return false表示这个请求不能成功转发到相应页面
return false;
}else {
return true;
}
}
}
2.注册到自己定义的配置类文件里,然后在IDEA中通过alt+Ins快捷键调用@WebMvcConfigurer里面的addInterceptors方法,再重写addInterceptors里面参数的方法registry.addInterceptor(new 自定义接口())
其中addPathPatterns表示的是要拦截的资源,excludePathPatterns表示的是不拦截的资源
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//视图控制器
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
registry.addViewController("/sss.html").setViewName("index");
registry.addViewController("/main.html").setViewName("dashboard");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor())
.addPathPatterns("/**")
//登陆页面,首页,登陆请求,静态资源,一个*表示该目录下的所有文件,**则包括所有文件夹
.excludePathPatterns("/index.html","/","/user/login","/css/*","/img/**","/js/**");
}
}
至此,拦截器就写完了可以用啦,附上controller代码
controller类
@Controller
public class LoginController {
@RequestMapping("/user/login")
public String login(
@RequestParam("username")String username,
@RequestParam("password")String password,
Model model, HttpSession session){
if(!StringUtils.isEmpty(username)&&"123456".equals(password)){
session.setAttribute("loginUser",username);
return "redirect:/main.html";
}
else{
model.addAttribute("msg","error password or account");
return "index";
}
}
}