jsp页面,mysql页面上的中文不显示为乱码,各个地方使用的编码(如UTF-8,GB18030,GBK等)的编码保持一致即可。
1. jsp页面的编码:
<%@page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
2. mysql编码:
jdbc:mysql://localhost:3306/library?user=root&pasasword=&useUnicode=true&characterEncoding=UTF-8
(此为jdbc的url)
3.request编码:
<%request.SetCharacterEncoding(UTF-8);%>
“三码合一”,妈妈再也不用担心我的乱码了!
如果给页面写了转换字符集的Filter那么第三步就不用了。。
Filter:
@WebFilter(filterName="/CharsetFilter", urlPatterns="/*")
public class CharsetFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
}
***********************************************************
如果在servlet中操作的话,第三步的filter写成这样:
Filter:
@WebFilter(filterName="/CharsetFilter", urlPatterns="/*")
public class CharsetFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request = new Request((HttpServletRequest) request);
request.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
}
Request是写在filter里面的内部类,如下:
class Request extends HttpServletRequestWrapper
{
public String toutf8(String input) {
try {
byte[] bytes = input.getBytes("ISO8859-1");
return new String(bytes, "utf-8");
} catch (Exception ex) {
}
return null;
}
public String getParameter(String name)
{
return
toutf8(getHttpServletRequest().getParameter(name));
}
public String[] getParameterValues(String name)
{
String values[] =getHttpServletRequest().getParameterValues(name);
if (values != null) {
for (int i = 0; i < values.length; i++) {
values[i] = toutf8(values[i]);
}
}
return values;
}