前台页面和后台处理的编码格式不一样就会出现乱码。自定义过滤器,把jsp页面的编码设置一下,tomcat服务器设置一下,一般就不会出现这种问题了。
1.网页编码设置为utf-8
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
2.服务器设置为utf-8
如tomcat的server.xml中
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8"/>
设置为utf-8
3.自定义过滤器设置字符编码为utf-8
request 和response都设置为utf-8
setCharacterEncoding("UTF-8");
如下:
Java代码
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;
public class LifeOnlineFilter extends StrutsPrepareAndExecuteFilter {
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest) req;
String uri=request.getRequestURI();
req.setCharacterEncoding("UTF-8");
res.setCharacterEncoding("UTF-8");
if(uri.indexOf("Androidservice")!=-1){
System.out.println("FilterDispetor.doFilter():true");
chain.doFilter(req, res);
}else{
super.doFilter(req, res, chain);
}
}
}
4.链接数据库设置为utf-8
<property name="url" value="jdbc:mysql://localhost:3306/lifeonline?useUnicode=true&characterEncoding=UTF-8">
</property>
5.把数据库编码设置为utf-8
如mysql数据如,在配置的时候勾选上utf-8原先mysql默认的为latin
总的来说只要把各个层次的编码设置为一致就不会乱码,
有些地方说设置成gbk不乱码,最好用utf-8因为其几乎支持全世界的所有语言 |