第三种解决方法
去掉PrintWrite
import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=utf-8"); request.setCharacterEncoding("utf-8"); // ServletContext context= this.getServletContext(); // PrintWriter out = response.getWriter(); String name = request.getParameter("username"); String password =request.getParameter("password"); String sex =request.getParameter("sex"); // out.println("用户名:" + name+"<br>"); // out.println("密码:" + password+"<br>" ); // out.println("性别:" + sex+"<br>"); String [] hobbys = request.getParameterValues("hobby"); // out.println("爱好:"); for (int i =0; i<hobbys.length;i++) { // out.println(hobbys[i]+" "); } if (name.equals("admin") && password.equals("123456")){ request.getRequestDispatcher("/success.html").forward(request,response); }else { // out.println("用户名或密码输入有误...3秒后将自动跳转 <br>"); response.setHeader("Refresh","3;URL=/error.html"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
NOTE:But!我们好像违背了表单(作业)的原则。不过在日常这种情况,Print Write的Servlet并未向页面输出内容,且页面输出的为success的内容。