最近开始学习struts2 开始就遇到乱码的问题,是在action中得到页面的数据是乱码 插到数据库中去的当然也是乱码 。去jsp群里请教,最终最终在高人的指点下解决了。
我是白开水 在此还要谢谢移居月球 嘎嘎 。
现把我的解决办法列出 ,供大家参考,当然我的方法不一定适合所有的乱码问题:
我先把所有的编码都改成了gbk 。后来月球给了我一个过滤器 我照着他的加上 问题就解决了 。
1.设置页面的编码:
<%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%>
<%@ page contentType="text/html; charset=GBK"%>
2.struts。xml中加上这两句:
<constant name="struts.i18n.encoding" value="GBK" />
<constant name="struts.locale" value="zh_CN" />
3.过滤器
过滤器写在com.water.house.filter包下的SitexaFilter.java文件中,代码如下:
package com.water.house.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;
public class SitexaFilter extends StrutsPrepareAndExecuteFilter {
private static String encoding = "GBK";
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
String encodingParam = filterConfig.getInitParameter("encoding");
if (encodingParam != null && encodingParam.trim().length() != 0) {
encoding = encodingParam;
}
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
super.doFilter(request, response, chain);
}
}
web.xml中加上一个这样的filter在struts2的filter前面 代码如下:
<filter>
<filter-name>filt</filter-name>
<filter-class>com.water.house.filter.SitexaFilter</filter-class> //这里的类的路径改成自己的
</filter>
<filter-mapping>
<filter-name>filt</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>