写在前面
你们好,我是小庄。很高兴能和你们一起学习Springboot。如果您对Java感兴趣的话可关注我的动态.
写博文是一种习惯,在这过程中能够梳理和巩固知识。
需求:管理员管理后台页面,未登录不能访问后台
eg:/admin/*路径下是后台的页面,/admin/login.html是后台登录页面
第一步:定义拦截器
/**
* 登录检查
*/
public class LoginHandlerIntercptor implements HandlerInterceptor {
//目标方法执行之前
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user=request.getSession().getAttribute("loginUser");//这个是登录时注册到session中的值
if(user==null){
//未登录
request.setAttribute("msg","没有权限请先登录");
request.getRequestDispatcher("/admin/login.html").forward(request,response);
return false;
}
else {
return true;
}
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
第二步:注册拦截器到配置中
@Configuration
public class LoginConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注册拦截器
LoginHandlerIntercptor loginInterceptor = new LoginHandlerIntercptor ();
InterceptorRegistration loginRegistry = registry.addInterceptor(loginInterceptor);
// 拦截路径
loginRegistry.addPathPatterns("/admin/*");
// 排除路径
loginRegistry.excludePathPatterns("/");
loginRegistry.excludePathPatterns("/admin/login");
// 排除资源请求
loginRegistry.excludePathPatterns("/css/login/*.css");
loginRegistry.excludePathPatterns("/js/login/**/*.js");
}
}
第三步:登录验证
@Controller
public class LoginController {
//拦截post请求
@PostMapping(value = "/admin/login")
public String login(@RequestParam("username") String username, @RequestParam("password") String password, Map<String,Object> map, HttpSession session){
if(!StringUtils.isEmpty(username)&& "123456".equals(password)){
session.setAttribute("loginUser",username);
return "/admin/sucess";
}
else {
map.put("msg","用户名密码错误");
return "/admin/login";
}
}
}