springboot2中session超时,退到登录页面方式
作者:姚华军 时间:2022-12-23 03:30:14
session超时退到登录页面
最近发现使用的工程居然没有session超时机制,功能太欠缺了,现在把追加方法分享出来,里面有一些坑,大家自由使用。
1、首先在springboot中追加配置session的超时时间
注意springboot2的写法发生了改变
springboot2写法
server:
servlet:
session:
timeout: 1800s
springboot1写法
server:
session:
timeout: 1800s
2、登录成功接口中把用户信息追加session中
public ResponseEntity loginGo(HttpServletRequest request,String userName, String password) {
// 此处省略若干
HttpSession session = request.getSession(true);
session.setAttribute("username", user.getUserRemark());
}
3、在WebMvcConfig中配置拦截规则和重定向规则
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.addViewController("/loginOverTime").setViewName("loginOverTime");
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/**") // 表示拦截所有的请求
.excludePathPatterns("/login", "/loginOverTime", "/register", "/plugins/**", "/javascript/**", "/api/system/user/login","/img/**","/css/common/**");
// 表示拦截所有的请求
}
}
4、实现 * ,先跳转到超时页面
这里采用先跳转中转页面loginOverTime,然后再跳转到登录页面,如果直接跳转到登录页面只能在页面的内部iframe中跳转,无法这个页面跳转
@Component
public class LoginInterceptor implements HandlerInterceptor {
Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// 获取session
HttpSession session = request.getSession(true);
// 判断用户是否存在,不存在就跳转到登录界面
if(session.getAttribute("user") == null){
response.sendRedirect(request.getContextPath()+"/loginOverTime");
return false;
}else{
session.setAttribute("user", session.getAttribute("user"));
return true;
}
}
}
5、在超时页面让用户等待几秒钟
然后自动跳转到login页面,提升一下用户体验
{% extends 'common/layout' %}
{% block head %}
<link href="{{ request.contextPath }}/css/common/loginOverTime.css" rel="external nofollow" rel="stylesheet" />
{% endblock %}
{% block content %}
<body class="body_bg" >
<div class="show">
<div id="page">
<h1>抱歉,登录超时~</h1>
<h2> </h2>
<font color="#666666">由于您长期未操作为了保证您的信息安全请重新登录!</font><br /><br />
<div align="center" style="color: #666666">
将于<span>3</span>秒后跳转至<a href="javascript:void(0)" rel="external nofollow" >登录页</a>
</div>
</div>
</div>
</body>
{% endblock %}
{% block footer %}
<script type="text/javascript">
$(document).ready(function(){
// 关闭二级菜单
if(parent.window.closeSecondMenu != undefined){
parent.window.closeSecondMenu();
}
// 读秒显示
var second = 3;
// 设置定时任务
window.setInterval("changeTime()", 1000);
// 修改时间
changeTime = function(){
// 时间自动减1
second--;
// 修改页面上显示
$("span").html(second);
// 判断是否跳转登陆页
if(second == 0){
$("a").click();
}
}
// 跳转至登录页
$("a").click(function(){
//window.location.href="{{ request.contextPath }}/login" rel="external nofollow" ;
window.top.location="{{ request.contextPath }}/login";
});
});
</script>
{% endblock %}
这样就实现了sesseion超时退出的问题,大功告成
session超时的问题
最近在做SpringBoot的项目,用到了session,发现放置好session后,过一会就失效了,用下面发语句获取session失效时间,发现是60s
request.getSession().getMaxInactiveInterval();
去网上查找,发现大多解决问题的办法是 在启动类中main方法的下面加入以下方法来手动设置session失效时间
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer(){
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer Container) {
container.setSessionTimeout(1800);//单位为S
}
};
}
但是社会在发展,时代在进步,SpringBoot2.0以后已经不支持这种方式了
ps:可以在pom文件中查看你的SpringBooot版本。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
SpringBoot2.0以后的版本只需要在application.properties中加入以下配置就好
server.servlet.session.timeout = PT5H
这里重点解释一下 PT5H 意思是设置session失效的时间是5小时
通过查看setTimeouot的方法,这里要求传入Duration的实例
public void setTimeout(Duration timeout) {
this.timeout = timeout;
}
Duration是在Java8中新增的,主要用来计算日期差值
Duration是被final声明的,并且是线程安全的
Duration转换字符串方式,默认为正,负以-开头,紧接着P,以下字母不区分大小写
D :天 T:天和小时之间的分隔符 H :小时 M:分钟 S:秒 每个单位都必须是数字,且时分秒顺序不能乱
比如P2dt3m5s P3d pt3h
最后总结一下Duration最实用的一个功能其实是 between 方法,因为有很多时候我们需要计算两个日期之间的天数或者小时数,用这个就可以很方便的进行操作。
来源:https://blog.csdn.net/yhj_911/article/details/106680773
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android XML設置屏幕方向(android:screenOrientation)详解
java后端进行跨域的几种方式小结
SpringMVC中@RequestMapping注解用法实例
![](https://img.aspxhome.com/file/2023/5/129165_0s.jpg)
Android性能优化之ViewPagers + Fragment缓存优化
![](https://img.aspxhome.com/file/2023/7/94987_0s.png)
Android自定义view Path 的高级用法之搜索按钮动画
![](https://img.aspxhome.com/file/2023/7/138327_0s.gif)
C#分布式事务的超时处理实例分析
Java实现获取指定个数的不同随机数
Spring Boot中@ConditionalOnProperty的使用方法
详解SpringBoot缓存的实例代码(EhCache 2.x 篇)
![](https://img.aspxhome.com/file/2023/1/77931_0s.jpg)
SpringCloud实现灰度发布的方法步骤
![](https://img.aspxhome.com/file/2023/6/83566_0s.png)
Android开发笔记之:用Enum(枚举类型)取代整数集的应用详解
![](https://img.aspxhome.com/file/2023/2/139612_0s.gif)
详解Spring Boot Oauth2缓存UserDetails到Ehcache
三种Android单击事件onclick的实现方法
Maven install 报错"程序包不存在"问题的解决方法
![](https://img.aspxhome.com/file/2023/1/76621_0s.png)
Java设计模式之GOF23全面讲解
![](https://img.aspxhome.com/file/2023/8/78228_0s.jpg)
C#双缓冲实现方法(可防止闪屏)
Java中的关键字_动力节点Java学院整理
![](https://img.aspxhome.com/file/2023/6/91536_0s.png)
C#实现伪装文件夹功能
![](https://img.aspxhome.com/file/2023/0/76410_0s.png)