encodingfilter.java

来自「jsp 应用开发技术光盘 是《jsp应用开发技术》这本书的源代码」· Java 代码 · 共 48 行

JAVA
48
字号
package ch17;

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() {

	}

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?