有一枚学生问问了我一个问题,突然灵感爆发,他使用的Spring的过滤器,前台利用GET方式向后端发出一个请求,由于里面含有中文数据,结果在后端显示的是乱码,他问我为什么?明明在Spring里面也配了字符过滤器,却出现了乱码,所以就看了一下spring实现的该过滤器,下面是过滤器的实现代码org.springframework.web.filter.CharacterEncodingFilter.java

public class CharacterEncodingFilter extends OncePerRequestFilter {

    private String encoding;

    private boolean forceEncoding = false;

    /**
* Set the encoding to use for requests. This encoding will be passed into a
* {@link javax.servlet.http.HttpServletRequest#setCharacterEncoding} call.
* <p>Whether this encoding will override existing request encodings
* (and whether it will be applied as default response encoding as well)
* depends on the {@link #setForceEncoding "forceEncoding"} flag.
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
} /**
* Set whether the configured {@link #setEncoding encoding} of this filter
* is supposed to override existing request and response encodings.
* <p>Default is "false", i.e. do not modify the encoding if
* {@link javax.servlet.http.HttpServletRequest#getCharacterEncoding()}
* returns a non-null value. Switch this to "true" to enforce the specified
* encoding in any case, applying it as default response encoding as well.
*/
public void setForceEncoding(boolean forceEncoding) {
this.forceEncoding = forceEncoding;
} @Override
protected void doFilterInternal(
HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException { if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
request.setCharacterEncoding(this.encoding); //此处设置是处理POST方式的编码参数问题
if (this.forceEncoding) {
response.setCharacterEncoding(this.encoding);
}
}
filterChain.doFilter(request, response);
} }

在web.xml该过滤器是这样配置的:需要设置的两个参数为encoding、forceEncoding,分别设置字符集及是否设置字符集,该filter也非常简单

    <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>

有的时候,看到源码才知道一些真理,所有才知道spring只是利用request.setCharacterEncoding(this.encoding);帮助我们处理了POST方式的乱码问题,碰到GET方式的提交,还是会出现乱码。


注意:自从Tomcat5.x开始,就对GET方式和POST方式的提交分别给予不同的处理方式[所以在二阶段学习的时候就应该严格区分get和post请求的处理情况,养成良好的习惯,想想是否做的到]。POST方式是利用request.setCharacterEncoding()来进行设置编码,如果没有设置的话,就是按照默认的ISO-8859-1来进行编码;GET方式提交总是利用默认的ISO-8859-1来进行编码参数


中文乱码解决方案


1.利用String[也是最常用的方式]

String username = new String(username.getBytes("ISO-8859-1"), "UTF-8"); //通过默认的编码获取到byte[],然后进行UTF-8再次编码  

2.在tomcat中的server.xml进行配置URIEncoding="UTF-8"

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

3.使用JavaScript对传递的参数进行编码

额外阅读

Js编码的几种方式区别:

1.window.escape()与HttpUtility.UrlEncodeUnicode()编码格式一样:将一个汉字编码为%uxxxx格式
不会被window.escape编码的字符有:@ _ - . * / +  这与http://www.w3school.com.cn/js/jsref_escape.asp上的解释不符合

2.window.encodeURIComponent()[我推荐使用这种方式]与HttpUtility.UrlEncode()编码格式一样:将一个汉字编码为%xx%xx%xx的格式

不会被window.encodeURIComponent编码的字符有:'  (  )  *  -  . _   ! ~   这与http://www.w3school.com.cn/js/jsref_encodeURIComponent.asp解释相符合

不会被HttpUtility.UrlEncode编码的字符有:'  (  )  *  -  .  _  ! 相比较而言,HttpUtility.UrlEncode比window.encodeURIComponent多一个 ~ 编码

3.不会被window.encodeURI编码的字符有: -  _  .  !  * (  )  ;  /  ?  :  @  &  =  $  ,  #,与encodeURIComponent对比,发现encodeURI不对:;/?:@&=+$,#这些用于分隔 URI 组件的标点符号进行编码

第一种: 事例演示说明
JavaScript代码:
window.self.location="searchbytext.action?searchtext="+encodeURIComponent(encodeURIComponent(seartext)); java后台处理代码: searchtext=java.net.URLDecoder.decode(searchtext,"UTF-8"); /* 为什么要两次编码的原因:后台java代码给searchtext赋值的时候,本身已经使用了一次解码,不过解码的结果依然不对。所以我们可以在页面上进行两次编码操作,这样后台自动的那次就可以抵消掉一次,然后在使用searchtext=java.net.URLDecoder.decode(searchtext,"UTF-8");进行一次解码就好了。【这种方式还是用的比较多的,我个人使用的比较少】
*/

我个人来说还是比较喜欢第一种情况,但是有的时候服务器有兼容问题,我曾经就遇到在tomcat中好用,放置到Weblogic后不好使了,之后我就只用第三种方式,对于第三种方式我不过多解释,希望大家有印象

我写了这么多,为什么你们总是不回复我呢!<( ̄▽ ̄)> 哇哈哈…!

[技巧篇]12.从Spring的编码过滤器说起的更多相关文章

  1. 关于web.xml中配置Spring字符编码过滤器以解决中文乱码的问题

    当出现中文乱码问题,Spring中可以利用CharacterEncodingFilter过滤器解决,如下代码所示: <!-- Spring字符编码过滤器:解决中文乱码问题 --> < ...

  2. Spring字符编码过滤器

    1 <filter> 2 <filter-name>characterEncodingFilter</filter-name> 3 <filter-class ...

  3. 深入Struts2的过滤器FilterDispatcher--中文乱码及字符编码过滤器

    引用 前几天在论坛上看到一篇帖子,是关于Struts2.0中文乱码的,楼主采用的是spring的字符编码过滤器(CharacterEncodingFilter)统一编码为GBK,前台提交表单数据到Ac ...

  4. Spring的字符编码过滤器CharacterEncodingFilter

    Spring中的字符编码过滤器,用来解决我们项目中遇到的编码问题. 使用方式特别友好,在web.xml加入: <filter> <description>字符集过滤器</ ...

  5. Spring编码过滤器:解决中文乱码

    Spring编码过滤器:解决中文乱码 针对问题: 前台JSP页面和JAVA代码中使用了不同的字符集进行编码的时候就会出现表单提交的数据或者上传/下载中文名称文件出现乱码的问题: 解决方案: web.x ...

  6. SpringMVC(12)完结篇 基于Hibernate+Spring+Spring MVC+Bootstrap的管理系统实现

    到这里已经写到第12篇了,前11篇基本上把Spring MVC主要的内容都讲了,现在就直接上一个项目吧,希望能对有需要的朋友有一些帮助. 一.首先看一下项目结构: InfrastructureProj ...

  7. spring设置字符编码过滤器

    一.在web.xml中的配置 <!-- characterEncodingFilter字符编码过滤器 --> <filter> <filter-name>chara ...

  8. Spring Cloud Gateway过滤器精确控制异常返回(实战,控制http返回码和message字段)

    欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 本篇概览 前文<Spring Cloud Gat ...

  9. Spring Cloud Gateway过滤器精确控制异常返回(实战,完全定制返回body)

    欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 本篇概览 Spring Cloud Gateway应用 ...

随机推荐

  1. Python最长连续数列的O(n)解法

    题目 输入一个乱序的连续数列,输出其中最长连续数列长度,要求算法复杂度为 O(n) . 输入样例 100,4,200,1,3,2 54,55,300,12 1 5,4,3,2,1 1,2,3,4,5, ...

  2. tensorflow学习笔记(4)-学习率

    tensorflow学习笔记(4)-学习率 首先学习率如下图 所以在实际运用中我们会使用指数衰减的学习率 在tf中有这样一个函数 tf.train.exponential_decay(learning ...

  3. leetcode个人题解——#22 Generate Parentheses

    思路: 递归解决,如果左括号个数小于右括号或者左括号数小于总括号对数,则生成一个左括号,如果左括号数大于右括号,生成一个右括号. class Solution { public: vector< ...

  4. 阿里校招内推C++岗位编程题第一题 空格最少的字符串

    给定一个字符串S和有效单词的字典D,请确定可以插入到S中的最小空格数,使得最终的字符串完全由D中的有效单词组成.并输出解. 如果没有解则应该输出n/a 例如: 输入: S = “ilikealibab ...

  5. C Program基础-宏定义

    写好c语言,漂亮的宏定义是非常重要的,我们在阅读别人工程时,往往能看到大量的宏定义,宏定义可以增加代码的可读性,也能增加代码的可移植性,一个好的宏定义甚至是一件艺术品.今天我们就来看看宏定义的方方面面 ...

  6. windows远程连接失败问题排查思路

    一般情况下,对WIN7的远程连接只需要5步即可完成远程连接的设置: 1).用户是否设置了密码 2).计算机属性-允许远程登录 3).设置计算机永不睡眠 4).关闭防火墙或者设置入站规则 5).排查Re ...

  7. java---Map接口实现类

    Map是一个双列集合接口,如果实现了Map接口,特点是数据以键值对形式存在,键不可重复,值可以重复.java中主要有HashMap.TreeMap.Hashtable.本文主要介绍Map的接口方法: ...

  8. 生活中的goto

    if(你是个傻逼?){ out.println("继续你的傻逼生活吧!"); }else(你不是傻逼?){ out.println("你说不是都不是啊,继续你的傻逼生活吧 ...

  9. DELPHI BOOKMARK使用

    关于书签(BookMark)操作:       书签操作主要用于在表中快速地定位记录指针,在应用程序中常常要保存记录指针所在的位置,在进行其他处理之后,希望能快速地返回到先前指针所在的位置,此时,使用 ...

  10. 如何在存储过程中执行set命令  我来答

    1.EXEC使用EXEC命令两种用种执行存储程另种执行态批处理所讲都第二种用 面先使用EXEC演示例,代码1DECLARE @TableName VARCHAR(50),@Sql NVARCHAR ( ...