登录验证过滤器
LoginCheckFilter.java
1 package org.guangsoft.filter;
2
3 import java.io.IOException;
4 import java.util.ArrayList;
5 import java.util.List;
6
7 import javax.servlet.Filter;
8 import javax.servlet.FilterChain;
9 import javax.servlet.FilterConfig;
10 import javax.servlet.ServletException;
11 import javax.servlet.ServletRequest;
12 import javax.servlet.ServletResponse;
13 import javax.servlet.http.HttpServletRequest;
14 import javax.servlet.http.HttpServletResponse;
15
16 import org.guangsoft.bean.Users;
17
18 import com.google.gson.Gson;
19
20 public class LoginCheckFilter implements Filter
21 {
22 @Override
23 public void init(FilterConfig filterconfig) throws ServletException
24 {
25 }
26
27 @Override
28 public void doFilter(ServletRequest servletrequest,
29 ServletResponse servletresponse, FilterChain filterchain)
30 throws IOException, ServletException
31 {
32 HttpServletRequest request = (HttpServletRequest) servletrequest;
33 HttpServletResponse response = (HttpServletResponse) servletresponse;
34 String option = request.getParameter("option");
35 Users user = (Users) request.getSession().getAttribute("user");
36 List<String> list = new ArrayList<String>();
37 list.add("login");
38 list.add("getUsers");
39 if (user != null || list.contains(option))
40 {
41 filterchain.doFilter(servletrequest, servletresponse);
42 }
43 else
44 {
45 response.getWriter().print(new Gson().toJson("login"));
46 }
47 }
48
49 @Override
50 public void destroy()
51 {
52 }
53 }
web.xml
1 <filter>
2 <filter-name>LoginCheckFilter</filter-name>
3 <filter-class>org.guangsoft.filter.LoginCheckFilter</filter-class>
4 </filter>
5 <filter-mapping>
6 <filter-name>LoginCheckFilter</filter-name>
7 <url-pattern>*.action</url-pattern>
8 </filter-mapping>