今天跟项目组做集成的时候发现一个很奇怪的乱码问题,web.xml的filter、jsp页面均进行了编码设置, 反复调试发现引起bug的原因是web.xml的下面几行:
<filter-mapping>
<filter-name>SecurityFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>CharacterEncoding</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>CharacterEncoding</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
根据servlet2.3规范filter执行是按照web.xml配置的filter-mapping先后顺序进行执行,所以上面的配置会导致遇见*.do的url请求,先进行SecurityFilter的过滤器处理,这时候没有做编码处理,已经是乱码,到下面的filter处理时已经时乱码,再做编码处理已经没有用处。
修正方式,调整filter-mapping顺序,如下:
<filter-mapping>
<filter-name>CharacterEncoding</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>CharacterEncoding</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>SecurityFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>