Step5:Working process of servlet + code

7 Step of working process of servlet-

step 1-client request to server for any servlet.

step 2-server finds that servlet using servlet-mapping and create 2 objects,
(a)request object- for servlet
(b)response object-for client

step 3- server calls service method in new thread and pass request and response objects as argument.

step 4-service method calls doPost() if request from client is POST else doGet().

step 5- servlet provide output in response object to server.

step 6-Server passes response object to client.

step 7- thread dies, garbage collection.

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>