index.html
<html>
<head>
<title>TODO supply a title</title>
</head>
<body>
<div><form action="/servletchaining/firstservlet" method="GET">
Enter your name: <input type="text" name="user"/>
<input type="submit" value="SUBMIT"/>
</form></div>
</body>
</html>
firstservlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class firstservlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
String name;
name = request.getParameter("user");
RequestDispatcher rd = request.getServletContext().getRequestDispatcher("/secondservlet");
if(name!=null) {
request.setAttribute("UserName",name);
rd.forward(request , response);
// Forward the value to another secondservlet
} else {
response.sendError(response.SC_BAD_REQUEST,
"UserName Required");
}//else
}//if
}//get method
}//class
secondservlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class secondservlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
String UserName = (String)request.getAttribute("UserName");
// Extracting the value which is set in FirstServlet
out.println("<h1>The UserName is </h1>"+ "<h1>"+ UserName+ "</h1>");
}
}
No comments:
Post a Comment