解决乱码问题,一般情况下三种方法:
1.contentType="text/html;charset=utf-8";
2.new String(str.getBytes("ISO-8859-1"),"utf-8");
3.request.setCharacterEncoding("utf-8");
第一种方法用在jsp页面的page指令中,保证显示的编码格式。例如:
<%@ page language="java" contentType="text/html;charset=utf-8"%>
第二种方法用于用一种新的编码格式对原来的字符串重新编码,例如:
new String("abc".getBytes("ISO-8859-1"),"utf-8");
第三种方法,用于对request中的编码进行设置。struts中便可采用这种方法,解决中文乱码问题。
1.新建一个类文件:
package com.yourcompany.struts;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionServlet;
public class CodeFilter extends ActionServlet {
protected void process(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
super.process(request, response);
}
}
2.将web.xml中的对应的ActionServlet修改为上述的类即可。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.4"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>com.yourcompany.struts.CodeFilter</servlet-class>
<!--
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
-->
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
3.重新部署应用,解决乱码问题就这么简单!