0% found this document useful (0 votes)
27 views

Servlet Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Servlet Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 94

Servlets

----------------------
Desktop application:

 A desktop application has to be


downloaded, installed in our computer,
then we can able to use it.
 If a new version of a desktop application
is released, then you have to update or
reinstall the application again in your
system.
 For example, IDE software’s like Eclipse,
IntelliJ, STS and Anti-virus software’s
like McAfee, Kaspersky are desktop
applications.
Web application:
 A web application is a software
application which executes on a web server
and users can access through browsers over
internet.
 A web application can provide the service
to multiple users at a time over internet.
 If any changes are made to a web
application then users are no need to make
any changes in their computer.
 Web applications are two types.
 1. Static web applications
 2. Dynamic web applications
 A static web application will provide the
same content to all the users without any
server-side processing.
 Static web applications can be developed
using HTML, CSS and Javascript.
 A dynamic web application will take user
input, process it at server-side and
generates dynamic content to the users.
 Dynamic web applications can be developed
using server-side web technologies like
servlets, asp.net, JSP, PHP, Node.js, ..
 To develop dynamic web applications, we
need both client-side and server-side web
technologies.

 For example, personal blogs, online


tutorials are static web applications.

 For example, facebook, amazon, irctc are


dynamic web applications.

 The three key components of a dynamic web


application are,
 1. Front end

 2. Back end

 3. Database

 Front end is a user interface where users


can interact with our application.

 Backend is a business logic of an


organization according to the business
rules.

 Database is for storing and retrieval of


the data.

Date: 21 / 3 / 2024

 A dynamic web application also requires


html, css and java script files. It also
contains servlet classes, JSP files to do
request processing at server.
 A web application contains a group of
resources. The resources are the files
like html files, css files, javascript
files, image files, servlet classes, jsp
files, ….
Web server and web container:
-----------------------------

 In the above diagram, client is requesting


for html file from server.
 The server will accept the request,
collects the html file from the web
application and serves that file as a
response to the client.
 In the above diagram, client is requesting
for servlet class.
 When a request comes, first web server
will accept it.
 After accepting, it checks whether the
request is for static resource or dynamic
resource.
 If the request is for dynamic resource
like a servlet class or a JSP file, then
web server will forward the request to the
web container.
 The web container will execute the servlet
class, and receives the dynamic content
generated by the servlet class.
 Now the container sends the dynamic
content to the web server.
 Finally, web server sends the dynamic
content as a response to the client.
Who is web container?
 A web container is program, which is
available in a web server, who takes care
of executing dynamic resources like
servlet classes and JSP files.
Servlet?
 It is a Java class which is capable of
handling the user input, processing it and
generating dynamic content.
How do we create a servlet class?
1. By deriving/extending GenericServlet
class
2. By deriving/extending HttpServlet
class
3. By implementing Servlet interface.
Date: 22 / 3 / 2024
 To develop servlet classes by the
programmers, servlet technology has
provided an API, which contains a set of
classes and interfaces, which are divided
into two packages.
 1. javax.servlet
 2. javax.servlet.http
 For the interfaces in the servlet API, the
implementations are provided in the server
software.
public class TestServlet extends
GenericServlet {
------
------
------
}
(or)
public class TestServlet extends
HttpServlet {
------
------
------
}
(or)
public class TestServlet implements
Servlet {
------
------
}

 If we implement Servlet interface, then


our class has to override all the abstract
methods of that interface.
 If we extend GenericServlet abstract
class, then our class has to override only
one abstract method called service().
 If we extend HttpServlet abstract class,
the our class can override the methods
like doGet(), doPost(), …..
 HttpServlet class is an abstract class,
but the class does not contain any
abstract methods.
 In Java, we can create a class as an
abstract class, without any abstract
methods, for the following two reasons.
 1. To convey a message that my class has
partial implementation/some dummy
implementation for the functionalities.
 2. To convey a message that my class has
partial implementation, so you can’t
create object to my class.

Life cycle methods of a servlet:


-----------------------------------
1. init
2. service
3. destroy
 A servlet class is developed by a
programmer but an object is created and
methods are invoked by the web container.
 The web container invokes init and destroy
methods only for once.
 The web container invokes service method
for each request.
 The web container creates only one object
to a servlet class. So it makes our
servlet class as a singleton class.
Syntax of init method:
public void init(ServletConfig config)
throws ServletException {
//code
}

Syntax of service method:


public void service(ServletRequest
request, ServletResponse response) throws
ServletException, IOException {
//code
}
Syntax of destroy method:
public void destroy() {
//code
}

Date: 23 / 3 / 2024
Web application directory layout:
web.xml(deployment descriptor):
------------------------------
 In this file, a developer has to write
some information about the servlet
classes, which is needed by the container.
Date: 25 / 3 / 2024
Installing Tomcat server:
1. Visit http://tomcat.apache.org
2. Goto download section, click on Tomcat 9
3. Click on 32-bit/64-bit windows service
installer
4. Apache-tomcat-9.0.87.exe file is downloaded
5. Double click on the downloaded file
6. Click on Next buttons, change server
shutdown port : 8085, then enter username and
password as admin
7. Next  finish
Note: The tomcat server is installed at,
C:\ Program Files\ Apache Software Foundation
\ Tomcat9.0

How can you start the server:


 Goto C:\ Program Files\ Apache Software
Foundation \ Tomcat9.0\bin folder, then
double click on either startup or Tomcat9.
 Verify the server is started or not,
Open browser and enter
http://localhost:8080 or
http://127.0.0.1:8080

First web application:


======================

1. Start the eclipse IDE


2. File  New  Dynamic web project
3. Enter project name: 01WebApp
4. Change dynamic web module version:
2.4
5. Next -> next -> finish
6. Right click on project(01WebApp) 
build path -> configure build path ->
libraries tab -> select web application
libraries -> Add external jars…  Go to
Tomcat 9.0\lib folder and choose servlet-
api.jar open  apply
7. Expand src -> main -> right click on
java  new  other -> class  package
com.ashokit.demo  name DemoServlet 
super class GenericServlet -> next 
finish
public class DemoServlet extends
GenericServlet {

public void service(ServletRequest


request, ServletResponse response) throws
ServletException, IOException {
//set MIME type (Multipurpose
Internet Mail Extension)
//MIME type has type/subtype
response.setContentType("text/html");
//create PrintWriter to write the
content into response object
PrintWriter out =
response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1> Welcome to
Servlets </h1>");
out.println("</body>");
out.println("</html>");
out.close();
}

Date: 26 / 3 / 2024

 Expand src  main  webapp  WEB-INF 


web.xml
 <servlet>
 <servlet-name>demo</servlet-
name>
 <servlet-
class>com.ashokit.demo.DemoServlet</se
rvlet-class>
 </servlet>

 <servlet-mapping>
 <servlet-name>demo</servlet-
name>
 <url-pattern>/welcome</url-
pattern>
 </servlet-mapping>

 Go to window menu  show view  servers

 In servers window  right click  new 


server  expand Apache  choose Tomcat
v9.0 server  next  click on browse
button and select Tomcat 9.0 folder  ok
 finish

 Right click on the project(01WebApp)  Run


As  Run on server  select Tomcat 9.0
server  next  finish

 Open browser, and enter the below url

http://localhost:8080/01WebApp/welcome

Date: 27 / 3/ 2024
1. Open MySQL Workbench
2. Create USERS table with columns
USER_NAME and
PASS_WORD
3. Insert some sample records into
the table and commit the records.
4. Launch Eclipse IDE
5. Create a Dynamic web project :
02LoginApp
6. Expand 02LoginApp  src  main 
right click on webapp folder  new  html
file
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login Page</title>
</head>
<body>
<form action = "./loginsrv" method =
"post">
<table>
<tr>
<td>Username</td>
<td> <input type = "text" name
= "uname"> </td>
</tr>
<tr>
<td>Password</td>
<td> <input type = "password"
name = "pwd"> </td>
</tr>
</table>
<input type = "submit" value =
"SUBMIT" >
</form>
</body>
</html>
7. Copy mysql driver software, mysql-
connector-j-8.3.0.jar into lib folder.
8. Right click on 02LoginApp  build
Path  configure build path  choose web
app libraries  Add external Jars… 
choose servlet-api.jar  apply and close.
9. Right click on java folder  new
 other class  enter package:
com.ashokit.login  name: LoginServlet 
super class: click on browse and choose
GenericServlet  finish
10. public class LoginServlet extends
GenericServlet {
11.
12. Connection conn = null;
13. PreparedStatement pstmt = null;
14.
15. public void init(ServletConfig
config) throws ServletException {
16. try {
17.
Class.forName("com.mysql.cj.jdbc.Driver
");
18. conn =
DriverManager.getConnection("jdbc:mysql
://localhost:3306/test", "root",
"root");
19. String query = "SELECT
COUNT(*) FROM USERS WHERE USER_NAME = ?
AND PASS_WORD = ?";
20. pstmt =
conn.prepareStatement(query);
21. }
22. catch(SQLException ex) {
23. ex.printStackTrace();
24. }
25. }
26.
27. public void
service(ServletRequest request,
ServletResponse response) throws
ServletException, IOException {
28.
29.

response.setContentType("text/html");
30.
31. PrintWriter out =
response.getWriter();
32.
33. //read the input from request
34. String username =
request.getParameter("uname");
35. String password =
request.getParameter("pwd");
36.
37. try {
38. //setting the username and
password to the PreparedStatement
39. pstmt.setString(1,
username);
40. pstmt.setString(2,
password);
41.
42. ResultSet rs =
pstmt.executeQuery();
43. rs.next();
44. int count = rs.getInt(1);
45. rs.close();
46.
47. if(count == 1) {
48. out.println("<html>");
49. out.println("<body>");
50. out.println("<h1>");
51. out.println("<font
color='green'>");
52. out.println("Welcome "
+ username +"<br>");
53. out.println("Your Login
Success!!");
54. out.println("</font>
</h1> </body> </html>");
55. }
56. else {
57. out.println("<html>");
58. out.println("<body>");
59. out.println("<h1>");
60. out.println("<font
color='red'>");
61. out.println("Your
username or password is invalid!!!");
62. out.println("</font>
</h1> </body> </html>");
63. }
64. }
65. catch(SQLException ex) {
66. ex.printStackTrace();
67. }
68.
69. out.close();
70. }
71.
72. public void destroy() {
73. try {
74. if ( pstmt != null ) {
75. pstmt.close();
76. }
77. if( conn != null ) {
78. conn.close();
79. }
80. }
81. catch(Exception e) {
82. e.printStackTrace();
83. }
84. }
85.
86. }
11. Expand webapp  WEB-INF  web.xml file,
add the below code
<servlet>
<servlet-name>Login</servlet-name>
<servlet-
class>com.ashokit.login.LoginServlet</servl
et-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/loginsrv</url-pattern>
</servlet-mapping>

12. Right click on 02LoginApp  Run As 


Run on server  Select Tomcat Server 
finish

13. Enter the below URL in browser


http://localhost:8080/02LoginApp/Login.html

Note:
Suppose, if you don’t want to add the
Login.html to the url explicitly, then add
the below tags in web.xml file.
<welcome-file-list>
<welcome-file>Login.html</welcome-
file>
</welcome-file-list>
Early loading a servlet:
 By default, a servlet class is lazily
loaded into the server.
 It means, whenever a servlet class
receives a first request, then its
object will be created by the servlet
container.
 If it is lazy loaded, the first request
has to wait until the object is created
and it is initialized.
 So, we can avoid this waiting time, by
early loading.
 To early load a servlet class into the
server, add the below tag under the
parent tag <servlet>
 <load-on-startup>1</load-on-startup>
 load-on-startup value must be >=0
Date: 29 / 3 / 2024
HTTP protocol:
 HTTP stands for Hyper Text Transfer
Protocol
 A protocol defines a set of rules,
standards, conventions that governs how
the data must be exchanged between two
entities in a network.
 A protocol defines a format, and sequence
for the data that should be exchanged.
 HTTP is a protocol designed to exchange
the data between web browsers and web
servers.
 HTTP protocol is developed by Roy
Fielding.
 In web development, a resource could be a
file or it could be some data.
 HTTP defines a set of request methods,
which are called verbs, to do some action
on a resource.
 GET : This request method is defined to
get a resource from the webserver.
 POST : This request method is defined to
send some resource to the web server.
 PUT : This request method is defined to
update some resource in the webserver.
 DELETE: This request method is defined to
delete a resource from the webserver.
 GET, PUT and DELETE are idempotent request
methods.
 POST is a non-idempotent request method.
 Idempotent request method means, when two
or more identical requests are made to a
webserver, then it doesn’t make any
changes to the server.
 Non-idempotent request method means, when
two or more identical requests are made to
a webserver, then it makes some changes to
the server.
Date: 30 / 3 / 2024
HttpServlet class
-----------------
 HttpServlet class extends GenericServlet
class.
 HttpServlet class is an abstract class,
but it has no abstract methods.
 HttpServlet class is given as an abstract
class, to indicate the developers that it
is an incomplete class.
 HttpServlet class has defined 7 doXxx()
methods with some dummy
implementation/logic, which doesn’t fit
for any application.
 ( doGet(), doPost(), doPut(), doDelete(),
doTrace(), doOptions(), doHead() )
 So, the developers has to override the
required doXxx() methods into their
servlet classes.
 The reason why doXxx() methods are not
declared as abstract methods is, if they
are declared as abstract then a developer
has to override all of them into their
servlet classes. It makes burden on
developers.
 HttpServlet class provides a provision to
define different actions/logics for
different HTTP request methods.
 For example, for a request method GET, you
can define the logic in doGet() method and
for a request method POST, you can define
the logic in doPost() method.

 In GenericServlet, we can’t define


different actions for different HTTP
methods, but we can do it in HttpServlet
class.

init parameters of a servlet:


--------------------------------
 Suppose, we are hard-coding technical
values in a servlet class.
 The technical values are like, connection
properties or email server properties or
messaging server properties, etc.
 In future, if there is a need to change
the technical properties, then you have to
modify the servlet code, then you have to
re-create a war file then again you have
to re-deploy it in
A server.
 So, to avoid the above process, we can
provide/pass the technical values to a
servlet class from outside of a servlet
class, from web.xml file.
 In web.xml, we need to configure init
parameters.
 Init parameters can be configured using a
tag
<init-param>
 Each init parameter has a key/name and a
value.

<init-param>
<param-name>driverClassName</param-
name>
<param-value>
com.mysql.cj.jdbc.Driver</param-
value>
</init-param>
 A servlet class can able access the init
parameters from ServletConfig object.
 Each servlet class has its own
ServletConfig object.
 If there are 5 servlet classes in a
project then 5 ServletConfig objects are
created.
 A servlet class can read the value of an
init parameter, by calling
getInitParameter() method.
For ex:
String driver =
config.getInitParameter(“driverClassName”)
;

Date: 1 / 4 / 2024
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Index Page</title>
</head>
<body>
New User?? <a
href="Signup.html">Signup</a> <br>
Existing User?? <a
href="Login.html">Signin</a>
</body>
</html>

Signup.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Signup Page</title>
</head>
<body>
<form action = "./signup" method =
"post">
<table>
<tr>
<td>Username</td>
<td> <input type="text" name =
"uname"> </td>
</tr>
<tr>
<td>Password</td>
<td> <input type="password" name =
"pwd"> </td>
</tr>
<tr>
<td>Confirm Password</td>
<td> <input type="password" name =
"cpwd"> </td>
</tr>
</table>
<input type="submit" value =
"singup">
</form>

</body>
</html>

SignupServlet.java
public class SignupServlet extends
HttpServlet {
Connection conn = null;
PreparedStatement pstmt = null;
public void init(ServletConfig config)
throws ServletException {
try {
String driver =
config.getInitParameter("driverClassName");
Class.forName(driver);
String url =
config.getInitParameter("dbUrl");
String username =
config.getInitParameter("username");
String password =
config.getInitParameter("password");
conn =
DriverManager.getConnection(url, username,
password);
String query = "INSERT INTO USERS
VALUES (?, ?)";
pstmt =
conn.prepareStatement(query);
}
catch(Exception ex) {
ex.printStackTrace();
}
}
protected void
doPost(HttpServletRequest req,
HttpServletResponse resp) throws
ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
String username =
req.getParameter("uname");
String password =
req.getParameter("pwd");
String repeatPassword =
req.getParameter("cpwd");
if( !repeatPassword.equals(password)
) {
out.println("<html> <body> ");
out.println("<font
color='red'>");
out.println("Confirm Password
doesn't match with Password!");
out.println("</font> </body>
</html>");
}
else {
try {
pstmt.setString(1, username);
pstmt.setString(2, password);
pstmt.executeUpdate();
out.println("<html> <body>");
out.println("Registration
Success!! <br>");
out.println("<a
href='Login.html'> click here </a> to
login");
out.println("</body>
</html>");
}
catch(Exception ex) {
out.println("<html> <body>");
out.println("Username already
exist!! <br>");
out.println("<a
href='Signup.html'> click here </a> to try
again");
out.println("</body>
</html>");
}
}
out.close();
}
public void destroy() {
try {
if ( pstmt != null ) {
pstmt.close();
}
if( conn != null ) {
conn.close();
}
}
catch(Exception e) {
e.printStackTrace();
}
}

web.xml
<servlet>
<servlet-name>Login</servlet-name>
<servlet-
class>com.ashokit.login.LoginServlet</servl
et-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/loginsrv</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>signup</servlet-name>
<servlet-
class>com.ashokit.login.SignupServlet</serv
let-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-
name>driverClassName</param-name>
<param-
value>com.mysql.cj.jdbc.Driver</param-
value>
</init-param>
<init-param>
<param-name>dbUrl</param-name>
<param-
value>jdbc:mysql://localhost:3306/test</par
am-value>
</init-param>
<init-param>
<param-name>username</param-name>
<param-value>root</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>root</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>signup</servlet-name>
<url-pattern>/signup</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.html</welcome-
file>
</welcome-file-list>

ServletContext object
---------------------
 ServletConfig, ServletContext,
ServletRequest, ServletResponse,
HttpServletRequest, HttpServletResponse,
etc.., all these are interfaces.
 The implementation classes for all the
interfaces of Servlet API, will be
provided by the servers.
 ServletContext is the way in a web
application, to share the data across all
the servlet classes in a project.
 ServletContext object is the global object
of a web application, where all the
servlet classes can access the data from
this object.
 If a servlet class wants to share the data
with others in a project, then it has to
store that data in the context object, so
that others can access it.
 If a developer wants to share data thru
context object then he/she has to
configure context parameters in web.xml
file.
 If a servlet class wants to share data
thru context then that servlet class has
to call setAttribute() method to store the
data.
 The other servlet classes can access the
data thru getAttribute() method.
 ServletConfig object is one for each
servlet class, but ServletContext object
is one for the entire web application.
 A servlet class can obtain ServletContext
object, by calling getServletContext()
method.
ServletContext context =
getServletContext();
 To configure context parameters,
use <context-param> tag under the root tag
<web-app>.
<context-param>
<param-name> </param-name>
<param-value> </param-value>
</context-param>

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Index Page</title>
</head>
<body>
<a href = 'srv1'> link to servlet1 </a>
<br> <br>
<a href = 'srv2'> link to servlet2 </a>
</body>
</html>

web.xml
<context-param>
<param-name>apiKey</param-name>
<param-
value>axjtyio2QnPJv32x</param-value>
</context-param>

<servlet>
<servlet-name>sone</servlet-name>
<servlet-
class>com.ashokit.context.ServletOne</servl
et-class>
</servlet>
<servlet-mapping>
<servlet-name>sone</servlet-name>
<url-pattern>/srv1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>stwo</servlet-name>
<servlet-
class>com.ashokit.context.ServletTwo</servl
et-class>
</servlet>
<servlet-mapping>
<servlet-name>stwo</servlet-name>
<url-pattern>/srv2</url-pattern>
</servlet-mapping>

ServletOne.java
public class ServletOne extends HttpServlet
{
protected void doGet(HttpServletRequest
req, HttpServletResponse resp) throws
ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
ServletContext context =
getServletContext();
String value =
context.getInitParameter("apiKey");
out.println("<html> <body>");
out.println("<font color='green'
size=10>");
out.println("apiKey : " + value);
out.println("</font> </body>
</html>");
out.close();
}

ServletTwo.java
public class ServletTwo extends HttpServlet
{
protected void doGet(HttpServletRequest
req, HttpServletResponse resp) throws
ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
ServletContext context =
getServletContext();
String value =
context.getInitParameter("apiKey");
out.println("<html> <body>");
out.println("<font color='red'
size=10>");
out.println("apiKey : " + value);
out.println("</font> </body>
</html>");
out.close();
}
}

Another example
Date: 5 / 4 / 2024
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Index Page</title>
</head>
<body>

<a href = "Policy.html"> Take policy </a>


<br> <br>
<a href = "CancelPolicy.html"> Cancel
Policy </a> <br> <br>
<a href = "ViewPolicy.html"> View
Policy</a>

</body>
</html>

Policy.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Take Policy</title>
</head>
<body>
<form action = "./issue">
Name : <input type = "text" name =
"name"> <br>
Age : <input type = "text" name =
"age"> <br>
<input type = "submit" value =
"submit">
</form>
</body>
</html>

CancelPolicy.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Cancel Policy</title>
</head>
<body>

<form action = "./cancel">


Policy id : <input type = "text"
name = "policyid"> <br>
<input type = "submit" value =
"submit">
</form>

</body>
</html>

ViewPolicy.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>View Policy</title>
</head>
<body>

<form action = "./view">


Policy id : <input type = "text"
name = "policyid"> <br>
<input type = "submit" value =
"submit">
</form>
</body>
</html>

Policy.java
package com.ashokit.policy;

import java.time.LocalDate;

public class Policy {


private int policyId;
private String name;
private int age;
private LocalDate expiresOn;
public int getPolicyId() {
return policyId;
}
public void setPolicyId(int policyId) {
this.policyId = policyId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public LocalDate getExpiresOn() {
return expiresOn;
}
public void setExpiresOn(LocalDate
expiresOn) {
this.expiresOn = expiresOn;
}

PolicyIssuanceServlet.java
public class PolicyIssuanceServlet extends
HttpServlet {
protected void doGet(HttpServletRequest
req, HttpServletResponse resp) throws
ServletException, IOException {
//read the input data
String name =
req.getParameter("name");
int age =
Integer.parseInt(req.getParameter("age"));
//generating policy id randomly
Random random = new Random();
int policyId =
random.nextInt(100000)+1;
Policy policy = new Policy();
policy.setPolicyId(policyId);
policy.setName(name);
policy.setAge(age);
policy.setExpiresOn(LocalDate.of(2025,
8, 15));
//get the ServletContext object
ServletContext context =
getServletContext();
Map<Integer, Policy> polociesMap =
null;
if (
context.getAttribute("polocies") == null )
{
polociesMap = new HashMap<>();
}
else {
polociesMap = (Map)
context.getAttribute("polocies");
}
int policyCount = 0;
if(
context.getAttribute("policyCount") ==
null) {
policyCount=1;
}
else {
policyCount = (Integer)
context.getAttribute("policyCount");
policyCount++;
}

polociesMap.put(policyId, policy);
//set/store the policiesMap object
into the context
context.setAttribute("polocies",
polociesMap);
//store the policy count into the
context
context.setAttribute("policyCount",
policyCount);
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<html><body>");
out.println("<h2> Your policy is
successfully created with id : "+ policyId
+"</h2>");
out.println("<br>");
out.println("<a href='index.html'>
click here </a> to goto index page");
out.println("</body> </html>");
out.close();
}
}

PolicyCancelServlet.java
public class PolicyCancelServlet extends
HttpServlet {
@Override
protected void doGet(HttpServletRequest
req, HttpServletResponse resp) throws
ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
int policyId =
Integer.parseInt(req.getParameter("policyid
"));
//get the ServletContext object
ServletContext context =
getServletContext();
//read the map from context
associated with the key polocies
Map<Integer, Policy> polociesMap =
(Map) context.getAttribute("polocies");
//read the policy count from the
context
int policyCount = (Integer)
context.getAttribute("policyCount");
if ( polociesMap.remove(policyId) !=
null ) {
policyCount--;
//store the values back to the
context
context.setAttribute("polocies",
polociesMap);
context.setAttribute("policyCount",
policyCount);
out.println("<html> <body> ");
out.println("<h2> Your policy
with id: " + policyId+" is cancelled
</h2>");
out.println("<br>");
out.println("<a
href='index.html'> click here </a> to goto
index page");
out.println("</body> </html>");
}
else {
out.println("<html> <body> ");
out.println("<h2>policy with id:
" + policyId+" doesn't exist!! </h2>");
out.println("<br>");
out.println("<a
href='index.html'> click here </a> to goto
index page");
out.println("</body> </html>");
}
out.close();
}

PolicyViewServlet.java
public class PolicyViewServlet extends
HttpServlet {
@Override
protected void doGet(HttpServletRequest
req, HttpServletResponse resp) throws
ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
int policyId =
Integer.parseInt(req.getParameter("policyid
"));
//get the ServletContext object
ServletContext context =
getServletContext();
//read the map from context
associated with the key polocies
Map<Integer, Policy> polociesMap =
(Map) context.getAttribute("polocies");
//read the policy count from the
context
int policyCount = (Integer)
context.getAttribute("policyCount");
Policy policy =
polociesMap.get(policyId);
if(policy != null) {
out.println("<html> <body>");
out.println("<h2>");
out.println("policy id : " +
policy.getPolicyId());
out.println("<br>");
out.println("Name : " +
policy.getName());
out.println("<br>");
out.println("Age : " +
policy.getAge());
out.println("<br>");
out.println("Expires on : " +
policy.getExpiresOn());
out.println("<hr>");
out.println("The total number of
polices : " + policyCount);
out.println("<br>");
out.println("<a
href='index.html'> click here </a> to goto
index page");
out.println(" </h2> </body>
</html> ");
}
else {
out.println("<html> <body>");
out.println("<h2>");
out.println("Policy with
id :"+policyId + " doesn't exist!!");
out.println("<br>");
out.println("<a
href='index.html'> click here </a> to goto
index page");
out.println("</h2> </body>
</html>");
}

Web.xml

<servlet>
<servlet-name>issue</servlet-name>
<servlet-
class>com.ashokit.policy.PolicyIssuanceServ
let</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>issue</servlet-name>
<url-pattern>/issue</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>cancel</servlet-name>
<servlet-
class>com.ashokit.policy.PolicyCancelServle
t</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cancel</servlet-name>
<url-pattern>/cancel</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>view</servlet-name>
<servlet-
class>com.ashokit.policy.PolicyViewServlet<
/servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>view</servlet-name>
<url-pattern>/view</url-pattern>
</servlet-mapping>
RequestDispatching in servlets:
-------------------------------
 Request Dispatching is a mechanism which
allows a servlet to forward a request to
another servlet/JSP/HTML or a servlet can
include the
response/output of another
servlet/JSP/HTML into the current servlet.
 In the above diagram, SecurityServlet
class is forwarding the request to
AdminServlet class.
 At a time, a servlet class can forward the
request to only one servlet class.
 When a request is forwarded, the target
servlet will generates the complete
response.
 When a request is forwarded, the
parameters of request are also forwarded
automatically.
 In the above diagram, when a profile is
created or updated then the request is
forwarded to ProfileViewServlet.
 ProfileViewServlet class is including the
response of HeaderServlet and
FooterServlet classes into it and then
sending the response to the client.
 A servlet class can include the response
of multiple servlet classes at a time.
 To forward a request or to include a
response, RequestDispatcher object is
required.
 Call/invoke getRequestDispatcher() of
request object, to obtain
RequestDispatcher object.

RequestDispatcher dispatcher =
request.getRequestDispatcher(“url of
target resource”);
 The methods of RequestDispatcher are,
1. forward(request, response)
2. include(request, response)

Example
Date: 10 / 4 / 2024

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Index Page</title>
</head>
<body>

<form action = "./entry">


<input type = "radio" name = "option"
value = "build"> Build Profile <br>
<input type = "radio" name = "option"
value = "update"> Update Profile <br>
<input type = "submit" value = "Yes I
want to build/update">
</form>

</body>
</html>

BuildProfile.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Build Profile</title>
</head>
<body>
<form action = "./buildSrv" method =
"post">
FirstName : <input type = "text" name =
"fname"> <br>
LastName : <input type = "text" name =
"lname"> <br>
Email : <input type = "email" name =
"email"> <br>
DOB : <input type = "date" name =
"dob"> <br>
Contact : <input type = "text" name =
"contact"> <br>
<input type = "submit" value =
"submit">
</form>

</body>
</html>

EntryServlet.java
@WebServlet( value = "/entry")
public class EntryServlet extends
HttpServlet {
@Override
protected void doGet(HttpServletRequest
req, HttpServletResponse resp) throws
ServletException, IOException {

String choice =
req.getParameter("option");
if( "build".equals(choice) ) {
RequestDispatcher dispatcher =
req.getRequestDispatcher("BuildProfile.html
");
dispatcher.forward(req, resp);
}
else {
RequestDispatcher dispatcher =
req.getRequestDispatcher("UpdateProfile.htm
l");
dispatcher.forward(req, resp);
}
}

ProfileCreateServlet.java
@WebServlet( value = "/buildSrv")
public class ProfileCreateServlet extends
HttpServlet {
@Override
protected void
doPost(HttpServletRequest req,
HttpServletResponse resp) throws
ServletException, IOException {
//read the input
String firstName =
req.getParameter("fname");
String lastName =
req.getParameter("lname");
String email =
req.getParameter("email");
String dob =
req.getParameter("dob");
String contact =
req.getParameter("contact");
String QUERY = "INSERT INTO
USERS_PROFILE VALUES ( ?, ?, ?, ?, ?)";

try {
//To convert a date from string
to date format
SimpleDateFormat sdf = new
SimpleDateFormat("yyyy-MM-dd");
Date dateOfBirth =
sdf.parse(dob);
//convert contact from string to
int
int phone =
Integer.parseInt(contact);

Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://l
ocalhost:3306/test", "root", "root");
PreparedStatement pstmt =
conn.prepareStatement(QUERY);
pstmt.setString(1, firstName);
pstmt.setString(2, lastName);
pstmt.setString(3, email);
java.sql.Date sqlDate = new
java.sql.Date(dateOfBirth.getTime());
pstmt.setDate(4, sqlDate);
pstmt.setInt(5, phone);
pstmt.executeUpdate();
pstmt.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
RequestDispatcher dispatcher =
req.getRequestDispatcher("viewSrv");
dispatcher.forward(req, resp);

ProfileViewServlet.java
@WebServlet( value = "/viewSrv")
public class ProfileViewServlet extends
HttpServlet {
@Override
protected void
doPost(HttpServletRequest req,
HttpServletResponse resp) throws
ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();

String query = "SELECT * FROM


USERS_PROFILE WHERE EMAIL = ?";
out.println("<html> <body>");
try {

Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://l
ocalhost:3306/test", "root", "root");
PreparedStatement pstmt =
conn.prepareStatement(query);
String email =
req.getParameter("email");
pstmt.setString(1, email);
ResultSet rs =
pstmt.executeQuery();
rs.next();
RequestDispatcher dispatcher1 =
req.getRequestDispatcher("headerSrv");
dispatcher1.include(req, resp);
out.println("<hr>");
out.println("FirstName : "+
rs.getString(1));
out.println("<br>");
out.println("LastName : "+
rs.getString(2));
out.println("<br>");
out.println("Email : "+
rs.getString(3));
out.println("<br>");
out.println("DOB : "+
rs.getString(4));
out.println("<br>");
out.println("Contact : "+
rs.getString(5));
out.println("<hr>");
RequestDispatcher dispatcher2 =
req.getRequestDispatcher("footerSrv");
dispatcher2.include(req, resp);
rs.close();
pstmt.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
out.println("</body> </html>");
out.close();
}

}
HeaderSevlet.java
@WebServlet( value = "/headerSrv")
public class HeaderServlet extends
HttpServlet {
@Override
protected void
doPost(HttpServletRequest req,
HttpServletResponse resp) throws
ServletException, IOException {
PrintWriter out = resp.getWriter();
out.println("<h3> <font color =
'blue'>");
out.println("ZEBSTER Private Ltd");
out.println("</h3> </font>");
//don't write out.close() here
}

FooterServlet.java
@WebServlet( value = "/footerSrv")
public class FooterServlet extends
HttpServlet {
@Override
protected void
doPost(HttpServletRequest req,
HttpServletResponse resp) throws
ServletException, IOException {
PrintWriter out = resp.getWriter();
out.println("<h5>");
out.println("&copy; All rights
reserved 2024-25");
out.println("</h5>");
//don't write out.close() here
}

CREATE THE BELOW TABLE IN MYSQL:


CREATE TABLE USERS_PROFILE (
FIRSTNAME VARCHAR(20),
LASTNAME VARCHAR(20),
EMAIL VARCHAR(30) PRIMARY KEY,
DOB DATE,
CONTACT INT(10)
);

SESSION MANAGEMENT IN SERVLETS


===================================
===
 By default, HTTP protocol exhibits
stateless behavior.
 The HTTP protocol doesn’t remember
anything about previous request, in
the current request.
 Even though, same client is sending
multiple requests to a server, HTTP
protocol assumes that different
clients are sending the requests.
 Each request will be treated as
independent request to a server.
 By default, web application also
exhibits stateless behavior.
 Session management is a mechanism,
which provides stateful communication
between a server and a client over
multiple requests.
 Stateful behavior means, the web
application will remember the
information/data of a client over
multiple requests.
 A session object is created in a
server, for each client to manage the
data/information of a client.
 The session objects are created as one
per each client. Suppose, if there are
two clients/users has logged in, then
Two session objects are created.
 For example, one client/user has made
5 requests to a server, then one
session object only created, because
the client is one client only.

How to create a session object?


 Call getSession() method of request
object, to create a session object.
 HttpSession session =
request.getSession();
 While calling getSession() method, we
can pass a boolean value as a
parameter also.
 getSession() and getSession(true) both
behavious like same. They return
existing session object, if not exist
then they create new session object.
 getSession(false) returns exisiting
session object, if not exist then it
returns null.
 HttpSession session=req.getSession();
 HttpSession session=req.getSession(true);
 HttpSession session=req.getSession(false);

How to store/retrieve/remove the state?


1. setAttribute(key, value)
2. getAttribute(key)
3. removeAttribute(key)
How to remove a session object?
 A session object gets removed from a
server, in the following two cases.
 1. When a user logout
 2. after a period of inactivity
 To remove session object, when a user
logout,
Call invalidate() method.
session.invalidate();
 Inactivity period will be different from
one server to another server.
 For ex, in Tomcat, inactivity period is 30
minutes, but in weblogic it is 1 hour.
 To set inactive period explicity, call
setMaxInactiveInterval() method.

session.setMaxInactiveInterval(60);//
seconds
Date: 12th Apr, 2024
How does a server identify the client?

Example
//If continue, redirect the user to

Products.html

//if checkout, read the cart from


session object

Date: 13th April, 2024


index.html
-----------
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login Page</title>
</head>
<body>

<form action = "./login" method = "post">


Username : <input type = "text" name =
"username"> <br>
Password : <input type = "password"
name = "password"> <br>
<input type = "submit" value =
"submit">
</form>

</body>
</html>

products.html
-------------
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Product List</title>
</head>
<body>
<form action = "./add-to-cart">
<input type = "checkbox" name =
"product" value = "p-1231"> Samsung QLED
TV <br>
<input type = "checkbox" name =
"product" value = "p-1241"> Macbook Pro
<br>
<input type = "checkbox" name =
"product" value = "p-1251"> Realme 9pro
<br>
<input type = "checkbox" name =
"product" value = "p-1261"> LG Micro Owen
<br>
<input type = "submit" value = "Add to
cart">
</form>

</body>
</html>

next.html
---------
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Next Page</title>
</head>
<body>
<a href = "./view?option=continue">
continue shopping </a> <br> <br>
<a href = "./view?option=checkout">
checkout </a>

</body>
</html>

LoginServlet.java
------------------
@WebServlet( value = "/login")
public class LoginServlet extends
HttpServlet {
@Override
protected void
doPost(HttpServletRequest req,
HttpServletResponse resp) throws
ServletException, IOException {
//read the username and password
from request
String username =
req.getParameter("username");
String password =
req.getParameter("password");
if(authenticate(username,password))
{
//create session object
HttpSession session =
req.getSession();
//add the username in session
object
session.setAttribute("username",
username);

resp.sendRedirect("products.html");
}
else {
resp.sendRedirect("index.html");
}
}
private boolean authenticate(String
username, String password) {
return username!=null && !
username.isEmpty() && password!=null && !
password.isEmpty();
}

CartServlet.java
----------------
@WebServlet( value = "/add-to-cart")
public class CartServlet extends
HttpServlet {
private static List<Product>
productsList=null;
static {
productsList = new
ArrayList<Product>();
productsList.add(new Product("p-
1231", "Samsung QLED TV", 250000.0));
productsList.add(new Product("p-
1241", "Macbook Pro", 175000.0));
productsList.add(new Product("p-
1251", "Realme 9Pro", 25000.0));
productsList.add(new Product("p-
1261", "LG Micro Owen", 14000.0));
}
@Override
protected void doGet(HttpServletRequest
req, HttpServletResponse resp) throws
ServletException, IOException {
String[] productIds =
req.getParameterValues("product");
HttpSession session =
req.getSession(false);
List<Product> cart =
(List<Product>)
session.getAttribute("cart");
if(cart == null) {
cart = new ArrayList<Product>();
}

for ( String pid : productIds) {


Product selectedProduct =
productsList.stream().filter(p ->
p.getProductId().equals(pid)).findFirst().o
rElse(null);
if(selectedProduct != null) {
cart.add(selectedProduct);
}
}
session.setAttribute("cart", cart);
resp.sendRedirect("next.html");

CartViewServlet.java
---------------------
@WebServlet(value = "/view")
public class CartViewServlet extends
HttpServlet {
@Override
protected void doGet(HttpServletRequest
req, HttpServletResponse resp) throws
ServletException, IOException {
String str =
req.getParameter("option");
if( str.equals("continue") ) {
resp.sendRedirect("products.html");
}
else {
HttpSession session =
req.getSession(false);
resp.setContentType("text/html");
PrintWriter out =
resp.getWriter();
List<Product> cart =
(List<Product>)
session.getAttribute("cart");
String username = (String)
session.getAttribute("username");
out.println("<html> <body>");
out.println("<h3> Hello "+
username +"! </h3>");
out.println("<br>");
out.println("Your cart
items ....");
out.println("<br>");
out.println("<ol>");
for(Product p : cart) {
out.println("<li>");
out.println(p.getProductId()
+" "+p.getProductName()+"
"+p.getPrice());
out.println("</li>");
}
out.println("</ol>");
out.println("<br>");
out.println("<a href='./logout'>
Logout </a>");
out.println("</body> </html>");
out.close();
}
}

LogoutServlet.java
-------------------
@WebServlet(value = "/logout")
public class LogoutServlet extends
HttpServlet {
@Override
protected void doGet(HttpServletRequest
req, HttpServletResponse resp) throws
ServletException, IOException {
HttpSession session =
req.getSession(false);
session.invalidate();
resp.sendRedirect("index.html");
}

Product.java
-----------
package com.ashokit.cart;

public class Product {


private String productId;
private String productName;
private double price;
public Product() {
}
public Product(String productId, String
productName, double price) {
super();
this.productId = productId;
this.productName = productName;
this.price = price;
}
public String getProductId() {
return productId;
}
public void setProductId(String
productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String
productName) {
this.productName = productName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}

Filters in web applications

 Filters are classes like servlets.


 Filters are created to define pre-
handle and/or post-handle logic
for servlets.
 While a request is going towards a
servlet class and while response
from a servlet class is going
towards the client, filters are
get executed by the web container.
 Instead of defining pre/post
handle logic in servlet classes,
we can separate them into a
filter.

 In the above diagram, the filter


class verifies the user and role
of the user.
 If the user is ADMIN then only it
allows the request to either
UpdateEmpServlet or
DeleteEmpServlet.

 In a web application, we can


create multiple filter classes
also, to define independent
pre/post processing logics.
 In the above diagram, we have
created filter1 to check whether
the use is an ADMIN or not
 If the user is ADMIN, then we have
created filter2 to check whether
he/she has a secret key to access
the servlet class or not.

How to create a filter?


 The only way of creating of a
filter is by implementing Filter
interface.
 The life cycle methods are,
init(), doFilter() and destroy().
 The init() and destroy() methods
are called for once, and
doFilter() method is called for
every request by the web
container.
 The FilterChain object is used to
move the request from current
filter to the next filter, and if
there is no next filter, the
request is moved to the servlet
class.

How to configure a filter?


 In web.xml file, you have to use
<filter> & <filter-mapping> tags.

<filter>
<filter-name>xxxx</filter-
name>
<filter-class>xxxx</filter-
class>
</filter>
<filter-mapping>
<filter-name>xxxx</filter-
name>
<url-pattern>/xxx</url-
pattern>
</filter-mapping>

 If you don’t to write the


configuration in web.xml file,
then you should use @WebFilter
annotation.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Index Page</title>
</head>
<body>

<form action = "./viewsrv" method =


"post">
<table>
<tr>
<td>Username</td>
<td> <input type = "text" name
= "uname"> </td>
</tr>
<tr>
<td>Password</td>
<td> <input type = "password"
name = "pwd"> </td>
</tr>
</table>
<input type = "submit" value =
"SUBMIT" >
</form>

</body>
</html>

User.java
public class User {
private String username;
private String password;
private String role;
public User() {
// TODO Auto-generated constructor
stub
}

public User(String username, String


password, String role) {
super();
this.username = username;
this.password = password;
this.role = role;
}
//setters & getters
}
AuthorizationFilter.java
@WebFilter( value = "/viewsrv")
public class AuthorizationFilter implements
Filter {
List<User> usersList;
@Override
public void init(FilterConfig
filterConfig) throws ServletException {
usersList = new ArrayList<>();
usersList.add(new User("John",
"John@123", "ADMIN"));
usersList.add(new User("Manoj",
"Manoj@123", "EMPLOYEE"));
usersList.add(new User("Harini",
"Hari@123", "ADMIN"));
}
@Override
public void doFilter(ServletRequest
req, ServletResponse resp, FilterChain
chain)
throws IOException,
ServletException {
String username =
req.getParameter("uname");
String password =
req.getParameter("pwd");
User user = usersList
.stream()
.filter(u ->
u.getUsername().equals(username) &&
u.getPassword().equals(password)&&
u.getRole().equals("ADMIN"))
.findFirst()
.orElse(null);
if( user != null) {
chain.doFilter(req, resp);
}
else {
PrintWriter out =
resp.getWriter();
out.println("<html> <body>");
out.println("<h3> <font color =
'red'>");
out.println("Username/Password is
invalid or the role is not ADMIN !!");
out.println("</font> </h3>");
out.println("<br>");
out.println("<a href=index.html>
click here </a>");
out.println("</body></html>");
out.close();
}

}
@Override
public void destroy() {
usersList = null;
}

ViewEmployeesServlet.java
@WebServlet( value = "/viewsrv")
public class ViewEmployeesServlet extends
HttpServlet {
@Override
protected void
doPost(HttpServletRequest req,
HttpServletResponse resp) throws
ServletException, IOException {
PrintWriter out = resp.getWriter();
String dbURL =
"jdbc:mysql://localhost:3306/test";
String dbUsername = "root";
String dbPassword = "root";
try {

Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn =
DriverManager.getConnection(dbURL,
dbUsername, dbPassword);
Statement stmt =
conn.createStatement();
ResultSet rs =
stmt.executeQuery("SELECT * FROM EMP");
out.println("<html> <body>");
out.println("<table border =
1>");
while(rs.next()) {
out.println("<tr>");
out.println("<td>" +
rs.getString(1) + "</td>");
out.println("<td>" +
rs.getString(2) + "</td>");
out.println("<td>" +
rs.getString(3) + "</td>");
out.println("<td>" +
rs.getString(4) + "</td>");
out.println("</tr>");
}
out.println("</table>");
out.println("</body> </html>");
rs.close();
stmt.close();
conn.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
out.close();
}
}

You might also like