springmvc中Post和get乱码的解决

第一种方法依赖于tomcate6中webapps\examples\WEB-INF\classes\filters下SetCharacterEncodingFilter这个类

实现方法在web.xml 中添加以下代码

<filter>
  <filter-name>CharacterEncodingFilter</filter-name>
  <filter-class>com.filter.CharacterEncodingFilter</filter-class>
  <init-param>
  <param-name>encoding</param-name>
  <param-value>UTF-8</param-value>
  </init-param>
  </filter>
  <filter-mapping>
  <filter-name>CharacterEncodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>

第二种使用spring中自带的一个设置编码的过滤器

实现方法在web.xml中添加以下代码

<filter>
  <filter-name>CharacterEncodingFilter</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>
  </filter>
  <filter-mapping>
  <filter-name>CharacterEncodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>

第三种方法因为在配置springmvc时写过如下代码

<servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:springmvc-servlet.xml</param-value>
  </init-param>
  
  </servlet>
  <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>*.action</url-pattern>
  </servlet-mapping>

因此第三种方法可以修改DispatcherServlet类  修改如下:


  
import javax.servlet.ServletConfig;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import org.springframework.web.servlet.DispatcherServlet;  
  
public class EncodingDispatcherServlet extends DispatcherServlet {  
 private String encoding;  
  
 public void init(ServletConfig config) throws ServletException {  
  encoding = config.getInitParameter("encoding");  
  super.init(config);  
 }  
  
 protected void doService(HttpServletRequest request, HttpServletResponse response) throws Exception {  
  request.setCharacterEncoding(encoding);  
  super.doService(request, response);  
  }  
}

然后将web.xml中配置改为:

 <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:springmvc-servlet.xml</param-value>
  </init-param>
  <init-param>
  <param-name>encoding</param-name>
  <param-value>UTF-8</param-value>
    </init-param>
  
  </servlet>
  <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>*.action</url-pattern>
  </servlet-mapping>

get乱码提交:

第一种方法:

修改tomcat配置文件添加编码与工程编码一致,如下:

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

第二种方法提交

String userName new;

String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")

你可能感兴趣的:(springmvc中Post和get乱码的解决)