码迷,mamicode.com
首页 > 编程语言 > 详细

Java URL 中文乱码解决办法

时间:2015-06-15 22:00:29      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

一. 统一所有的编码格式

(1)JSP页面设置:<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

(2)设置编辑器默认的编码格式

例如,我的编辑器是myeclipse,全局编码设置的方法:ToolBar-->Window-->Preferences-->General-->Workspace-->Text file encoding

局部编码设置:在源码按右键-->General-->Editors-->Test Editors-->Spelling-->Encoding,这里是设置单个文件的编码。

二. 使用过滤器filter

首先自己编写一个过滤器

   1: package com.bigdata.util;
   2:  
   3: import java.io.IOException;
   4: import javax.servlet.Filter;
   5: import javax.servlet.FilterChain;
   6: import javax.servlet.FilterConfig;
   7: import javax.servlet.ServletException;
   8: import javax.servlet.ServletRequest;
   9: import javax.servlet.ServletResponse;
  10:  
  11: public class CharacterEncodingFilter implements Filter{
  12:     protected FilterConfig filterConfig = null;
  13:     protected String encoding ="";
  14:     @Override
  15:     public void destroy() {
  16:         // TODO Auto-generated method stub
  17:         filterConfig = null;
  18:         encoding = null;
  19:     }
  20:  
  21:     @Override
  22:     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
  23:             FilterChain filterChain) throws IOException, ServletException {
  24:         // TODO Auto-generated method stub
  25:         if(encoding != null && !"".equals(encoding))
  26:             servletRequest.setCharacterEncoding(encoding);
  27:         filterChain.doFilter(servletRequest, servletResponse);
  28:     }
  29:  
  30:     @Override
  31:     public void init(FilterConfig arg0) throws ServletException {
  32:         // TODO Auto-generated method stub
  33:         this.filterConfig = arg0;
  34:         this.encoding = filterConfig.getInitParameter("encoding");
  35:     }
  36:  
  37: }
接着,在web.xml中配置过滤器
   1: <filter>
   2:     <filter-name>characterEncodingFilter</filter-name>
   3:     <filter-class>com.bigdata.util.CharacterEncodingFilter</filter-class>
   4:     <init-param>
   5:         <param-name>encoding</param-name>
   6:         <param-value>UTF-8</param-value>
   7:      </init-param>
   8:    </filter>
   9:     <filter-mapping>
  10:       <filter-name>characterEncodingFilter</filter-name>
  11:       <url-pattern>/*</url-pattern>
  12:     </filter-mapping>

三. 终极绝招

如果前两个方法试过之后,依然无法解决乱码问题,可以试试这个终极绝招

   1: String str = new String(request.getParameter("something").getBytes("ISO-8859-1"),"utf-8")
但是网上都不推荐这种做法,不知道是什么原因,求大神解释!

Java URL 中文乱码解决办法

标签:

原文地址:http://www.cnblogs.com/bloodhunter/p/4579116.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!