[原]过滤器解决Servlet中文乱码
2015-05-20 19:57
513 查看
一、问题描述:Servlet接收来自JSP页面的中文参数时,在Servlet文件中编写输出语句,控制台输出中文乱码。
(乱码问题以前经常碰到,改编码格式相当麻烦)
利用过滤器解决方法可以一次性解决问题
1.过滤器在此方法的作用:每当程序要运行Servlet文件之前,都要去执行过滤器文件;在过滤器文件中编写要在Servlet文件之前运行的代码。
2.实现过程:分为两步(1.编写过滤器类。2.编写配置文件)
1.过滤器类
(1).在src文件下建个包 com.filter
(2).在此包下新建类 SetCharacterEncodingFilter
(3).代码:
2.配置web.xml文件(/WebRoot/WEB-INF/web.xml)
(乱码问题以前经常碰到,改编码格式相当麻烦)
利用过滤器解决方法可以一次性解决问题
1.过滤器在此方法的作用:每当程序要运行Servlet文件之前,都要去执行过滤器文件;在过滤器文件中编写要在Servlet文件之前运行的代码。
2.实现过程:分为两步(1.编写过滤器类。2.编写配置文件)
1.过滤器类
(1).在src文件下建个包 com.filter
(2).在此包下新建类 SetCharacterEncodingFilter
(3).代码:
package com.filter; //1、新建一个SetCharacterEncodingFilter.java的类:(并在web.xml里配置好)即可以添加中文数据 import java.io.IOException; import javax.servlet.*; public class SetCharacterEncodingFilter implements Filter{ protected String encoding = null; protected FilterConfig filterConfig = null; protected boolean ignore = true; public void destroy() { this.encoding = null; this.filterConfig = null; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (ignore || (request.getCharacterEncoding() == null)) { String encoding = selectEncoding(request); if (encoding != null) request.setCharacterEncoding(encoding); } chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; // 获取初始化参数 this.encoding = filterConfig.getInitParameter("encoding"); String value = filterConfig.getInitParameter("ignore"); if (value == null) { this.ignore = true; } else if (value.equalsIgnoreCase("true")) { this.ignore = true; } else if (value.equalsIgnoreCase("yes")) { this.ignore = true; } else this.ignore = false; } protected String selectEncoding(ServletRequest request) { return (this.encoding); } }
2.配置web.xml文件(/WebRoot/WEB-INF/web.xml)
<!--过滤器,将此代码放在</web-app>之上--> <filter> <filter-name>Set Character Encoding</filter-name> <filter-class>com.filter.SetCharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <!--制定过滤器映射--> <filter-mapping> <filter-name>Set Character Encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
相关文章推荐
- Servlet 中文乱码解决【使用过滤器】
- Servlet中通过过滤器实现统一的手动编码(解决中文乱码)
- Servlet中通过过滤器实现统一的手动编码(解决中文乱码)
- Servlet中通过过滤器实现统一的手动编码(解决中文乱码)
- 过滤器解决Servlet中文乱码
- 备忘录:用servlet过滤器解决JSP中文乱码
- 解决中文乱码用spring经典编码过滤器org.springframework.web.filter.CharacterEncodingFilter
- servlet输出js脚本到页面时的中文会乱码的解决方法
- struts使用过滤器解决中文乱码问题
- Servlet——解决全站乱码问题(过滤器)
- Servlet学习笔记—request获得参数中文乱码问题解决
- 使用过滤器解决中文乱码问题
- jsp和servlet操作mysql中文乱码问题的解决办法
- JavaEE-----------servlet之解决中文乱码问题
- java ---servlet解决中文乱码的几种办法
- 解决中文乱码的过滤器
- Servlet中文乱码解决
- jsp用过滤器解决中文乱码问题的方法
- 使用filter(过滤器)处理JSP和servlet的中文乱码
- 心得7--Servlet的中文、数字输出乱码解决