Servlet Notes
Servlet Notes
----------------------
Desktop application:
2. Back end
3. Database
Date: 21 / 3 / 2024
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
Date: 26 / 3 / 2024
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>
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.
<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>
</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>
</body>
</html>
ViewPolicy.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>View Policy</title>
</head>
<body>
Policy.java
package com.ashokit.policy;
import java.time.LocalDate;
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>
</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();
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("© All rights
reserved 2024-25");
out.println("</h5>");
//don't write out.close() here
}
session.setMaxInactiveInterval(60);//
seconds
Date: 12th Apr, 2024
How does a server identify the client?
Example
//If continue, redirect the user to
Products.html
</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>();
}
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;
<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>
</body>
</html>
User.java
public class User {
private String username;
private String password;
private String role;
public User() {
// TODO Auto-generated constructor
stub
}
}
@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();
}
}