编写拦截器
package blog.csdn.net.mchenys.intercept;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/**
* 解决请求乱码问题
* @author mChenys
*
*/
public class EncodingIntereptor extends AbstractInterceptor {
private static final long serialVersionUID = 6826256332417695666L;
@Override
public String intercept(ActionInvocation invo) throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
if (request.getMethod().equalsIgnoreCase("post")) {
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
Iterator<String[]> iterval = request.getParameterMap().values().iterator();
while (iterval.hasNext()) {
String[] parames = iterval.next();
for (int i = 0; i < parames.length; i++) {
try {
parames[i] = new String(parames[i].getBytes("iso8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
return invo.invoke();
}
}
编辑struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="test" extends="json-default,struts-default" namespace="/test">
<!-- 配置拦截器 -->
<interceptors>
<interceptor name="encoding" class="blog.youkuaiyun.com.mchenys.intercept.EncodingIntereptor"></interceptor>
<!-- 定义拦截器栈 -->
<interceptor-stack name="myStack">
<!-- 引入自定义的拦截器 -->
<interceptor-ref name="encoding"/>
<!-- 引入默认的拦截器 -->
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<action name="*" class="blog.youkuaiyun.com.mchenys.action.TestAction" method="{1}">
<!-- 引入拦截器栈 -->
<interceptor-ref name="myStack"/>
<!-- <result name="jump" type="chain">demo2</result> -->
<result type="json">
<param name="root">dataMap</param>
<!-- 是否去掉返回值为NULL的properties -->
<param name="excludeNullProperties">true</param>
</result>
</action>
</package>
</struts>
搞定~~