java web filter 之一 基础实现
filter是什么
一个Filter处理一个jsp:
实现filter要实现javax.servlet包下的filter接口,本例子实现的是设置所有jsp也的字符编码
package com.tgb.drp.util.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 CharsetEncodingFilter implements Filter {
private String encodeString;
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse
response,
FilterChain chain) throws IOException, ServletException
{
System.out.println("begin");
// 设置字符集
request.setCharacterEncoding(encodeString);
//继续向下执行,如果还有其他filter继续调用其他filter,没有的话将消息发送给服务器或客户端
chain.doFilter(request, response);
System.out.println("end");
}
@Override
public void init(FilterConfig filterConfig) throws
ServletException {
//
encodeString=filterConfig.getInitParameter("encoding");
}
}
写好filter类后,需要在配置文件中设置对哪些request和response进行过滤处理,本例子设置对所有的jsp页进行处理,在web.xml的web-app节点下,配置好后,可以写一个jsp页进行测试了。
多个filter处理一个jsp页
package com.tgb.drp.util.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 AuthenticationFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse
response,
FilterChain chain) throws IOException, ServletException
{
//控制用户访问权限
HttpServletRequest req=(HttpServletRequest)request;
HttpServletResponse res=(HttpServletResponse)response;
HttpSession session=req.getSession();
if(session.getAttribute("user_info")!=null){
chain.doFilter(request, response);
}else{
res.sendRedirect(req.getContextPath()+"/error.html");
}
}
@Override
public void init(FilterConfig filterConfig) throws
ServletException {
}
}
然后在配置文件里继续进行下配置,代码如下
≤?xml version="1.0" encoding="UTF-8"?≥
≤web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"≥
≤session-config≥
≤session-timeout≥60≤/session-timeout≥
≤/session-config≥
≤/web-app≥
好了到此就可以设置两个filter对一个jsp页进行处理了,当启动tomcat,访问响应的jsp页时,设置的filter就会起作用。