注意<form action="q" method="post">里边的method是post,在servlet里边相应的就调用doPost方法,然后在调用doGet方法
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// doPost(request, response);
response.setContentType("text/html;charset=UTF-8");
//String title = "用户登录";
// 接收HTML页面上的表单内容。
String name =request.getParameter("name");
String passwd = request.getParameter("password");
System.out.println("UserName:"+name+";"+"PassWord:"+passwd);
//获取数据库里对应名字的密码,getSqlPw(String); 与数据库的交互获取密码
String sqlPw = getSqlPw(name);
//将数据写回
PrintWriter out = response.getWriter();
if(sqlPw==null)
sqlPw = "NULL";
out.write(sqlPw); //sqlPw为xml数据
out.close();
}


本文介绍了如何处理Servlet在接收到POST请求时出现的中文乱码问题。通过在doPost方法中设置请求和响应的字符编码为UTF-8,并在doGet方法中同样处理,确保了数据正确传输。示例代码展示了如何获取并打印表单中的中文姓名和密码,以及如何向响应中写回数据。
537

被折叠的 条评论
为什么被折叠?



