浏览 1653 次
锁定老帖子 主题:完美解决中文乱码的问题
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (4)
|
|
---|---|
作者 | 正文 |
发表时间:2009-02-04
1 借助spring web.xml中增加 <filter> <filter-name>Set Character Encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf8</param-value> </init-param> </filter> <filter-mapping> <filter-name>Set Character Encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
配置文件即可,如果不用spring怎么办呢?有办法啊 <filter> <filter-name>encodingFilter</filter-name> <filter-class>com.rda.commons.filter.ChineseFilter</filter-class> <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> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
配置文件,然后呢,转码的过滤器就要自己写咯 package com.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; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * 创建人:金鑫 * 创建时间:2008-9-21 下午03:27:03 * 类作用:中文转码过滤器 * */ @SuppressWarnings("serial") public class ChineseFilter extends HttpServlet implements Filter { private FilterConfig filterConfig; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) { try { String encoding = filterConfig.getInitParameter("encoding"); //从WEB.xml配置文件中取出参数,这样我们可以通过配置修改编码格式. request.setCharacterEncoding(encoding);//设置请求的编码格式 filterChain.doFilter(request, response); } catch (ServletException sx) { filterConfig.getServletContext().log(sx.getMessage()); } catch (IOException iox) { filterConfig.getServletContext().log(iox.getMessage()); } } public void destroy() { } protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException { super.doGet(arg0, arg1); } protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException { super.doPost(arg0, arg1); } /** * @function 验证数据是否为空,如果为空则转换 * @param param * @return String */ public String checkNull(String param) { if (param == null || param.equals("")) { return ""; } else { return param; } } }
OK,完美解决掉啦。 其实解决乱码很简单的,就是通过过滤器来实现的,呵呵很简单吧? 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |