1.请求转发
1.概述:让服务器跳转到另一个资源上
2.方法
1.request.getRequestDispatcher("跳转资源路径").forward(request, response);
2.域对象
1.作用:实现servlet与servlet之间的数据传输功能
2.例如:Request本质上就是一个域对象, 域对象就是一个容器。
3.域对象的方法
1.request.setAttribute(key,value);往request对象中存数据
2.requet.getAttribute(key) 从request对象中取数据
3.request.removeAttribute(key) 删除request中的数据。
4.域对象存储数据的方式是键值对
4.代码
1.Html代码:
<html>
<head>
<title>reg.html</title>
</head>
<body>
<form action="/day36_login/userServlet" method="post">
用户名:<input type="text" name="username"/><br/>
密码:<input type="password" name="password"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
2.UserServlet代码:
public class UserServlet extends HttpServlet {
private UserDao userDao = new UserDao();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//解决乱码
request.setCharacterEncoding("utf-8");
//获取请求参数
String userName = request.getParameter("username");
String password = request.getParameter("password");
User user = new User(userName,password);
//把数据存储到数据库中
userDao.save(user);
// 往request域对象存储数据
request.setAttribute("USER",user);
//跳转到另外一个Servlet上显示注册是否成功的信息。
request.getRequestDispatcher("/infoServlet").forward(request, response); //请求转发,跳转到infoServlet
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
3.InfoServlet代码:
public class InfoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//从域对象对象中取出数据
User user = (User) request.getAttribute("USER");(强转)
OutputStream out = response.getOutputStream();
out.write(("<h1>恭喜"+user.getUsername()+"注册成功</h1>").getBytes());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
原文地址:https://www.cnblogs.com/huifeidezhuzai/p/10884135.html