使用字符编码Filter
package com.helloweenvsfei.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 CharacterEncodingFilter implements Filter { private String characterEncoding; private boolean enabled; @Override public void init(FilterConfig config) throws ServletException { characterEncoding = config.getInitParameter("characterEncoding"); enabled = "true".equalsIgnoreCase(characterEncoding.trim()) || "1".equalsIgnoreCase(characterEncoding.trim()); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (enabled || characterEncoding != null) { request.setCharacterEncoding(characterEncoding); response.setCharacterEncoding(characterEncoding); } chain.doFilter(request, response); } @Override public void destroy() { characterEncoding = null; }}
web.xml 配置如下
characterEncodingFilter com.helloweenvsfei.filter.CharacterEncodingFilter characterEncoding UTF-8 enable true characterEncodingFilter /*
注意:页面编码方式必须一致。另外如果使用GET表单提交。需要修改Tomcat /conf/server.xml 里的URIEncoding 修改代码如下
基本所有的javaWeb程序都用该Filter。
附:characteEncoding.jsp验证编码器
1 <%@ page language="java" contentType="text/html; charset=UTF-8"%> 2 3 4 5 6Insert title here 7 16 17 1819 您输入了:20 ${ param.text }2122