1、首先编写过滤器,实际上就是继承了filter接口的一个类,实现其中的init doChain 和destroy方法
packagecom.util; importjava.io.IOException; importjavax.servlet.Filter; importjavax.servlet.FilterChain; importjavax.servlet.FilterConfig; importjavax.servlet.ServletException; importjavax.servlet.ServletRequest; importjavax.servlet.ServletResponse; public class EncoderFilter implementsFilter { @Override public voiddestroy() { //TODO Auto-generated method stub System.out.println("i defined filter destroy~~~~~~~~~~~~~~~~~~~~~~"); } @Override public voiddoFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throwsIOException, ServletException { //TODO Auto-generated method stub arg0.setCharacterEncoding("UTF-8"); System.out.println("the request encoding is " +arg0.getCharacterEncoding()); System.out.println("enter myself filter~~~~~~~~~~~~~~~~~~~~~~" + new String(arg0.getParameter("men.name").getBytes(), "GBK")); arg2.doFilter(arg0, arg1); } @Override public void init(FilterConfig arg0) throwsServletException { //TODO Auto-generated method stub System.out.println("i defined filter init~~~~~~~~~~~~~~~~~~~~~~"); } }
2、在web.xml文件里面,加入如下代码
<filter> <filter-name>encodeFilter</filter-name> <filter-class>com.util.EncoderFilter</filter-class> </filter> <filter-mapping> <filter-name>encodeFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
切记,此代码应该加在struts2的过滤器前面的位置。
这时候访问传汉字应该是没有问题了,可是~~~还是乱码,解决办法:修改tomcat的server.xml文件
将
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
里添加上后面3个编码的设置
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
useBodyEncodingForURI="true"
IEncoding="utf-8"
URIEncoding="utf-8"
/>
这时候传汉字就正常了!
关于编码,可以使用request.getCharacterEncoding()方法来看请求时采用的是什么编码!