解决post方式传递中文时乱码问题

为了避免中文乱码问题,需要在web.xml文件中增加编码过滤器,同时JSP页面编码设置为UTF-8,form表单的提交方式必须为post。

以下提供三种不同的解决方案:

 

一、SSM框架中:使用spring自带的编码过滤器

<filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> 
</filter> 
<filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> 
</filter-mapping>

 

二、Servlet中:使用自己编写的编码过滤器

web.xml

<filter><display-name>EncodingFilter</display-name><filter-name>EncodingFilter</filter-name><filter-class>jdbc.util.EncodingFilter</filter-class><init-param><param-name>pro_encoding</param-name><param-value>UTF-8</param-value></init-param>
</filter>
<filter-mapping><filter-name>EncodingFilter</filter-name><url-pattern>/*</url-pattern>
</filter-mapping>

EncodingFilter.java

public class EncodingFilter implements Filter {private String encoding = null;public EncodingFilter() {}public void destroy() {}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {System.out.println("encoding filter UTF-8");request.setCharacterEncoding(encoding);response.setCharacterEncoding(encoding);chain.doFilter(request, response);}public void init(FilterConfig fConfig) throws ServletException {encoding = fConfig.getInitParameter("pro_encoding");}
}

 

三、每次用到时手动转码:

String str = new String(request.getParameter("user").getBytes("iso-8859-1"), "UTF-8");

 

本文链接:https://my.lmcjl.com/post/12920.html

展开阅读全文

4 评论

留下您的评论.