protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //response.getWriter().append("Served at: ").append(request.getContextPath()); request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8");//解码 //向网页输出内容 PrintWriter out=response.getWriter(); //获取用户的姓名和密码 String b_username = request.getParameter("b_username"); String b_password = request.getParameter("b_password"); System.out.println(b_password+" "+b_username+"==="); //调用Login方法进行判断 BuyerobjDao dao = new BuyerobjDao(); boolean success = dao.login(b_username, b_password); System.out.println(success); if(success==true){ System.out.println("登录成功"); response.sendRedirect("shouyu.html"); }else{ System.out.println("登录失败"); response.sendRedirect("jingdong.jsp"); } } 改错
时间: 2024-03-14 14:46:09 浏览: 96
Java-Operate-XML.rar_Jsp/Servlet_Java_
代码中主要存在的问题是:
1. doGet方法中的response.getWriter()方法只能调用一次,不能重复调用,否则会报错。
2. 在设置response的字符编码时,应该在获取PrintWriter对象之前进行设置,否则会无效。
修改后的代码如下:
```java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
//向网页输出内容
PrintWriter out = response.getWriter();
//获取用户的姓名和密码
String b_username = request.getParameter("b_username");
String b_password = request.getParameter("b_password");
System.out.println(b_password + " " + b_username + "===");
//调用Login方法进行判断
BuyerobjDao dao = new BuyerobjDao();
boolean success = dao.login(b_username, b_password);
System.out.println(success);
if (success) {
System.out.println("登录成功");
response.sendRedirect("shouyu.html");
} else {
System.out.println("登录失败");
response.sendRedirect("jingdong.jsp");
}
out.close();
}
```
修改的主要内容包括:
1. 删除了无用的注释和代码。
2. 将获取PrintWriter对象的代码移到设置response字符编码的前面。
3. 修改了if语句中的判断条件,使其更加简洁。
阅读全文