struts2字符乱码

来源:互联网 发布:csgo弹道优化 编辑:程序博客网 时间:2024/05/17 23:31

编写全局拦截器,代码如下:


package cn.pgysoft.estates.interceptor;



import java.util.Iterator;


import javax.servlet.http.HttpServletRequest;


import org.apache.struts2.StrutsStatics;


import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;


public class CharacterEncodingInterceptor  extends AbstractInterceptor{

private static final long serialVersionUID = 1L;


private static final String GET_REQUEST = "get";

private static final String POST_REQUEST = "post";

private static final String UTF_ENCODE_FORMAT = "UTF-8";

private static final String ISO_ENCODE_FORMAT = "ISO8859-1";

@SuppressWarnings("unchecked")
@Override
public String intercept(ActionInvocation ai) throws Exception {
ActionContext ac = ai.getInvocationContext();
HttpServletRequest request = (HttpServletRequest)ac.get(StrutsStatics.HTTP_REQUEST);
if(GET_REQUEST.equalsIgnoreCase(request.getMethod())
|| POST_REQUEST.equalsIgnoreCase(request.getMethod())){
request.setCharacterEncoding(UTF_ENCODE_FORMAT);
}else{
Iterator<String[]> paramValues = request.getParameterMap().values().iterator();
while(paramValues.hasNext()){
String[] paramValue = (String[])paramValues.next();
for(int i=0;i<paramValue.length;i++){
paramValue[i] = new String(paramValue[i].getBytes(ISO_ENCODE_FORMAT), UTF_ENCODE_FORMAT);
}
}
}
return ai.invoke();
}

}



配置全局拦截器:

<struts>
<package name="struts-base" extends="struts-default">


<!-- <global-results> <result name="logout" type="redirect">/test/forwardToLogin!forward</result> 
<result name="error">/error.jsp</result> <result name="exception">/error.jsp</result> 
</global-results> <global-exception-mappings> <exception-mapping exception="java.lang.Exception" 
result="exception" /> </global-exception-mappings> -->


<interceptors>
<interceptor-stack name="financialsupervisionstack">
<interceptor-ref name="encodeInterceptor"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
<interceptor name="encodeInterceptor"
class="cn.pgysoft.estates.interceptor.CharacterEncodingInterceptor" />
</interceptors>
<!-- <default-interceptor-ref name="defaultStack" /> -->
<default-interceptor-ref name="financialsupervisionstack" />


</package>


</struts>