Step5: Working process of servlet + code

Learn with our youtube video –

7 Step of working process of servlet-

StepDescription
1Client requests a servlet from the server
2Server locates the servlet using servlet-mapping and creates request and response objects
3Server calls the service method in a new thread, passing the request and response objects as arguments
4The service method calls doPost() if the request is a POST request, or doGet() if it is a GET request
5The servlet provides output in the response object to the server
6Server passes the response object to the client
7The thread dies and garbage collection is performed

Example 1-Web app to call a servlet to print “java is simple” from a html page.

Output-

ezgif 2 d5825ca31c36

-2 Files-
1-XYZ.java(inside package ‘abc’)
2-index.html(inside WebContent folder)

1-XYZ.java (servlet)

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet("/XYZ")
public class XYZ extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.print("java is simple");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}

 

2-index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="XYZ">View Profile</a>
</body>
</html>