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.

-Block Diagram

wrksrvlt

 

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

Output-ezgif-com-ef2aa71955

 

Project Structure-

we123

-3 Files-
1-XYZ.java(inside package ‘abc’)
2-web.xml(inside WEB-INF folder)
3-index.html(inside WebContent folder)

1-XYZ.java (servlet)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package abc;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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-web.xml (deployment descriptor)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<display-name>FirstWeb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>a</servlet-name>
<servlet-class>abc.XYZ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>a</servlet-name>
<url-pattern>/pqr</url-pattern>
</servlet-mapping>
</web-app>

3-index.html

1
2
3
4
5
6
7
<html>
<body>
<a href="pqr">click here</a>
</body>
</html>

 

Advertisements