Servlet 获取前端Form表单数据,并实现请求重定向、请求转发

1.前端界面

编写一个最简单的登录界面:





Insert title here


	
用户名:
密    码:

Servlet 获取前端Form表单数据,并实现请求重定向、请求转发_第1张图片

2. Servlet 编写

共编写2个Servlet(继承 HttpServlet ):

  1. BlogServlet1:
    doPost()
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
		// 获取参数值
		String username = (String) request.getParameter("username");
		String password = (String) request.getParameter("password");
		// 输出到控制台
		System.out.println("username: " + username);
		System.out.println("password: " + password);
		
		// 请求重定向
		// 设置参数值
		request.setAttribute("newName", "sendRedirect");
		response.sendRedirect("/class02/BlogServlet2");
		
		// 请求转发
		// 设置参数值
		request.setAttribute("newName", "RequestDispatcher");
		RequestDispatcher requestDispatcher = request.getRequestDispatcher("/BlogServlet2");
		requestDispatcher.forward(request, response);
	}
  1. BlogServlet2:
    doGet()
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		PrintWriter out = response.getWriter();
		// 输出到页面
		out.println("BlogServlet2: 

"); out.println("name: " + request.getParameter("username") + "
"); out.println("passwd: " + request.getParameter("password") + "
"); out.println("newName: " + request.getAttribute("newName") + "
"); }

3. 运行

注释请求转发:
Servlet 获取前端Form表单数据,并实现请求重定向、请求转发_第2张图片

结果:URL地址变化
浏览器登录:
Servlet 获取前端Form表单数据,并实现请求重定向、请求转发_第3张图片
控制台:
在这里插入图片描述
Servlet 获取前端Form表单数据,并实现请求重定向、请求转发_第4张图片

注释请求重定向:
Servlet 获取前端Form表单数据,并实现请求重定向、请求转发_第5张图片

结果:
Servlet 获取前端Form表单数据,并实现请求重定向、请求转发_第6张图片

完!

你可能感兴趣的:(Servlet)