标签:
一、自定义的类(注意其中的属性,web.xml中的配置就是根据这个类的) import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Iterator; /** * Filter - 编码格式转换 */ public class EncodingConvertFilter extends OncePerRequestFilter { /** 原编码格式:与web.xml文件中对应设置 */ private String fromEncoding = "ISO-8859-1"; /** 目标编码格式 :与web.xml文件中对应设置*/ private String toEncoding = "UTF-8"; @SuppressWarnings("unchecked") @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (request.getMethod().equalsIgnoreCase("GET")) { for (Iterator<String[]> iterator = request.getParameterMap().values().iterator(); iterator.hasNext();) { String[] parames = iterator.next(); for (int i = 0; i < parames.length; i++) { try { parames[i] = new String(parames[i].getBytes(fromEncoding), toEncoding); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } filterChain.doFilter(request, response); } /** * 获取原编码格式 * @return 原编码格式 */ public String getFromEncoding() { return fromEncoding; } /** * 设置原编码格式 * @param fromEncoding * 原编码格式 */ public void setFromEncoding(String fromEncoding) { this.fromEncoding = fromEncoding; } /** * 获取目标编码格式 * @return 目标编码格式 */ public String getToEncoding() { return toEncoding; } /** * 设置目标编码格式 * @param toEncoding * 目标编码格式 */ public void setToEncoding(String toEncoding) { this.toEncoding = toEncoding; } } 二、web.xml <!--springmvc自定的过滤post--> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <!-- 其中encoding用来设置编码格式,forceEncoding用来设置是否理会 request.getCharacterEncoding()方法,设置为true则强制覆盖之前的编码格式 --> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <!--自定义过滤get请求,如果tomcat中server.xml文件中配置了URIEncoding="UTF-8",可以不需要--> <filter> <filter-name>encodingConvertFilter</filter-name> <filter-class>home.xxx.filter.EncodingConvertFilter</filter-class> <init-param> <param-name>fromEncoding</param-name> <param-value>ISO-8859-1</param-value> </init-param> <init-param> <param-name>toEncoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping>
161912、工具类:spring+springmvc自定义编码转换
标签:
原文地址:http://www.cnblogs.com/zrbfree/p/5863667.html