1、创建过滤器Java类
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class SetCharacterEncodingFilter implements Filter{
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
//传递控制到下一个过滤器
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
2
、web.xml配置
不适用StrutsPrepareAndExecuteFilter,将所用过滤器放置在StrutsPrepareFilter和StrutsExecuteFilter之间,编码设置为UTF-8。2.1.3版本后不用ActionContextCleanUp
<?xml version="1.0" encoding="UTF-8"?><!--必要-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<filter>
<filter-name>StrutsPrepareFilter</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>StrutsPrepareFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>SetCharacterEncoding</filter-name>
<filter-class>com.flowers.with.utils.SetCharacterEncodingFilter</filter-class><!--根据创建过滤器所在的位置填写-->
</filter>
<filter-mapping>
<filter-name>SetCharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>StrutsExecuteFilter</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>StrutsExecuteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
3、struts.xml配置编码设置为UTF-8
<?xml version="1.0" encoding="UTF-8"?>
4、JSP配置,JSP页面编码设置为UTF-8,form提交的方法设置成post,默认为get
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <!--必要-->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
String path = request.getContextPath();
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!--必要-->
<title>Register</title>
</head>
<body style="background-image: url(../IMAGE/repeat1.jpg)">
<form action="register" id="registerForm" method="post"><!--方法设置为post-->
</form>
</body>
</html>