需求
学生(表单中记录需求信息)访问班主任(Teacher)
班主任在学生的请求中追加了一条数据,加上了自己的名字
班主任把请求转发给了修理员(WorkMan)
修理员查看请求(主要查看班主任的名字)
步骤 编写表单,发post请求
<%--
Created by IntelliJ IDEA.
User: LH
Date: 2022/11/8
Time: 9:49
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="teacher" method="post">
<div>
学生姓名:<input type="text" name="student">
</div>
<div>
需求介绍:<input type="text" name="need">
</div>
<div>
<input type="submit" value="提交需求">
</div>
</form>
</body>
</html>
编写Teacher,获取学生的请求,追加自己的名字,请求转发
package servlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/teacher")
public class Teacher extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 解决乱码
req.setCharacterEncoding("utf-8");
// 获取数据
String student = req.getParameter("student");
String need = req.getParameter("need");
// 输出数据
System.out.println("学生姓名:"+student);
System.out.println("学生需求:"+need);
// 追加老师的姓名(关键点)
req.setAttribute("teacherName","pyhui");
// 请求转发(关键)
RequestDispatcher workman = req.getRequestDispatcher("workman");
workman.forward(req,resp);
}
}
编写WorkMan,获取学生的请求信息与班主任的名字
package servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/workman")
public class WorkMan extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取学生的请求
System.out.println("workman开始获取学生请求。。。。");
// 获取数据
String student = req.getParameter("student");
String need = req.getParameter("need");
// 输出数据
System.out.println("学生姓名:"+student);
System.out.println("学生需求:"+need);
// 获取老师的名字
System.out.println("wm获取老师的信息。。。");
Object teacherName = req.getAttribute("teacherName");
System.out.println("老师姓名:"+teacherName);
}
}
最终结果
学生姓名:小明666
学生需求:空调坏了快来修
workman开始获取学生请求。。。。
学生姓名:小明666
学生需求:空调坏了快来修
wm获取老师的信息。。。
老师姓名:pyhui