使用Filter目的是让所有的页面都先通过一个文件处理一下。
实例1:EncodingFilter.java -关于编码的Filter
package com.english.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class EncodingFilter implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException,
ServletException {
arg0.setCharacterEncoding("UTF-8");
arg1.setCharacterEncoding("UTF-8");
arg2.doFilter(arg0, arg1);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
同时,要在web.xml中进行Filter 的配置:
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>com.english.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>//*</url-pattern>
</filter-mapping>
实例2 SessionFilter.java -关于Session 判断的一个Filter,这个文件要过滤一些文件,而让另一些文件通过,所以加了url 的判断。
package com.english.filter;
import java.io.IOException;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionFilter implements Filter {
private static String[] passUrls = { "login.view", "login.do", "logout.do", "index.do", "index.view",
"register.view", "register.do", ".jpg", ".js", "testId.do", ".css" };
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException,
ServletException {
HttpServletResponse resp = (HttpServletResponse) arg1;
HttpServletRequest req = (HttpServletRequest) arg0;
HttpSession session = req.getSession();
String url = req.getRequestURI();
boolean pass = false;
for (String passUrl : passUrls) {
if (url.endsWith(passUrl) || session.getAttribute("englishUser") != null) {
pass = true;
}
}
if (pass) {
chain.doFilter(arg0, arg1);
} else {
req.getRequestDispatcher("/login.view").forward(arg0, arg1);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
posted on 2008-06-26 23:12
BlueSunshine 阅读(196)
评论(0) 编辑 收藏 所属分类:
学习心得