1. 程式人生 > >過濾器程式碼

過濾器程式碼

package filter;

import java.io.IOException;

import javax.servlet.*;

public class EncodingFilter implements Filter {

protected String encoding = null;

protected FilterConfig config;

public void init(FilterConfig filterConfig) throws ServletException {

this.config = filterConfig;

// 得到在 web.xml 中配置的編碼

this.encoding = filterConfig.getInitParameter("Encoding");

}

public void doFilter(

ServletRequest request,

ServletResponse response,

FilterChain chain)

throws IOException, ServletException {

if (request.getCharacterEncoding() == null) {

// 得到指定的編碼

String encode = getEncoding();

if (encode != null) {

//設定 request 的編碼

request.setCharacterEncoding(encode);

response.setCharacterEncoding(encode);

}

}

chain.doFilter(request, response);

}

protected String getEncoding() {

return encoding;

}

public void destroy() {

}

}