有三种方法:
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>