在编程中,我们会碰到各种各样的乱码问题,在此个人做一个小结,也为以后查看用(此处已utf-8格式为例)
1.jsp页面,设定为UTF-8格式.
2.后台获取前台页面的值时,在获取值的地方加上代码 :remark = new String(remark .getBytes("iso-8859-1"), "utf-8");
<我的是备注remark,大家可以根据自己的字段修改;>
3.如果有用到struts2框架,可在配置里面家伙是哪个如下配置:
<constant name="struts.i18n.encoding" value="utf-8"></constant>
4.如果使用了spring框架,可以使用spring解决乱码问题
利用spring自定义的CharacterEncodingFilter,使用方式如下。
在web.xml文件中添加
<filter>
<filter-name>encodingFilter</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>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
5.也可以自己写一个过滤器类,代码如下:
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);
if (this.forceEncoding && responseSetCharacterEncodingAvailable) {
response.setCharacterEncoding(this.encoding);
}
}
filterChain.doFilter(request, response);
}