编写2个Servlet,在第一个Servlet中使用setAttribute设置2个域数据后转发到第二个Servlet,在第二个Servlet中使用getAttribute取出域数据,使用response对象回传给客户端。
时间: 2023-06-27 19:06:17 浏览: 74
第一个Servlet:
```java
import java.io.IOException;
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("/FirstServlet")
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = "John";
int age = 30;
request.setAttribute("name", name);
request.setAttribute("age", age);
request.getRequestDispatcher("SecondServlet").forward(request, response);
}
}
```
第二个Servlet:
```java
import java.io.IOException;
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("/SecondServlet")
public class SecondServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = (String) request.getAttribute("name");
int age = (int) request.getAttribute("age");
response.getWriter().println("Name: " + name + ", Age: " + age);
}
}
```
在第一个Servlet中,我们使用setAttribute方法将两个值设置为名为"name"和"age"的属性。然后,我们将请求分派给第二个Servlet。
在第二个Servlet中,我们使用getAttribute方法获取这两个属性的值,并将它们与一些文本一起传递回客户端。
阅读全文