SpringBoot注册登录(三):注册--验证账号密码是否符合格式及后台完成注册功能点击打开链接
SpringBoot注册登录(四):登录功能--密码错误三次,需要等待2分钟才能登录,固定时间内不能登录点击打开链接
SpringBoot注册登录(五):登录功能--Scheduling Tasks定时作业,用于某个时间段允许/不允许用户登录点击打开链接
SpringBoot--mybatis--ajax--模态框--log:注册、登录、拦截器、文件系统源代码点击打开链接
直接运行程序,就会加载拦截器了。这个拦截器在没登录前只会放行登录注册、验证码的请求
一、先在启动类加上注解(如果使用了下面步骤的代码程序执行失败的话)
- @ComponentScan
- @EnableAutoConfiguration
- @EnableScheduling
- @Configuration
二、定义两个类
1、LoginInterceptor
- package com.fxy.interceptor;
- import com.fxy.bean.User;
- import com.fxy.service.UserService;
- import org.apache.log4j.Logger;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Component;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- import java.util.ArrayList;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Set;
- /**
- * 登录验证拦截
- *
- */
- @Controller
- @Component
- public class LoginInterceptor extends HandlerInterceptorAdapter {
- Logger log = Logger.getLogger(LoginInterceptor.class);
- /*@Autowired
- UserService userService;*/
- /*@Value("${IGNORE_LOGIN}")
- Boolean IGNORE_LOGIN;*/
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
- throws Exception {
- String basePath = request.getContextPath();
- String path = request.getRequestURI();
- // log.info("basePath:"+basePath);
- // log.info("path:"+path);
- if(!doLoginInterceptor(path, basePath) ){//是否进行登陆拦截
- return true;
- }
- // HttpSession session = request.getSession();
- // int userID = 2;
- // UserInfo userInfo = sysUserService.getUserInfoByUserID(userID);
- // System.out.println(JsonUtil.toJson(userInfo));
- // session.setAttribute(Constants.SessionKey.USER, userInfo);
- //如果登录了,会把用户信息存进session
- HttpSession session = request.getSession();
- List<User> users = (List<User>) session.getAttribute("userList");
- /*User userInfo = new User();
- userInfo.setId(users.get(0).getId());
- userInfo.setName(users.get(0).getName());
- userInfo.setPassword(users.get(0).getPassword());*/
- //开发环节的设置,不登录的情况下自动登录
- /*if(userInfo==null && IGNORE_LOGIN){
- userInfo = sysUserService.getUserInfoByUserID(2);
- session.setAttribute(Constants.SessionKey.USER, userInfo);
- }*/
- if(users==null){
- /*log.info("尚未登录,跳转到登录界面");
- response.sendRedirect(request.getContextPath()+"signin");*/
- String requestType = request.getHeader("X-Requested-With");
- // System.out.println(requestType);
- if(requestType!=null && requestType.equals("XMLHttpRequest")){
- response.setHeader("sessionstatus","timeout");
- // response.setHeader("basePath",request.getContextPath());
- response.getWriter().print("LoginTimeout");
- return false;
- } else {
- log.info("尚未登录,跳转到登录界面");
- response.sendRedirect(request.getContextPath()+"signin");
- }
- return false;
- }
- // log.info("用户已登录,userName:"+userInfo.getSysUser().getUserName());
- return true;
- }
- /**
- * 是否进行登陆过滤
- * @param path
- * @param basePath
- * @return
- */
- private boolean doLoginInterceptor(String path,String basePath){
- path = path.substring(basePath.length());
- Set<String> notLoginPaths = new HashSet<>();
- //设置不进行登录拦截的路径:登录注册和验证码
- //notLoginPaths.add("/");
- notLoginPaths.add("/index");
- notLoginPaths.add("/signin");
- notLoginPaths.add("/login");
- notLoginPaths.add("/register");
- notLoginPaths.add("/kaptcha.jpg");
- notLoginPaths.add("/kaptcha");
- //notLoginPaths.add("/sys/logout");
- //notLoginPaths.add("/loginTimeout");
- if(notLoginPaths.contains(path)) return false;
- return true;
- }
- }
- 登录验证拦截
*/ @Controller @Component public class LoginInterceptor extends HandlerInterceptorAdapter {
Logger log = Logger.getLogger(LoginInterceptor.class);
/*@Autowired
UserService userService;*/
/*@Value("${IGNORE_LOGIN}")
Boolean IGNORE_LOGIN;*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
String basePath = request.getContextPath();
String path = request.getRequestURI();
// log.info("basePath:"+basePath); // log.info("path:"+path);
if(!doLoginInterceptor(path, basePath) ){//是否进行登陆拦截
return true;
}
// HttpSession session = request.getSession(); // int userID = 2; // UserInfo userInfo = sysUserService.getUserInfoByUserID(userID); // System.out.println(JsonUtil.toJson(userInfo)); // session.setAttribute(Constants.SessionKey.USER, userInfo);
//如果登录了,会把用户信息存进session
HttpSession session = request.getSession();
List<User> users = (List<User>) session.getAttribute("userList");
/*User userInfo = new User();
userInfo.setId(users.get(0).getId());
userInfo.setName(users.get(0).getName());
userInfo.setPassword(users.get(0).getPassword());*/
//开发环节的设置,不登录的情况下自动登录
/*if(userInfo==null && IGNORE_LOGIN){
userInfo = sysUserService.getUserInfoByUserID(2);
session.setAttribute(Constants.SessionKey.USER, userInfo);
}*/
if(users==null){
/*log.info("尚未登录,跳转到登录界面");
response.sendRedirect(request.getContextPath()+"signin");*/
String requestType = request.getHeader("X-Requested-With");
// System.out.println(requestType); if(requestType!=null && requestType.equals("XMLHttpRequest")){ response.setHeader("sessionstatus","timeout"); // response.setHeader("basePath",request.getContextPath()); response.getWriter().print("LoginTimeout"); return false; } else { log.info("尚未登录,跳转到登录界面"); response.sendRedirect(request.getContextPath()+"signin"); } return false; } // log.info("用户已登录,userName:"+userInfo.getSysUser().getUserName()); return true; }
/**
* 是否进行登陆过滤
* @param path
* @param basePath
* @return
*/
private boolean doLoginInterceptor(String path,String basePath){
path = path.substring(basePath.length());
Set<String> notLoginPaths = new HashSet<>();
//设置不进行登录拦截的路径:登录注册和验证码
//notLoginPaths.add("/");
notLoginPaths.add("/index");
notLoginPaths.add("/signin");
notLoginPaths.add("/login");
notLoginPaths.add("/register");
notLoginPaths.add("/kaptcha.jpg");
notLoginPaths.add("/kaptcha");
//notLoginPaths.add("/sys/logout");
//notLoginPaths.add("/loginTimeout");
if(notLoginPaths.contains(path)) return false;
return true;
}
}
2、WebConfig
- package com.fxy.interceptor;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
- import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
- import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
- import org.springframework.web.servlet.view.InternalResourceViewResolver;
- import org.springframework.web.servlet.view.JstlView;
- @Configuration
- public class WebConfig extends WebMvcConfigurerAdapter {
- //@Autowired
- //LogInterceptor logInterceptor;
- @Autowired
- LoginInterceptor loginInterceptor;
- /
- * 不需要登录拦截的url:登录注册和验证码
- */
- final String[] notLoginInterceptPaths = {"/signin","/login/","/index/","/register/","/kaptcha.jpg/","/kaptcha/"};//"/", "/login/", "/person/", "/register/", "/validcode", "/captchaCheck", "/file/", "/contract/htmltopdf", "/questions/", "/payLog/", "/error/" };
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- // 日志拦截器
- //registry.addInterceptor(logInterceptor).addPathPatterns("/");
- // 登录拦截器
- registry.addInterceptor(loginInterceptor).addPathPatterns("/**").excludePathPatterns(notLoginInterceptPaths);
- }
- @Override
- public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
- configurer.enable();
- }
- @Bean
- public InternalResourceViewResolver viewResolver() {
- InternalResourceViewResolver resolver = new InternalResourceViewResolver();
- resolver.setPrefix("/templates/");
- resolver.setSuffix(".html");
- resolver.setViewClass(JstlView.class);
- return resolver;
- }
- @Override
- public void addViewControllers(ViewControllerRegistry registry) {
- }
- }