jsp,action乱码问题

解决思路:

1,手写过滤器,在web.xml中配置,并且注意filter-mapping的顺序设置在基础过滤器前面

代码如下:

package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
 * 乱码过滤器
 * @author Administrator
 *
 */
public class SetCodeFilter  implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		// TODO Auto-generated method stub
		arg0.setCharacterEncoding("UTF-8");//将请求编码设为UTF-8
		arg1.setCharacterEncoding("UTF-8");//将请求编码设为UTF-8
		arg2.doFilter(arg0, arg1);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	 

	 
 
 

 

	
}

  web.xml代码

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<!-- struts基本过滤器 -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    	<!--编码过滤器 -->
	<filter>
	<filter-name>encoding</filter-name>
	<filter-class>filter.SetCodeFilter</filter-class>
	</filter>
		<filter-mapping>
	<filter-name>encoding</filter-name>
	<url-pattern>/*</url-pattern>
	</filter-mapping>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

</web-app>

 

2,如果使用的是tomcat服务器的话,有必要在config文件夹下面的servel.xml中配置如下:

 <Connector port="8080" protocol="HTTP/1.1" URIEncoding="UTF-8"
               connectionTimeout="20000"
               redirectPort="8443" />

3,在sturts.xml中新增contant标签:

    <constant name="struts.i18n.encoding" value="UTF-8" />

通过上述3个步骤,一般就能解决

 

4,写一下我刚发现的解决方案,适应于struts2.1.6版本

如果你用的是这个版本,<constant name="struts.i18n.encoding" value="UTF-8" />配置这个常量不能解决 问题,因为官网上说这是struts2.1.6的bug,在2.1.7已经解决这BUG,如果我们还想用2.1.6版本,那么修改一下web.xml的默认filter即可。

即:将org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter 改成

org.apache.struts2.dispatcher.FilterDispatcher。

你可能感兴趣的:(action)