有时候难免需要传递中文参数到action,页面设置utf-8,但是由于tomcat默认字符编码为ISO8859-1
1、当你不使用spring的时候,那么我们可以写一个拦截器去转化所有传递来的请求参数,并将其转化为utf-8
import java.io.UnsupportedEncodingException;
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 EncodingInterceptor extends AbstractInterceptor {//集成拦截器的一个实现类,此实现类只需要写主要的拦截方法
public String intercept(ActionInvocation arg0) throws Exception {
ActionContext actionContext = arg0.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
System.out.println("Encoding Intercept...");
/**
* 此方法体对GET 和 POST方法均可
*/
if (request.getMethod().compareToIgnoreCase("post") >= 0) {//如果是post请求
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
Iterator iter = request.getParameterMap().values().iterator();
while (iter.hasNext()) {
String[] parames = (String[]) iter.next();
for (int i = 0; i < parames.length; i++) {
try {
System.out.println("----->"+parames[i]);
parames[i] = new String(parames[i].getBytes("iso8859-1"), "utf-8");// 此处utf-8与页面编码一样
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
return arg0.invoke();
}
}
然后在struts中配置拦截器
<interceptor name="Encoding" class="com.dbs.action.interceptor.EncodingInterceptor"/>
并将其放入拦截器栈中,加入默认拦截器
<interceptor-stack name="loginStack">
<interceptor-ref name="Login"/>
<interceptor-ref name="Encoding"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
<span style="white-space:pre"> </span> <default-interceptor-ref name="loginStack"/>
2.、当你使用到spring的时候那就更简单了,spring就是一个大容器,它可以帮我们去管理字符集 Spring中的字符集过滤器可以很方便的为我们解决项目中出现的中文乱码问题,而且使用方法也很简单,只需要在web.xml文件中配置一下该过滤器,设置两个重要的参数(encoding和forceEncoding)即可:
<!-- 配置请求过滤器,编码格式设为UTF-8,避免中文乱码-->
<filter>
<filter-name>springUtf8Encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>springUtf8Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
其中
org.springframework.web.filter.CharacterEncodingFilter
这个类我们可以查看
public class CharacterEncodingFilterextends OncePerRequestFilter {
private String encoding;
private boolean forceEncoding = false;
/**
* Set the encoding to usefor requests. This encoding will be passed into a
* {@link javax.servlet.http.HttpServletRequest#setCharacterEncoding} call.
* <p>Whether this encoding will overrideexisting request encodings
* (and whether it will beapplied as default response encoding as well)
* depends on the {@link #setForceEncoding "forceEncoding"} flag.
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
/**
* Set whether theconfigured {@link #setEncoding encoding} of this filter
* is supposed to overrideexisting request and response encodings.
* <p>Default is "false", i.e. do notmodify the encoding if
* {@link javax.servlet.http.HttpServletRequest#getCharacterEncoding()}
* returns a non-null value.Switch this to "true" to enforce the specified
* encoding in any case,applying it as default response encoding as well.
* <p>Note that the response encoding will onlybe set on Servlet 2.4+
* containers, sinceServlet 2.3 did not provide a facility for setting
* a default responseencoding.
*/
public void setForceEncoding(boolean forceEncoding) {
this.forceEncoding = forceEncoding;
}
@Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response,FilterChain filterChain)
throws ServletException, IOException {
if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
request.setCharacterEncoding(this.encoding);
if (this.forceEncoding) {
response.setCharacterEncoding(this.encoding);
}
}
filterChain.doFilter(request, response);
}
}
由源码可以知道,该字符集过滤器有两个重要参数,分别是encoding和forceEncoding,这两个参数分别有什么作用呢?
以下是参考文档的介绍:
setEncoding
public voidsetEncoding(java.lang.String encoding)
Set the encodingto use for requests. This encoding will be passed into aServletRequest.setCharacterEncoding(java.lang.String) call.
setForceEncoding
public voidsetForceEncoding(boolean forceEncoding)
Set whether theconfigured encoding of this filter is supposed to override existing request andresponse encodings.
通过参考文档,我们可以知道:
l
第一个方法setEncoding()相当于:ServletRequest.setCharacterEncoding(java.lang.String)
2.
第二个方法setForceEncoding()的作用是:
强制ServletResponse的编码格式和ServletRequest的编码格式一样。
也就是说,无论是request还是response,encoding设置了两者的编码格式,只不过forceEncoding默认值为false,此时就只是设置了request的编码格式,即在Servlet中:
request.setCharacterEncoding("XXXX");
如果设置forceEncoding的值为true时,相当于Servlet中:
request.setCharacterEncoding("XXXX");
response.setCharacterEncoding(“XXXX”);
现在我们回过头来看看最初给大家看的web.xml中那部分过滤器的配置,相信大家都明白了,配置的作用相当于Servlet中的:
@RequestMapping(value="XXXXX")
public void XXXXX(User user,HttpServletRequestreq,HttpServletResponse resp) throws UnsupportedEncodingException
{
resp.setCharacterEncoding("UTF-8");
req.setCharacterEncoding("UTF-8");
......
}