mysql数据库编码有一个很烦人的地方就是插入中文时候容易产生乱码,在本文中将介绍两种解决办法!
1在普通web项目中
1所有jsp和servlet页面编码统一使用utf-8(或者gbk),
2写一个过滤器package com.jin.servlet;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class Filtercode implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
在配置文件web.xml中加入如下代码<filter>
<filter-name>Filtercode</filter-name>
<filter-class>com.jin.servlet.Filtercode</filter-class>
</filter>
<filter-mapping>
<filter-name>Filtercode</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
3 数据库配置文件my.ini
中修改默认编码gb2312(此处不能设置称utf-8,我设置称utf8时候不能启动)两处都要修改,然后在管理工具->服务中重新启动mysql
@二
在struts中数据库插入中文解决办法。
1所有jsp设置编码utf-8,
2数据库配置文件my.ini
中修改默认编码gb2312(此处不能设置称utf-8,我设置称utf8时候不能启动)两处都要修改,然后在管理工具->服务中重新启动mysql
3写个控制器
package com.jinchun.Filter;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.RequestProcessor;
public class MyFilter extends RequestProcessor {
@Override
protected boolean processPreprocess(HttpServletRequest request,
HttpServletResponse response) {
// TODO Auto-generated method stub
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
}
4在struts-config.xml中修改代码如下
<struts-config>
<data-sources />
<form-beans >
<form-bean name="reg1Form" type="com.jinchun.form.Reg1Form" />
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings >
<action
attribute="reg1Form"
input="/reg1.jsp"
name="reg1Form"
path="/reg1"
type="com.jinchun.action.Reg1Action">
<forward
name="fail1"
path="/fail.jsp"
redirect="true" />
<forward
name="success1"
path="/success.jsp"
redirect="true" />
</action>
</action-mappings>
<controller processorClass="com.jinchun.Filter.MyFilter">
</controller>
<message-resources parameter="com.jinchun.ApplicationResources" />
<!--使用验证表单的时候一定要在form这个里面来加入 plug-in -->
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
/WEB-INF/validation.xml"/>
</plug-in>
</struts-config>