请求转发与请求作用域

创建input.jsp页面,通过表单输入学号、姓名后,单击登录按钮,控制转发到FirstServlet对其进行处理,然后通过请求对象的getRequestDispartcher()获得RequestDispartcher对象,将请求转发至SecondServlet,在SecondServlet中用输出流对象out输出该学生的学号和姓名。输出页面还包含一个超链接,单击该链接可以返回至input.jsp页面。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
login.jsp


  
    
    
    ForwordJsp.jsp
	
  
  
  
    this is students form: 
学号:

姓名:

        
package com.demo;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/getMethod")
public class SecondServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		Student stu  = (Student) request.getAttribute("stu");
		String id = stu.getId();
		String name = stu.getName();
		out.println("");
		out.println("");
		out.println("  result");
		out.println("  ");
		out.print(" 学号: "+id + "
"); out.print(" 姓名: "+name + "
"); out.print(""); out.println(" "); out.println(""); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
package com.demo;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/login")
public class FirstServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String id = request.getParameter("id");
		String name = request.getParameter("name");	
		request.setAttribute("stu",new Student(id, name));
		System.out.println("成功 == "+ id +"  ==  "+name);    
	    request.getRequestDispatcher("/SecondServlet.do").forward(request, response);
		out.flush();
		out.close();
	}
}

请求转发与请求作用域_第1张图片

你可能感兴趣的:(servlet,前端)