JSP中文解决方案
在JSP中,经常会出现中文显示乱码的现象。一般出现的场所是JSP页面、request对象获取请求参数、Servlet输出响应和数据库交互。
1、JSP页面:每个JSP页面的第一行将page指令中的charset值设为支持中文编码的gbk,gb2312,gb1036等
<%@ page language="java" contentType="text/html;charset=gb2312"%>
2、request获取请求参数的获取:获取时,将获取的参数及其值进行字符串转换,以支持中文显示。
eg:<%
String name = (String) request.getParameter("username");
String namezh =new String(name.getBytes("iso8859-1"));
%>
同理,config对象获取配置参数也是同样的解决方案。
3、Servlet输出响应:需要对不同的请求方法实现不同的处理接口,如处理Http GET方法的doGet接口,处理HTTP Post方法的doPost接口等。但实现中文支持的方法都类型。
eg:doGet方式:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
request.setCharacterEncoding("gb2312");
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
out.println();
...
}
需注意的是这些设置必须在创建PrintWriter对象之前。