日期:2014-05-17  浏览次数:20676 次

为什么我想servlet传递中文数据时会出现乱码的情况?
以下是我编写的servlet类:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ActionServlet extends HttpServlet{
public void service(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");

String path = request.getRequestURI();
String uri =  path.substring(path.lastIndexOf("/"),path.lastIndexOf("."));

// System.out.println(path);
// System.out.println(uri);

if(uri.equals("/showAllEmp")){
EmployeeDAO dao = (EmployeeDAO)FactoryDAO.getInstanceOf("EmployeeDAO");
List<Employee> list = dao.findAllEmp();

PrintWriter out = response.getWriter();

if(list.isEmpty()){
out.println("没有雇员,请<a href = 'addEmp.html'>添加</a>");
}else{
out.println("<table width='60%' border='2' cellspace='3' cellpadding='3'>");
out.println("<tr><td>ID</td><td>姓名</td><td>年龄</td><td>薪水</td><td>操作</td></tr>");
Iterator<Employee> it = list.iterator();
while(it.hasNext()){
Employee emp = it.next();
out.println("<tr><td>" + emp.getId() + "</td><td>" + emp.getName() + 
"</td><td>" + emp.getAge() + "</td><td>" + emp.getSalary() + 
"</td><td><a href='deleteEmp.do?id=" + emp.getId() + "'>删除</a>&nbsp&nbsp" +
"<a href='showSingleEmp.do?id=" + emp.getId() + "'>修改</a></td></tr>");
}
out.println("</table>");
out.println("<a href='addEmp.html'>添加雇员</a>");

out.close();
}
}else if(uri.equals("/addEmp")){

int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
Long salary = Long.parseLong(request.getParameter("salary"));

Employee emp = new Employee();
emp.setId(id);
emp.setName(name);
emp.setAge(age);
emp.setSalary(salary);

EmployeeDAO dao = (EmployeeDAO)FactoryDAO.getInstanceOf("EmployeeDAO");
dao.addEmp(emp);

response.sendRedirect("showAllEmp.do");
}else if(uri.equals("/deleteEmp")){
int id = Integer.parseInt(request.getParameter("id"));
EmployeeDAO dao = (EmployeeDAO)FactoryDAO.getInstanceOf("EmployeeDAO");
dao.deleteEmp(id);