遇到get请求中文编码的时候,有的人会采用在Tomcat/conf/server.xml中的如下添加一句:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
即:URIEncoding="utf-8"
但是这种方法不可采取!!!
为什么那?原因是:我们写的代码客户用的时候,不一定用Tomcat服务器,可能用webLogic等服务器,所以不可能让客户修改服务器,这是不可取的方法,牢记!!!
一般采用如下的方法:
String name=response.getParameter("username");
//因为服务器是iso编码格式的,所以我们反编译回来
byte[] bytes=name.getBytes("ISO-8859-1");
name=new String(bytes,"utf-8");
完整例子如下:
(1)form.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP ‘form.jsp‘ starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
</br>
<form action="OneServlet" method="post">
姓名:<input type="text" name="username" value="张三"/></br>
<input type="submit" name="提交"/><br/>
</form>
<a href="OneServlet?username=李四">点击</a>
</body>
</html>
(2)OneServlet如下:
package com.shujia;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class OneServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name=request.getParameter("username");
byte[] bytes=name.getBytes("iso-8859-1");
name=new String(bytes,"utf-8");
System.out.println("get name:"+name );
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//首先request.setCharacterEncoding("utf-8");防止中文乱码必须要在获取值之前添加
request.setCharacterEncoding("utf-8");
String name=request.getParameter("username");
System.out.println("name:"+name);
}
}