高手的存在,就是让服务10亿人的时候,你感觉只是为你一个人服务......

登录filter实现

目录
  1. 1. 在web.xml中增加对filer的配置
  2. 2. 新建一个filter类

最近想实现一个vo登录的功能,左思右想~~
嗯,应该是需要实现权限和登录认证的功能,看来是做写一个登录过滤器或者拦截器了。
项目使用的springmvc框架,查阅了一些资料,决定使用filter过滤器,拦截器与过滤器的区别

具体实现比较简单,配置配置,写个filter类就行了,如下:

  • 在web.xml中增加对filer的配置

    Alt text

  • 新建一个filter类

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
package com.focustech.fds.web.controller;

import java.io.IOException;
import java.util.Random;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
* 登录验证的filter实现
*
* @author lit
*/

public class SecurityServlet extends HttpServlet implements Filter {
private static final long serialVersionUID = 1L;
private FilterConfig config;
public static String[] EXCEPT_PAGE;

// 登录页面
public static final String LOGIN_PAGE = "/login";

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {


HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
request.setAttribute("version", new Random().nextInt());
BodyReaderHttpServletRequestWrapper requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
if (requestWrapper != null) {
request = requestWrapper;
}

// 排除一些jsp,css等文件
for (String exception : EXCEPT_PAGE) {
if (request.getRequestURI().endsWith(exception)) {

filterChain.doFilter(request, response);
return;
}
}

// String ref = request.getHeader("REFERER");
String ref = "REFERER";
HttpSession session = request.getSession(false);
String type = request.getHeader("X-Requested-With");
if (session == null || session.getAttribute("fdsUser") == null || ref == null || "".equals(ref)) {
if ("XMLHttpRequest".equalsIgnoreCase(type)) {// AJAX REQUEST
// PROCESS
response.setHeader("sessionstatus", "timeout");
return;
}
response.sendRedirect(request.getContextPath() + LOGIN_PAGE);
return;
}
filterChain.doFilter(request, response);
return;
}

public void init(FilterConfig filterConfig) throws ServletException {
String exception = filterConfig.getInitParameter("exception");
if (exception != null && !"".equals(exception)) {
EXCEPT_PAGE = exception.split(",");
}
config = filterConfig;
}

}

搞定~
以后凡是URL中带有/vo/的请求都走过滤器滤一滤!