项目使用的是idea开发工具,thymeleaf+springboot1.56(2.0版本也可以)+mybatis.现在需要写一个拦截器,网上有很多,但是对于我这种小白有些地方看的不太明白,今天我来写的详细一些,废话不多说开始(这里拦截器没有使用springWebSecurity框架,所以不用在maven中配置)
首先写一个实体类,项目使用的是mybatis 所以可以自动生成。表的字段其实很简单
private Long userNo;
private Integer id;
private String userName;
private String password;
private String nickName;
private String role;
其中userName和password是必须的,其他的我项目需要用,你们可以不加。
然后写一个拦截器配置类,继承WebMvcConfigurerAdpter,其中SESSION_KEY可以随便写,登录的Controller类会调用它然后存到session中,SecurityInterceptor类会接收它,如果不为空就放行,否则跳转到登录页面。详情请看下面代码
/**
* Created by yStar on 2018/2/23 16:36:16
* 拦截器配置
*/
@Configuration
public class WebSecurityConfig extends WebMvcConfigurerAdapter {
public static final String SESSION_KEY="name";
@Bean
public SecurityInterceptor getSecurityInterceptor(){
return new SecurityInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry){
InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
//排除配置
addInterceptor.excludePathPatterns("/error");
addInterceptor.excludePathPatterns("/login/**");
addInterceptor.excludePathPatterns("/captcha");//排除验证码
//拦截配置
addInterceptor.addPathPatterns("/**/**");
}
private class SecurityInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws IOException{
HttpSession session = request.getSession();
//判断是否已有该用户登录的session
if(session.getAttribute("account") !=null){
return true;
}
//跳转到登录页
String url = "/art/login";
response.sendRedirect(url);
return false;
}
}
}
登录的Controller类
@Controller
public class helloController {
@Autowired
private SystemLogService systemLogService;
@RequestMapping("/")
public String index(@SessionAttribute(WebSecurityConfig.SESSION_KEY) String account,Model model) {
model.addAttribute(account);
return "login";
}
@RequestMapping("/login")
public String login(ModelMap map) {
return "login";
@PostMapping(value = "login")
public String login(SysUser sysUser, ModelMap map, HttpServletRequest request, HttpSession session) {
SysUser sysUser1 = sysUserMapper.login(sysUser);
if (sysUser1 != null) {
//如果不为空就代表由此用户,然后存到日志里(这些代码和拦截器无关 可忽略)
SystemLog systemLog = new SystemLog(); systemLog.setUserIP(getIpAddr(request)); systemLog.setUserNo(sysUser1.getUserNo()); systemLog.setLogNo(IDUtil.next()); systemLog.setLoginDate(new Date());
systemLogService.systemLog(systemLog);
//把SESSION_KEY存到session中
session.setAttribute("account",WebSecurityConfig.SESSION_KEY);
map.addAttribute("systemLog", systemLog);
return "/index";
} else {
map.put("msg", "账号或密码错误!");
return "login";
}
}
到此就可以实现拦截功能了,登录功能暂没详写。
下面这个是退出登录,移除session,写在登录的controller类中
/**
* 退出登录
* @param session
* @return
*/
@GetMapping("/logout")
public String logout(HttpSession session) {
// 移除session
session.removeAttribute("account");
return "redirect:/login";
}
![](https://i-blog.csdnimg.cn/blog_migrate/d3d256c1990640ef8c9f336c6f7b7b98.png)