<!
DOCTYPE html>
<html>
<head>
<title>Request Attributes Example</title>
</head>
<body>
<h2>Enter Your Name</h2>
<form action="setDataServlet" method="POST">
<label>Your Name: </label>
<input type="text" name="userName" required><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SetDataServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Get the user input from the form
String userName = request.getParameter("userName");
// Set the user name in the request attribute
request.setAttribute("userName", userName);
// Forward the request to the next servlet
RequestDispatcher dispatcher =
request.getRequestDispatcher("/getDataServlet");
dispatcher.forward(request, response);
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetDataServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Retrieve the user name from the request attribute
String userName = (String) request.getAttribute("userName");
// Set the content type for the response
response.setContentType("text/html");
// Print the response
PrintWriter out = response.getWriter();
out.println("<html><body>");
if (userName != null) {
out.println("<h2>Welcome, " + userName + "!</h2>");
} else {
out.println("<h2>No user name found in the request.</h2>");
out.println("</body></html>");
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<servlet>
<servlet-name>SetDataServlet</servlet-name>
<servlet-class>SetDataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SetDataServlet</servlet-name>
<url-pattern>/setDataServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>GetDataServlet</servlet-name>
<servlet-class>GetDataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetDataServlet</servlet-name>
<url-pattern>/getDataServlet</url-pattern>
</servlet-mapping>
</web-app>