解决中文乱码( jsp表单提交中文时出现乱码)

来源:互联网 发布:仿牌外贸seo 编辑:程序博客网 时间:2024/06/05 15:21

有三种方法:

   1.建立一个filter中文解决乱码

   2.Struts2在struts.xml中修改默认的编码设定

   3.用Spring解决中文乱码

   4.直接在jsp中修改解决

 

   1.建立一个filter解决乱码

1)建立一个filter类src/util/SetCharacterEncodingFilter.java

复制代码
package util;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.UnavailableException;     public class SetCharacterEncodingFilter implements Filter {   
    public void destroy() {    }       public void doFilter(ServletRequest request, ServletResponse response,    FilterChain chain)throws IOException, ServletException {
    //设置编码
    request.setCharacterEncoding("gb2312");    // 传递控制到下一个过滤器    chain.doFilter(request, response);    }    public void init(FilterConfig filterConfig) throws ServletException {    }}
复制代码

 

2.修改web.xml,添加filter和filter-mapping(在struts的FilterDispatcher映射之前添加)

复制代码
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5"     xmlns="http://java.sun.com/xml/ns/javaee"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">    
     <!--      -->
   <filter>        <filter-name>Set Character Encoding</filter-name>         <filter-class>util.SetCharacterEncodingFilter</filter-class>     </filter>     <filter-mapping>         <filter-name>Set Character Encoding</filter-name>        <url-pattern>/*</url-pattern>     </filter-mapping>        web-app>
复制代码

 

 

   2.Struts2在struts.xml中修改默认编码(Struts2_2.16以上)

<struts>    <constant name="struts.i18n.encoding" value="gbk"></constant></struts>

 

 

   3.用Spring解决中文乱码

修改web.xml,添加filter和filter-mapping(在struts的FilterDispatcher映射之前添加)

复制代码
<filter>        <filter-name>encodingFilter</filter-name>        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>        <init-param>            <param-name>encoding</param-name>            <param-value>GBK</param-value>        </init-param>    </filter>        <filter-mapping>        <filter-name>encodingFilter</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>
复制代码

 

 

 

   4.直接在jsp中修改解决

复制代码
<%@ page contentType="text/html; charset=gb2312"%><html><head>    <title>JSP的中文处理</title><meta http-equiv="Content-Type" content="text/html; charset=gb2312"></head><body><%   String s=new String(request.getParameter("name").getBytes("ISO-8859-1"),"gb2312") ;   out.print(s);%></body></html>
复制代码
漫人生路上,该放下的要放下,往事如过眼烟云,浅笑则安...

转载于:http://www.cnblogs.com/J-wym/p/3284182.html
0 0
原创粉丝点击