1. //获取contentpath<br />// String contextPath = req.getContextPath();<br />// 重定向<br />// resp.sendRedirect(contextPath + "/" + "success.html");<br /> }<br />案例:
    1. @WebServlet("/login")
    2. public class UserResponse extends HttpServlet {
    3. @Override
    4. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    5. req.setCharacterEncoding("utf-8");
    6. String username = req.getParameter("username");
    7. String password = req.getParameter("password");
    8. //去数据库里查询用户和密码是否合法
    9. //...省略一些代码
    10. resp.setContentType("text/html;charset=utf-8");
    11. //合法
    12. // resp.getWriter().write("欢迎" + username);
    13. req.setAttribute("username", username);
    14. String flag = "2";
    15. // req.setAttribute("flag", flag);
    16. String sex = "男";
    17. if (flag == "2") {
    18. sex = "女";
    19. }
    20. req.setAttribute("sex", sex);
    21. //数据库中查出来的的所有用户的名称集合
    22. // List<String> nameList = new ArrayList<>();
    23. // nameList.add("张三");
    24. // nameList.add("李四");
    25. // req.setAttribute("nameList", nameList);
    26. List<Student> students = new ArrayList<>();
    27. Student student = new Student();
    28. student.setName("张三");
    29. student.setAge(80);
    30. student.setHeight(2);
    31. student.setHobby("打牌");
    32. student.setLevel("5");
    33. students.add(student);
    34. Student student2 = new Student();
    35. student2.setName("张三2");
    36. student2.setAge(802);
    37. student2.setHeight(22);
    38. student2.setHobby("打牌2");
    39. student2.setLevel("52");
    40. students.add(student2);
    41. req.setAttribute("studentList", students);
    42. req.getRequestDispatcher("/success.jsp").forward(req,resp);
    43. //获取contentpath
    44. // String contextPath = req.getContextPath();
    45. // 重定向
    46. // resp.sendRedirect(contextPath + "/" + "success.html");
    47. }
    48. }