Spring MVC过滤器-登录过滤的代码实现
程序员文章站
2024-03-09 10:47:41
一个非常简单的登录权限拦截器,具体代码如下:
以下代码是继承onceperrequestfilter实现登录过滤的代码:
/**
*
* @...
一个非常简单的登录权限拦截器,具体代码如下:
以下代码是继承onceperrequestfilter实现登录过滤的代码:
/** * * @author geloin * @date 2012-4-10 下午2:37:38 */ package com.test.spring.filter; import java.io.ioexception; import java.io.printwriter; import javax.servlet.filterchain; import javax.servlet.servletexception; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import org.springframework.web.filter.onceperrequestfilter; /** * 登录过滤 * * @author geloin * @date 2012-4-10 下午2:37:38 */ public class sessionfilter extends onceperrequestfilter { /* * (non-javadoc) * * @see * org.springframework.web.filter.onceperrequestfilter#dofilterinternal( * javax.servlet.http.httpservletrequest, * javax.servlet.http.httpservletresponse, javax.servlet.filterchain) */ @override protected void dofilterinternal(httpservletrequest request, httpservletresponse response, filterchain filterchain) throws servletexception, ioexception { // 不过滤的uri string[] notfilter = new string[] { "login.html", "index.html" }; // 请求的uri string uri = request.getrequesturi(); // uri中包含background时才进行过滤 if (uri.indexof("background") != -1) { // 是否过滤 boolean dofilter = true; for (string s : notfilter) { if (uri.indexof(s) != -1) { // 如果uri中包含不过滤的uri,则不进行过滤 dofilter = false; break; } } if (dofilter) { // 执行过滤 // 从session中获取登录者实体 object obj = request.getsession().getattribute("logineduser"); if (null == obj) { // 如果session中不存在登录者实体,则弹出框提示重新登录 // 设置request和response的字符集,防止乱码 request.setcharacterencoding("utf-8"); response.setcharacterencoding("utf-8"); printwriter out = response.getwriter(); string loginpage = "...."; stringbuilder builder = new stringbuilder(); builder.append("<script type=\"text/javascript\">"); builder.append("alert('网页过期,请重新登录!');"); builder.append("window.top.location.href='"); builder.append(loginpage); builder.append("';"); builder.append("</script>"); out.print(builder.tostring()); } else { // 如果session中存在登录者实体,则继续 filterchain.dofilter(request, response); } } else { // 如果不执行过滤,则继续 filterchain.dofilter(request, response); } } else { // 如果uri中不包含background,则继续 filterchain.dofilter(request, response); } } }
写完过滤器后,需要在web.xml中进行配置:
<filter> <filter-name>sessionfilter</filter-name> <filter-class>com.test.spring.filter.sessionfilter</filter-class> </filter> <filter-mapping> <filter-name>sessionfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇: Java执行JavaScript代码