tomcat乱码

本文介绍了解决Java Web项目中提交数据出现乱码的方法,包括修改Tomcat配置、使用过滤器等方案,并提供了具体实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  

问题:
在java-tomcat-eclipse-mysql 环境中(其实什么环境不重要)
当页面提交以及action中通过request.getParameter的时候会出现乱码
方案一:
当你在ACTION中添加语句content = new String(request.getParameter("content").getBytes("ISO-8859-1"),"GB2312");
来对其进行转换是没有任何问题的
方案二:
Tomcat 的 Server.xml文件 的 Connector 添加 URIEncoding=“GBK”
方案三:
做个filter
方案二和三都存在一个问题就是在IE中仍然存在乱码的问题 但到了其他浏览器就没有问题了@
解决办法是把HTML中的content="text/html; charset=GBK"
 
JSP中也是如此!
现在专门讲一下filter:
先写个filter 假设放在com.DP.Filter包中
public class filter implements Filter {
 protected String encoding = null;
 
 protected FilterConfig filterConfig = null;
 
 protected boolean ignore = true;
 
 public void init(FilterConfig filterConfig) throws ServletException {
 // TODO Auto-generated method stub
 this.filterConfig = filterConfig;
 this.encoding = filterConfig.getInitParameter("encoding");
 String value = filterConfig.getInitParameter("ignore");
 if (value == null)
   this.ignore = true;
 else if (value.equalsIgnoreCase("true"))
   this.ignore = true;
 else if (value.equalsIgnoreCase("yes"))
   this.ignore = true;
 else
   this.ignore = false;
 }
 
 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException {
 // TODO Auto-generated method stub
   if (ignore || (request.getCharacterEncoding() == null)) {
   String encoding = selectEncoding(request);
   if (encoding != null)
    
    request.setCharacterEncoding(encoding);
    /*Enumeration test= request.getParameterNames(); 
    String name=null;
       String nameValue=null;
       while(test.hasMoreElements())
       {
        name=(String)test.nextElement();
        nameValue=new String(request.getParameter(name).getBytes("ISO-8859-1"),"GB2312");
        System.out.println("name***"+name+"***value***"+nameValue);
       } */
 }
 chain.doFilter(request, response);
 
 }
 
 public void destroy() {
 // TODO Auto-generated method stub
 this.encoding = null;
 this.filterConfig = null;
 }
 
 protected String selectEncoding(ServletRequest request) {
 
 return (this.encoding);
 
 }
 
}
然后设置web.xml,添加以下代码:(注意filter在web.xml中的放置顺序)
                <filter>
 <filter-name>filter</filter-name>
 <filter-class>com.DP.Filter.filter</filter-class>
 <init-param>
   <param-name>encoding</param-name>
   <param-value>GBK</param-value>
 </init-param>
 <init-param>
   <param-name>ignore</param-name>
   <param-value>true</param-value>
 </init-param>
 </filter>
 
 <filter-mapping>
 <filter-name>filter</filter-name>
 <url-pattern>*.do</url-pattern>
 </filter-mapping>
如此就解决了添加filter后的所有提交页面的乱码的问题!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值