一个非常简单的登录权限拦截器,具体代码如下:
以下代码是继承OncePerRequestFilter实现登录过滤的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
/** * * @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中进行配置:
1
2
3
4
5
6
7
8
|
< 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 > |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://blog.csdn.net/geloin/article/details/7445441