编码问题
1.从谷歌浏览器传入的数据,出现中文乱码;
在别的浏览器中没有出现这个问题;
我的最后解决:将提交的方式修改为POST并创建过滤器解决!
package com.ch.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; public class EncodeFilter implements Filter { @Override public void destroy() { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); chain.doFilter(request, response); } @Override public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
在web.xml中的配置
<!-- 过滤器配置 --> <filter> <filter-name>encorder</filter-name> <filter-class>com.ch.filter.EncodeFilter</filter-class> </filter> <filter-mapping> <filter-name>encorder</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2.解决乱码的几种方式
(1)在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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
(2)在struts.xml中进行配置
<constant name="struts.i18n.encoding" value="UTF-8"/>
(3)在Tomcat中进行配置
<Connector port="8080" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" debug="0" connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8"/>
(4)通过request和response
request.setCharacterEncoding("utf-8"); //对GET方式提交的数据无效 response.setContentType("text/html;charset=utf-8");
(5)处理GET请求的数据
String name = request.getParameter("userName"); name=new String(userName.getBytes("ISO-8859-1","utf-8"))
(6)对于html和JSP
HTML <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> JSP <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>