简单的超时登录验证功能

“泻水置平地,各自东西南北流”

项目中经常会用到超时登录的功能,比如说,登录上去之后,20分钟或者半个小时没有操作的话,再刷新就会提示重新登录;

实现

  1. 在web.xml中添加过滤器:
	<filter>
		<filter-name>permissionChecksFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<param-name>targetFilterLifecycle</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>permissionChecksFilter</filter-name>
		<url-pattern>*.jsp</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>permissionChecksFilter</filter-name>
		<url-pattern>/controller/*</url-pattern>
	</filter-mapping>
  1. 注册过滤器:
<!-- Session检查Filter -->
	<bean id="permissionChecksFilter" class="cn.arunner.web.filter.PermissionChecksFilter">
		<property name="cacheUtil" ref="cacheUtil"></property>
	</bean>
  1. 编写过滤器代码

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    	//获取主页面地址
        this.mainPageUrls = ((String)this.cacheUtil.getSysParamVal("main_page_urls", String.class, "")).split(";");
        //获取校验排除的地址
        this.excludeFilterUrls = ((String)this.cacheUtil.getSysParamVal("exclude_filter_check_urls", String.class, "")).split(";");
        //获取登录页面的地址
        this.loginPageUrl = (String)this.cacheUtil.getSysParamVal("login_page_url", String.class, "login.jsp");
        //获取没权限页面地址
        this.noPermissionPageUrl = (String)this.cacheUtil.getSysParamVal("no_permission_page_url", String.class, "error/nopermission.html");
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession(true);
        String path = req.getRequestURI();
        String projectname = req.getContextPath();
        //从session中虎丘当前用户信息,该用户信息在用户登录时存入,下面介绍
        Object userObj = session.getAttribute("http_session_atribute_current_user_info");
        if (!path.equals(projectname + "/") && !this.checkUrl(projectname, path, this.excludeFilterUrls)) {
        //如果从session中获取的对象为空,则提示登录超时
            if (userObj == null) {
                PrintWriter out = res.getWriter();
                out.write("<div style='margin-right: auto;margin-left: auto;width: 640px;margin-top: 100px;' align=\"center\"><div style='padding-top: 10px;padding-right: 14px;padding-bottom: 10px;padding-left: 14px;border: 1px solid #CCCCCC;'><div style='background-color: #F5F5F5;padding-top: 18px;padding-right: 40px;padding-bottom: 18px;padding-left: 40px;font-family: Tahoma;'><h1 style='font-size: 24px;font-weight: bolder;margin-bottom: 5px;text-align: center;padding-bottom: 10px;'>登录超时,5秒后将自动跳转<a target='_parent' href='" + projectname + "/" + this.loginPageUrl.split(";")[0] + "' style='color:orange'  onmouseleave='this.style.color=\"orange\"' onmouseover='this.style.color=\"red\"'>登录页面</a></h1></div></div></div><script>setTimeout('parent.location=\"" + projectname + "/" + this.loginPageUrl.split(";")[0] + "\"',5000)</script>");
            } else {
            	//判断当前用户是否用权限查看当前页面,如果没有,则提示无权限
                if (!this.checkUrl(projectname, path, this.mainPageUrls)) {
                //获取用户拥有的菜单信息
                    Map menus = (Map)session.getAttribute("http_session_atribute_all_menu_info");
                    String tempPath = path.substring(projectname.length() + 1);
                    if (menus.containsKey(tempPath) && menus.get(tempPath) == null) {
                        PrintWriter out = res.getWriter();
                        int noPermissionGoType = (Integer)this.cacheUtil.getSysParamVal("no_permission_go_type", Integer.class, 0);
                        if (noPermissionGoType == 0) {
                            out.print("<script>parent.location='" + projectname + "/" + this.noPermissionPageUrl + "';</script>");
                        } else {
                            out.print("<script>location='" + projectname + "/" + this.noPermissionPageUrl + "';</script>");
                        }

                        return;
                    }
                }

                chain.doFilter(request, response);
            }
        } else {
            chain.doFilter(request, response);
        }
    }
  1. 把用户信息存入缓存
			CurrentUserBean sysUser = (CurrentUserBean) map.get("currentSysUser");

			sysUser.setLogintime(new Date());
			sysUser.setIndex(index);
			sysUser.setSessionid(session.getId());
			sysUser.setServername(request.getLocalAddr() + ":"
					+ request.getLocalPort());
			sysUser.setExplorer(CommonUtils.getClientExplorerType(request));
			sysUser.setLoginip(request.getRemoteAddr());

			session.removeAttribute("http_session_atribute_current_user_info");
			//设置当前用户信息(这里也可以设置缓存的过期时间,不设置默认就是半个小时:session.setMaxInactiveInterval(30*60);//以秒为单位,即在没有活动30分钟后,session将失效)
			session.setAttribute("http_session_atribute_current_user_info",
					sysUser);
		//设置当前用户的权限信息
			session.setAttribute("http_session_atribute_all_menu_info",
					buildAllMenu((List) map.get("allMenuList")));
  1. 设置缓存过期时间的三种方式:
  • 在Tomcat中设置:
    在tomcat-7.0\conf\web.xml中设置,以下是tomcat7.0中默认配置:
<session-config>
<session-timeout>30</session-timeout>
</session-config>
  • 在工程的web.xml中设置(单位是分钟)
<session-config>
<session-timeout>15</session-timeout>
</session-config>
  • 在Java中设置
session.setMaxInactiveInterval(30*60);//以秒为单位,即在没有活动30分钟后,session将失效
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
学生宿舍管理系统登录功能一般包括以下步骤: 1. 用户打开登录页面,输入用户名和密码。 2. 系统验证用户名和密码是否正确,如果错误则提示用户重新输入。 3. 如果用户名和密码正确,则系统验证用户权限,如果用户权限不足则提示用户无法登录。 4. 如果用户权限足够,则系统记录用户登录状态,并跳转到对应的主页面。 下面是一个简单的学生宿舍管理系统登录功能的实现示例(使用Python Flask框架): ```python from flask import Flask, request, session, redirect, url_for, render_template app = Flask(__name__) app.secret_key = 'your_secret_key' # 假设有两个用户:admin和user,密码都是123456 users = { 'admin': '123456', 'user': '123456' } # 登录页面 @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] if username in users and users[username] == password: session['username'] = username return redirect(url_for('dashboard')) else: return render_template('login.html', error='用户名或密码错误') else: return render_template('login.html') # 主页面 @app.route('/dashboard') def dashboard(): if 'username' in session: return render_template('dashboard.html') else: return redirect(url_for('login')) # 退出登录 @app.route('/logout') def logout(): session.pop('username', None) return redirect(url_for('login')) if __name__ == '__main__': app.run(debug=True) ``` 在这个示例中,我们使用了Flask框架来实现登录功能。具体步骤如下: 1. 用户打开/login页面,输入用户名和密码。 2. 如果是POST请求,则获取用户名和密码,并验证是否正确。 3. 如果用户名和密码正确,则记录用户登录状态(使用Flask的session实现),并跳转到/dashboard页面。 4. 如果用户名和密码错误,则返回登录页面,并提示错误信息。 5. 如果是GET请求,则直接返回登录页面。 6. 在/dashboard页面中,如果用户已经登录,则展示主页面内容;如果用户未登录,则跳转到登录页面。 7. 当用户点击退出登录按钮时,清空用户登录状态,并跳转到登录页面。 需要注意的是,为了保护用户密码的安全性,我们应该将密码进行加密存储,并且在验证时比对加密后的结果。此外,为了防止恶意攻击,我们还需要设置一些安全措施,例如限制登录次数、设置登录超时等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值