java filter过滤器的配置
Web.xml配置,以下字段放在servlet下
<filter>
<filter-name>sessionFilter</filter-name>
<filter-class>com.FlyPig.util.filter_session</filter-class>
</filter>
<filter-mapping>
<filter-name>sessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
filter代码如下:起到了过滤登陆界面login.jsp和根路径以外的过滤
1 package com.FlyPig.util;
2
3 import java.io.IOException;
4
5 import javax.servlet.Filter;
6 import javax.servlet.FilterChain;
7 import javax.servlet.FilterConfig;
8 import javax.servlet.ServletException;
9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import javax.servlet.http.HttpSession;
14
15 public class filter_session implements Filter {
16 private String encoding;
17
18 public filter_session() {
19 }
20
21 public void init(FilterConfig filterconfig) throws ServletException {
22 encoding = "utf-8";
23 }
24
25 public void doFilter(ServletRequest servletrequest,
26 ServletResponse servletresponse, FilterChain filterchain)
27 throws IOException, ServletException {
28 servletrequest.setCharacterEncoding(encoding);
29 servletresponse.setCharacterEncoding(encoding);
30 HttpServletRequest req=(HttpServletRequest)servletrequest;
31 HttpSession session=req.getSession();
32 HttpServletResponse resp=(HttpServletResponse) servletresponse;
33
34 String url=req.getRequestURI();
35 System.out.println(url);
36 if(!url.equals("/FlyPig")&&!url.equals("/FlyPig/login.jsp")){
37 if(session.getAttribute("username")==null||session.getAttribute("username")==""){
38 resp.sendRedirect("login.jsp");
39 return ;
40 }
41 }
42
43
44 filterchain.doFilter(servletrequest, servletresponse);
45 }
46
47 public void destroy() {
48 }
49 }