SpringBoot 拦截器--只允许进入登录注册页面,没登录不允许查看其它页面
SpringBoot注册登录(三):注册--验证账号密码是否符合格式及后台完成注册功能点击打开链接
SpringBoot注册登录(四):登录功能--密码错误三次,需要等待2分钟才能登录,固定时间内不能登录点击打开链接
SpringBoot注册登录(五):登录功能--Scheduling Tasks定时作业,用于某个时间段允许/不允许用户登录点击打开链接
SpringBoot--mybatis--ajax--模态框--log:注册、登录、拦截器、文件系统源代码点击打开链接
直接运行程序,就会加载拦截器了。这个拦截器在没登录前只会放行登录注册、验证码的请求
一、先在启动类加上注解(如果使用了下面步骤的代码程序执行失败的话)
- @ComponentScan
- @EnableAutoConfiguration
- @EnableScheduling
- @Configuration
@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;
- }
- }
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;
}
}
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) {
- }
- }
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) { }
}
SpringBoot 拦截器--只允许进入登录注册页面,没登录不允许查看其它页面的更多相关文章
- Java结合SpringBoot拦截器实现简单的登录认证模块
Java结合SpringBoot拦截器实现简单的登录认证模块 之前在做项目时需要实现一个简单的登录认证的功能,就寻思着使用Spring Boot的拦截器来实现,在此记录一下我的整个实现过程,源码见文章 ...
- Springboot 拦截器配置(登录拦截)
Springboot 拦截器配置(登录拦截) 注意这里环境为springboot为2.1版本 1.编写拦截器实现类,实现接口 HandlerInterceptor, 重写里面需要的三个比较常用的方 ...
- 【SpringBoot】SpringBoot拦截器实战和 Servlet3.0自定义Filter、Listener
=================6.SpringBoot拦截器实战和 Servlet3.0自定义Filter.Listener ============ 1.深入SpringBoot2.x过滤器Fi ...
- springboot拦截器HandlerInterceptor详解
Web开发中,我们除了使用 Filter 来过滤请web求外,还可以使用Spring提供的HandlerInterceptor(拦截器). HandlerInterceptor 的功能跟过滤器类似,但 ...
- SpringBoot 拦截器 && 拦截之后返回前台自定义格式
1.加入 阿里的 json jar包 <!--json jar相关jar包--> <dependency> <groupId>com.fasterxml.jacks ...
- SpringBoot拦截器中Bean无法注入(转)
问题 这两天遇到SpringBoot拦截器中Bean无法注入问题.下面介绍我的思考过程和解决过程: 1.由于其他bean在service,controller层注入一点问题也没有,开始根本没意识到Be ...
- SpringBoot拦截器中无法注入bean的解决方法
SpringBoot拦截器中无法注入bean的解决方法 在使用springboot的拦截器时,有时候希望在拦截器中注入bean方便使用 但是如果直接注入会发现无法注入而报空指针异常 解决方法: 在注册 ...
- Springboot拦截器未起作用
之前遇到要使用springboot拦截器却始终未生效的状况,查了网上的博客,大抵都是@Component,@Configuration注解未加,或是使用@ComponentScan增加包扫描,但是尝试 ...
- SpringBoot拦截器中service或者redis注入为空的问题
原文:https://my.oschina.net/u/1790105/blog/1490098 这两天遇到SpringBoot拦截器中Bean无法注入问题.下面介绍我的思考过程和解决过程: 1.由于 ...
随机推荐
- sqlalchemy配置多读写库多连接后的关系设置
前言 一般来说,解决sqlalchemy 连接多个库的最简单的方式是新建两个或多个db.session 相互没有关联,modle配置不同的db.session来连接,这样的话,relationship ...
- 构建一个.net的干货类库,以便于快速的开发 - 加密
在开发程序的时候,加密是一个程序一个必须的功能,基本上任何程序都会用到加密,而不同的加密方式又适应不同需求,有些加密是不可逆的,最常见是用于用户密码的加密,因为很多时候程序里面不该显示出用户的明文密码 ...
- log4j2异步日志解读(二)AsyncLogger
前文已经讲了log4j2的AsyncAppender的实现[log4j2异步日志解读(一)AsyncAppender],今天我们看看AsyncLogger的实现. 看了这个图,应该很清楚AsyncLo ...
- 配置Tomcat && Http简介
WEB环境搭建 1. Web服务器 Web服务器主要用来接收客户端发送的请求和响应客户端请求. 作为JavaWeb程序来说,还需要有Servet容器,容器的主要作用就是调用java程序处理用户发送的请 ...
- arduino 字符解析
Arduino String.h库函数详解 此库中包含1 charAT()2 compareTo()3 concat()4 endsWith()5 equals()6 equalslgnoreCa ...
- 转载pcb设计详细版
http://www.51hei.com/bbs/dpj-52438-1.html 详细的altium designer制作PCB步骤,按照步骤一步步的学习就会自己制作PCB模型 目 录 实验三 层 ...
- python自动化--语言基础三字典、函数、全局/局部变量
字典 dict1 = {,'class':'first'} print(dict1.keys()) #打印所有的key值 print(dict1.values()) #打印所有的values值 pri ...
- 上传一个npm包
1.先创建一个npm账号 https://www.npmjs.com/signup 2.在cmd里输入命令进入项目文件夹 3.使用npm init 命令创建一个package.json(确保nodej ...
- python学习笔记(5)—— tuple 本质探究
>>> t=(1,2,3,['a','b','c'],4,5) >>> t[3][0]='x' >>> t (1, 2, 3, ['x', 'b' ...
- SQL SERVER 2008 在某表中新增一列时失败
背景:新增列语句如:“alter table 表名 add 列名 float default 0 with values”(用VS2010做网站,这句话是在C#代码里执行的) 报错提示: 警告: 已经 ...