Java URL 中文乱码解决办法

时间:2021-09-24 11:00:34

一. 统一所有的编码格式

(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")

但是网上都不推荐这种做法,不知道是什么原因,求大神解释!