//获取contentpath<br />// String contextPath = req.getContextPath();<br />// 重定向<br />// resp.sendRedirect(contextPath + "/" + "success.html");<br /> }<br />案例:
@WebServlet("/login")
public class UserResponse extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
//去数据库里查询用户和密码是否合法
//...省略一些代码
resp.setContentType("text/html;charset=utf-8");
//合法
// resp.getWriter().write("欢迎" + username);
req.setAttribute("username", username);
String flag = "2";
// req.setAttribute("flag", flag);
String sex = "男";
if (flag == "2") {
sex = "女";
}
req.setAttribute("sex", sex);
//数据库中查出来的的所有用户的名称集合
// List<String> nameList = new ArrayList<>();
// nameList.add("张三");
// nameList.add("李四");
// req.setAttribute("nameList", nameList);
List<Student> students = new ArrayList<>();
Student student = new Student();
student.setName("张三");
student.setAge(80);
student.setHeight(2);
student.setHobby("打牌");
student.setLevel("5");
students.add(student);
Student student2 = new Student();
student2.setName("张三2");
student2.setAge(802);
student2.setHeight(22);
student2.setHobby("打牌2");
student2.setLevel("52");
students.add(student2);
req.setAttribute("studentList", students);
req.getRequestDispatcher("/success.jsp").forward(req,resp);
//获取contentpath
// String contextPath = req.getContextPath();
// 重定向
// resp.sendRedirect(contextPath + "/" + "success.html");
}
}