request请求转发和request域运用

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代码:  
			
			  
			    reg.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(("

恭喜"+user.getUsername()+"注册成功

").getBytes()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

你可能感兴趣的:(javaweb)