0% found this document useful (0 votes)
5 views106 pages

file_1683178465_0003311_servlet

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 106

SERVLETS

1
Servlet
 Servlet technology is used to create web application (resides at
server side and generates dynamic web page).

 Servlet technology is robust and scalable because of java


language. Before Servlet, CGI (Common Gateway Interface)
scripting language was popular as a server-side programming
language. But there was many disadvantages of this
technology.

 There are many interfaces and classes in the servlet API such
as Servlet, GenericServlet, HttpServlet, ServletRequest,
ServletResponse etc.

2
What is a Servlet?

Servlet can be described in many ways, depending on the context.

 Servlet is a technology i.e. used to create web application.


 Servlet is an API that provides many interfaces and classes including
documentations.
 Servlet is an interface that must be implemented for creating any servlet.
 Servlet is a class that extend the capabilities of the servers and respond to
the incoming request. It can respond to any type of requests.
 Servlet is a web component that is deployed on the server to create
dynamic web page.

3
4
What is web application?

 A web application is an application accessible


from the web. A web application is composed of
web components like Servlet, JSP, Filter etc. and
other components such as HTML. The web
components typically execute in Web Server and
respond to HTTP request.

7
CGI(Commmon Gateway Interface)

8
Disadvantages of CGI

There are many problems in CGI technology:


 If number of clients increases, it takes more time
for sending response.
 For each request, it starts a process and Web
server is limited to start processes.
 It uses platform dependent language e.g. C, C++,
perl.

9
Advantage of Servlet

10
Web Terminology

11
Website
 Website is a collection of related web pages that may contain
text, images, audio and video. The first page of a website is
called home page. Each website has specific internet address
(URL) that you need to enter in your browser to access a
website.
 Website is hosted on one or more servers and can be accessed
by visiting its homepage using a computer network. A website
is managed by its owner that can be an individual, company or
an organization.
A website can be of two types:
 Static Website
 Dynamic Website

12
Static website

13
Dynamic website

14
Servlet API

 The javax.servlet and javax.servlet.http packages


represent interfaces and classes for servlet api.
 The javax.servlet package contains many
interfaces and classes that are used by the servlet
or web container. These are not specific to any
protocol.
 The javax.servlet.http package contains
interfaces and classes that are responsible for http
requests only.
15
Interfaces in javax.servlet package
 There are many interfaces in javax.servlet package. They are as follows:
 Servlet
 ServletRequest
 ServletResponse
 RequestDispatcher
 ServletConfig
 ServletContext
 SingleThreadModel
 Filter
 FilterConfig
 FilterChain
 ServletRequestListener
 ServletRequestAttributeListener
 ServletContextListener
 ServletContextAttributeListener

16
Interfaces in javax.servlet.http package

 There are many interfaces in javax.servlet.http package. They


are as follows:
 HttpServletRequest
 HttpServletResponse
 HttpSession
 HttpSessionListener
 HttpSessionAttributeListener
 HttpSessionBindingListener
 HttpSessionActivationListener
 HttpSessionContext (deprecated now)

17
Classes in javax.servlet.http package

There are many classes in javax.servlet.http package.


They are as follows:
 HttpServlet
 Cookie
 HttpServletRequestWrapper
 HttpServletResponseWrapper
 HttpSessionEvent
 HttpSessionBindingEvent
 HttpUtils (deprecated now)
18
Servlet Interface

 Servlet interface provides common behaviour to


all the servlets.
 Servlet interface needs to be implemented for
creating any servlet (either directly or indirectly).
It provides 3 life cycle methods that are used to
initialize the servlet, to service the requests, and
to destroy the servlet and 2 non-life cycle
methods.

19
Methods of Servlet interface

20
GenericServlet class

 GenericServletclass
implements Servlet, ServletConfig and Serializable interface
s. It provides the implementation of all the methods of these
interfaces except the service method.
 GenericServlet class can handle any type of request so it is
protocol-independent.
 You may create a generic servlet by inheriting the
GenericServlet class and providing the implementation of the
service method.

21
Methods of GenericServlet class
 ere are many methods in GenericServlet class. They are as follows:
 public void init(ServletConfig config) is used to initialize the servlet.
 public abstract void service(ServletRequest request, ServletResponse response) provides
service for the incoming request. It is invoked at each time when user requests for a servlet.
 public void destroy() is invoked only once throughout the life cycle and indicates that servlet
is being destroyed.
 public ServletConfig getServletConfig() returns the object of ServletConfig.
 public String getServletInfo() returns information about servlet such as writer, copyright,
version etc.
 public void init() it is a convenient method for the servlet programmers, now there is no need
to call super.init(config)
 public ServletContext getServletContext() returns the object of ServletContext.
 public String getInitParameter(String name) returns the parameter value for the given
parameter name.
 public Enumeration getInitParameterNames() returns all the parameters defined in the
web.xml file.
 public String getServletName() returns the name of the servlet object.
 public void log(String msg) writes the given message in the servlet log file.
 public void log(String msg,Throwable t) writes the explanatory message in the servlet log
file and a stack trace. 22
Servlet Example by inheriting the GenericServlet class

 import java.io.*;
 import javax.servlet.*;

 public class First extends GenericServlet{


 public void service(ServletRequest req,ServletResponse res)
 throws IOException,ServletException{

 res.setContentType("text/html");

 PrintWriter out=res.getWriter();
 out.print("<html><body>");
 out.print("<b>hello generic servlet</b>");
 out.print("</body></html>");

 }
 }
23
HttpServlet class

 The HttpServlet class extends the GenericServlet


class and implements Serializable interface. It
provides http specific methods such as doGet,
doPost, doHead, doTrace etc.

24
Methods of HttpServlet class
There are many methods in HttpServlet class. They are as follows:
 public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected
service method by converting the request and response object into http type.
 protected void service(HttpServletRequest req, HttpServletResponse res) receives the request from the
service method, and dispatches the request to the doXXX() method depending on the incoming http request
type.
 protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET request. It is
invoked by the web container.
 protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST request. It
is invoked by the web container.
 protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD request.
It is invoked by the web container.
 protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the OPTIONS
request. It is invoked by the web container.
 protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT request. It is
invoked by the web container.
 protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the TRACE
request. It is invoked by the web container.
 protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the DELETE
request. It is invoked by the web container.
 protected long getLastModified(HttpServletRequest req) returns the time when HttpServletRequest was
last modified since midnight January 1, 1970 GMT.

25
Life Cycle of a Servlet (Servlet Life Cycle)
The web container maintains the life cycle of a
servlet instance. Let's see the life cycle of the
servlet:
 Servlet class is loaded.

 Servlet instance is created.

 init method is invoked.

 service method is invoked.

 destroy method is invoked.

26
27
28
29
Steps to create a servlet example
There are given 6 steps to create a servlet example. These steps are required for all
the servers.
 The servlet example can be created by three ways:
 By implementing Servlet interface,
 By inheriting GenericServlet class, (or)
 By inheriting HttpServlet class
 The mostly used approach is by extending HttpServlet because it provides http
request specific method such as doGet(), doPost(), doHead() etc.

Here, we are going to use apache tomcat server in this example. The steps are as
follows:
 Create a directory structure
 Create a Servlet
 Compile the Servlet
 Create a deployment descriptor
 Start the server and deploy the project
 Access the servlet 30
1)Create a directory structures
 The directory structure defines that where to put the different
types of files so that web container may get the information
and respond to the client.
 The Sun Microsystem defines a unique standard to be
followed by all the server vendors. Let's see the directory
structure that must be followed to create the servlet.

31
2)Create a Servlet
There are three ways to create the servlet.By implementing the
Servlet interface
 By inheriting the GenericServlet class
 By inheriting the HttpServlet class

The HttpServlet class is widely used to create the servlet


because it provides methods to handle http requests such as
doGet(), doPost, doHead() etc.In this example we are going to
create a servlet that extends the HttpServlet class. In this
example, we are inheriting the HttpServlet class and providing
the implementation of the doGet() method. Notice that get
request is the default request.
32
 import javax.servlet.http.*;
 import javax.servlet.*;
 import java.io.*;
 public class DemoServlet extends HttpServlet{
 public void doGet(HttpServletRequest req,HttpServletResponse res)
 throws ServletException,IOException
 {
 res.setContentType("text/html");//setting the content type
 PrintWriter pw=res.getWriter();//get the stream to write the data

 //writing html in the stream


 pw.println("<html><body>");
 pw.println("Welcome to servlet");
 pw.println("</body></html>");

 pw.close();//closing the stream


 }}

33
3)Compile the servlet
 For compiling the Servlet, jar file is required to be loaded. Different Servers
provide different jar files:

Two ways to load the jar file


1) set classpath
2) paste the jar file in JRE/lib/ext folder

Put the java file in any folder. After compiling the java file, paste the class file of
servlet in WEB-INF/classesdirectory.

34
4)Create the deployment descriptor (web.xml file)
 The deployment descriptor is an xml file, from which Web Container gets the information about the servet
to be invoked.
 The web container uses the Parser to get the information from the web.xml file. There are many xml parsers
such as SAX, DOM and Pull.
 There are many elements in the web.xml file. Here is given some necessary elements to run the simple
servlet program.
Web.xml file
 <web-app>

 <servlet>
 <servlet-name>india</servlet-name>
 <servlet-class>DemoServlet</servlet-class>
 </servlet>

 <servlet-mapping>
 <servlet-name>india</servlet-name>
 <url-pattern>/welcome</url-pattern>
 </servlet-mapping>

 </web-app>

35
Description of the elements of web.xml file
 There are too many elements in the web.xml file. Here is the illustration of
some elements that is used in the above web.xml file. The elements are as
follows:
 <web-app> represents the whole application.
 <servlet> is sub element of <web-app> and represents the servlet.
 <servlet-name> is sub element of <servlet> represents the name of the
servlet.
 <servlet-class> is sub element of <servlet> represents the class of the
servlet.
 <servlet-mapping> is sub element of <web-app>. It is used to map the
servlet.
 <url-pattern> is sub element of <servlet-mapping>. This pattern is used at
client side to invoke the servlet.

36
5)Start the Server and deploy the project
 To start Apache Tomcat server, double click on the startup.bat file under
apache-tomcat/bin directory.

One Time Configuration for Apache Tomcat Server


You need to perform 2 tasks:
 set JAVA_HOME or JRE_HOME in environment variable (It is required to
start server).
 Change the port number of tomcat (optional). It is required if another server
is running on same port (8080).

37
How Servlet works?
It is important to learn how servlet works for understanding
the servlet well. Here, we are going to get the internal detail
about the first servlet program.
 The server checks if the servlet is requested for the first time.
 If yes, web container does the following tasks:
 loads the servlet class.
 instantiates the servlet class.
 calls the init method passing the ServletConfig object
 else
 calls the service method passing request and response objects
 The web container calls the destroy method when it needs to
remove the servlet such as at time of stopping server or
undeploying the project.
38
How web container handles the servlet request?
The web container is responsible to handle the request. Let's see how it
handles the request.

 maps the request with the servlet in the web.xml file.


 creates request and response objects for this request
 calls the service method on the thread
 The public service method internally calls the protected service method
 The protected service method calls the doGet method depending on the
type of request.
 The doGet method generates the response and it is passed to the client.
 After sending the response, the web container deletes the request and
response objects. The thread is contained in the thread pool or deleted
depends on the server implementation.

39
What is written inside the public service method?
 The public service method converts the ServletRequest object into the HttpServletRequest
type and ServletResponse object into the HttpServletResponse type. Then, calls the service
method passing these objects. Let's see the internal code:
 public void service(ServletRequest req, ServletResponse res)
 throws ServletException, IOException
 {
 HttpServletRequest request;
 HttpServletResponse response;
 try
 {
 request = (HttpServletRequest)req;
 response = (HttpServletResponse)res;
 }
 catch(ClassCastException e)
 {
 throw new ServletException("non-HTTP request or response");
 }
 service(request, response);
 }
40
What is written inside the protected service method?
 The protected service method checks the type of request, if request type is get, it
calls doGet method, if request type is post, it calls doPost method, so on. Let's see
the internal code:
 protected void service(HttpServletRequest req, HttpServletResponse resp)
 throws ServletException, IOException
 {
 String method = req.getMethod();
 if(method.equals("GET"))
 {
 long lastModified = getLastModified(req);
 if(lastModified == -1L)
 {
 doGet(req, resp);
 }
 ....
 //rest of the code
 }
 } 41
welcome-file-list in web.xml
The welcome-file-list element of web-app, is used to define a list of
welcome files. Its sub element is welcome-file that is used to define the
welcome file.
A welcome file is the file that is invoked automatically by the server, if you
don't specify any file name.
By default server looks for the welcome file in following order:
 welcome-file-list in web.xml
 index.html
 index.htm
 index.jsp
 If none of these files are found, server renders 404 error.
 If you have specified welcome-file in web.xml, and all the files index.html,
index.htm and index.jsp exists, priority goes to welcome-file.
 If welcome-file-list entry doesn't exist in web.xml file, priority goes to
index.html file then index.htm and at last index.jsp file.
42
Web.xml
 <web-app>

 ....

 <welcome-file-list>
 <welcome-file>home.html</welcome-file>
 <welcome-file>default.html</welcome-file>
 </welcome-file-list>
 </web-app>

 Now, home.html and default.html will be the welcome files.


 If you have the welcome file, you can directory invoke the project as given
below:
 http://localhost:8888/myproject

43
load on startup in web.xml
 The load-on-startup element of web-app loads the servlet at the time of
deployment or server start if value is positive. It is also known as pre
initialization of servlet.
 You can pass positive and negative value for the servlet.

Advantage of load-on-startup element


 As you know well, servlet is loaded at first request. That means it
consumes more time at first request. If you specify the load-on-startup in
web.xml, servlet will be loaded at project deployment time or server start.
So, it will take less time for responding to first request.

Passing positive value


 If you pass the positive value, the lower integer value servlet will be loaded
before the higher integer value servlet. In other words, container loads the
servlets in ascending integer value. The 0 value will be loaded first then 1,
2, 3 and so on.
44
Web.xml
 <web-app>
 ....

 <servlet>
 <servlet-name>servlet1</servlet-name>
 <servlet-class>com.javatpoint.FirstServlet</servlet-class>
 <load-on-startup>0</load-on-startup>
 </servlet>

 <servlet>
 <servlet-name>servlet2</servlet-name>
 <servlet-class>com.javatpoint.SecondServlet</servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>

 ...
 </web-app>
 There are defined 2 servlets, both servlets will be loaded at the time of project deployment or
server start. But, servlet1 will be loaded first then servlet2
 Passing negative value
 If you pass the negative value, servlet will be loaded at request time, at first request. 45
ServletRequest Interface
 An object of ServletRequest is used to provide the client request information to a
servlet such as content type, content length, parameter names and values, header
informations, attributes etc.
Methods of ServletRequest interface

46
Example of ServletRequest to display the name of the user

47
Server
 import javax.servlet.http.*;
 import javax.servlet.*;
 import java.io.*;
 public class DemoServ extends HttpServlet{
 public void doGet(HttpServletRequest req,HttpServletResponse res)
 throws ServletException,IOException
 {
 res.setContentType("text/html");
 PrintWriter pw=res.getWriter();

 String name=req.getParameter("name");//will return value


 pw.println("Welcome "+name);

 pw.close();
 }}

48
RequestDispatcher in Servlet
 The RequestDispatcher interface provides the facility of dispatching the request to
another resource it may be html, servlet or jsp. This interface can also be used to
include the content of another resource also. It is one of the way of servlet
collaboration.

 There are two methods defined in the RequestDispatcher interface.

Methods of RequestDispatcher interface


The RequestDispatcher interface provides two methods. They are:
 public void forward(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Forwards a request from a servlet to
another resource (servlet, JSP file, or HTML file) on the server.

 public void include(ServletRequest request,ServletResponse response)throws


ServletException,java.io.IOException:Includes the content of a resource (servlet,
JSP page, or HTML file) in the response.

49
As you see in the above figure, response of
second servlet is sent to the client. Response of
the first servlet is not displayed to the user.

50
As you can see in the above figure, response of second
servlet is included in the response of the first servlet
that is being sent to the client.

51
52
Example of RequestDispatcher interface

53
54
55
Login.java
 import java.io.*;
 import javax.servlet.*;
 import javax.servlet.http.*;

 public class Login extends HttpServlet {


 public void doPost(HttpServletRequest request, HttpServletResponse response)


 throws ServletException, IOException {

 response.setContentType("text/html");
 PrintWriter out = response.getWriter();

 String n=request.getParameter("userName");
 String p=request.getParameter("userPass");

 if(p.equals("servlet"){
 RequestDispatcher rd=request.getRequestDispatcher("servlet2");
 rd.forward(request, response);
 }
 else{
 out.print("Sorry UserName or Password Error!");
 RequestDispatcher rd=request.getRequestDispatcher("/index.html");
 rd.include(request, response);
 }
 }

 } 56
WelcomeServlet.java
 import java.io.*;
 import javax.servlet.*;
 import javax.servlet.http.*;

 public class WelcomeServlet extends HttpServlet {


 public void doPost(HttpServletRequest request, HttpServletResponse response)


 throws ServletException, IOException {

 response.setContentType("text/html");
 PrintWriter out = response.getWriter();

 String n=request.getParameter("userName");
 out.print("Welcome "+n);
 }

 }

57
web.xml
 <web-app>
 <servlet>
 <servlet-name>Login</servlet-name>
 <servlet-class>Login</servlet-class>
 </servlet>
 <servlet>
 <servlet-name>WelcomeServlet</servlet-name>
 <servlet-class>WelcomeServlet</servlet-class>
 </servlet>

 <servlet-mapping>
 <servlet-name>Login</servlet-name>
 <url-pattern>/servlet1</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
 <servlet-name>WelcomeServlet</servlet-name>
 <url-pattern>/servlet2</url-pattern>
 </servlet-mapping>

 <welcome-file-list>
 <welcome-file>index.html</welcome-file>
 </welcome-file-list> 58
 </web-app>
Session Tracking in Servlets
 Session simply means a particular interval of time.
 Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
 Http protocol is a stateless so we need to maintain state using session tracking techniques.
Each time user requests to the server, server treats the request as the new request. So we need
to maintain the state of an user to recognize to particular user.
 HTTP is stateless that means each request is considered as the new request. It is shown in the
figure given below:

59
Why use Session Tracking?
To recognize the user It is used to recognize the particular
user.

Session Tracking Techniques


There are four techniques used in Session tracking:
 Cookies
 Hidden Form Field
 URL Rewriting
 HttpSession

60
Cookies in Servlet

 A cookie is a small piece of information that is


persisted between the multiple client requests.

 A cookie has a name, a single value, and optional


attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.

61
How Cookie works
By default, each request is considered as a new request. In cookies
technique, we add cookie with response from the servlet. So cookie is
stored in the cache of the browser. After that if request is sent by the user,
cookie is added with request by default. Thus, we recognize the user as the
old user.

62
Types of Cookie
There are 2 types of cookies in servlets.
 Non-persistent cookie
 Persistent cookie

Non-persistent cookie
It is valid for single session only. It is removed each time
when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time
when user closes the browser. It is removed only if user logout
or signout.

63
Advantage of Cookies
 Simplest technique of maintaining the state.
 Cookies are maintained at client side.

Disadvantage of Cookies
 It will not work if cookie is disabled from the
browser.
 Only textual information can be set in Cookie
object.

64
Cookie class

65
Other methods required for using Cookies

 For adding cookie or getting the value from the cookie, we


need some methods provided by other interfaces. They
are:public void addCookie(Cookie ck):method of
HttpServletResponse interface is used to add cookie in
response object.

 public Cookie[] getCookies():method of HttpServletRequest


interface is used to return all the cookies from the browser.

66
67
How to get Cookies?

68
Simple example of Servlet Cookies

 In this example, we are storing the name of the user in the cookie object
and accessing it in another servlet. As we know well that session
corresponds to the particular user. So if you access it from too many
browsers with different values, you will get the different value.

69
index.html
 <form action="servlet1" method="post">
 Name:<input type="text" name="userName"/><br/>
 <input type="submit" value="go"/>
 </form>

70
FirstServlet.java
 import java.io.*;
 import javax.servlet.*;
 import javax.servlet.http.*;

 public class FirstServlet extends HttpServlet {


 public void doPost(HttpServletRequest request, HttpServletResponse response){


 try{

 response.setContentType("text/html");
 PrintWriter out = response.getWriter();

 String n=request.getParameter("userName");
 out.print("Welcome "+n);

 Cookie ck=new Cookie("uname",n);//creating cookie object


 response.addCookie(ck);//adding cookie in the response

 //creating submit button


 out.print("<form action='servlet2'>");
 out.print("<input type='submit' value='go'>");
 out.print("</form>");

 out.close();

 }catch(Exception e){System.out.println(e);}
 }
 }

71
SecondServlet.java
 import java.io.*;
 import javax.servlet.*;
 import javax.servlet.http.*;

 public class SecondServlet extends HttpServlet {


 public void doPost(HttpServletRequest request, HttpServletResponse response){


 try{

 response.setContentType("text/html");
 PrintWriter out = response.getWriter();

 Cookie ck[]=request.getCookies();
 out.print("Hello "+ck[0].getValue());

 out.close();

 }catch(Exception e){System.out.println(e);}
 }

 72
 }
Web.xml
 <web-app>

 <servlet>
 <servlet-name>s1</servlet-name>
 <servlet-class>FirstServlet</servlet-class>
 </servlet>

 <servlet-mapping>
 <servlet-name>s1</servlet-name>
 <url-pattern>/servlet1</url-pattern>
 </servlet-mapping>

 <servlet>
 <servlet-name>s2</servlet-name>
 <servlet-class>SecondServlet</servlet-class>
 </servlet>

 <servlet-mapping>
 <servlet-name>s2</servlet-name>
 <url-pattern>/servlet2</url-pattern>
 </servlet-mapping>
 73
 </web-app>
2) Hidden Form Field
 In case of Hidden Form Field a hidden (invisible) textfield is used for
maintaining the state of an user.
 In such case, we store the information in the hidden field and get it from
another servlet. This approach is better if we have to submit form in all the
pages and we don't want to depend on the browser.

 Let's see the code to store value in hidden field.

<input type="hidden" name="uname" value="Vimal Jaiswal">

Here, uname is the hidden field name and Vimal Jaiswal is the hidden field
value.

74
75
Example of using Hidden Form Field
In this example, we are storing the name of the user in a
hidden textfield and getting that value from another servlet.

76
3)URL Rewriting

 In URL rewriting, we append a token or identifier to the URL


of the next Servlet or the next resource. We can send
parameter name/value pairs using the following format:
 url?name1=value1&name2=value2&??

 A name and a value is separated using an equal = sign, a


parameter name/value pair is separated from another parameter
using the ampersand(&). When the user clicks the hyperlink,
the parameter name/value pairs will be passed to the server.
From a Servlet, we can use getParameter() method to obtain a
parameter value.

77
78
79
4) HttpSession interface
In such case, container creates a session id for each user.The container uses this id
to identify the particular user.An object of HttpSession can be used to perform two
tasks:
1) bind objects
2)view and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.

80
81
Example of using HttpSession
In this example, we are setting the attribute in the session scope in one servlet and
getting that value from the session scope in another servlet. To set the attribute in
the session scope, we have used the setAttribute() method of HttpSession interface
and to get the attribute, we have used the getAttribute method.

82
FirstServlet.java
 import java.io.*;
 import javax.servlet.*;
 import javax.servlet.http.*;

 public class FirstServlet extends HttpServlet {


 public void doGet(HttpServletRequest request, HttpServletResponse response){


 try{

 response.setContentType("text/html");
 PrintWriter out = response.getWriter();

 String n=request.getParameter("userName");
 out.print("Welcome "+n);

 HttpSession session=request.getSession();
 session.setAttribute("uname",n);

 out.print("<a href='servlet2'>visit</a>");

 out.close();

 }catch(Exception e){System.out.println(e);}
 }

83
 }
SecondServlet.java
 import java.io.*;
 import javax.servlet.*;
 import javax.servlet.http.*;

 public class SecondServlet extends HttpServlet {


 public void doGet(HttpServletRequest request, HttpServletResponse response)


 try{

 response.setContentType("text/html");
 PrintWriter out = response.getWriter();

 HttpSession session=request.getSession(false);
 String n=(String)session.getAttribute("uname");
 out.print("Hello "+n);

 out.close();

 }catch(Exception e){System.out.println(e);}
 }
 } 84
web.xml
 <web-app>

 <servlet>
 <servlet-name>s1</servlet-name>
 <servlet-class>FirstServlet</servlet-class>
 </servlet>

 <servlet-mapping>
 <servlet-name>s1</servlet-name>
 <url-pattern>/servlet1</url-pattern>
 </servlet-mapping>

 <servlet>
 <servlet-name>s2</servlet-name>
 <servlet-class>SecondServlet</servlet-class>
 </servlet>

 <servlet-mapping>
 <servlet-name>s2</servlet-name>
 <url-pattern>/servlet2</url-pattern>
 </servlet-mapping>

 </web-app>

85
Database connectivity from the servlet
 import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBConnection extends HttpServlet {


public void service(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet JDBC</title></head>");
out.println("<body>");
out.println("<h1>Servlet JDBC</h1>");
out.println("</body></html>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null; 86
 try {
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection
("jdbc:mysql://192.168.10.59:3306/example","root","root");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM servlet");
// displaying records
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print("\t\t\t");
out.print(rs.getObject(2).toString());
out.print("<br>");
}
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
out.close();
}
}
87
Example 2: Servlet database connectivity
 package com.jwt.servlet;

 import java.io.IOException;
 import java.io.PrintWriter;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.PreparedStatement;

 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;

 public class RegisterServlet extends HttpServlet {


 public void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {

 response.setContentType("text/html");
 PrintWriter out = response.getWriter();

 String n = request.getParameter("userName");
 String p = request.getParameter("password");
 String e = request.getParameter("email");
 String c = request.getParameter("language");

88
 try {
 Class.forName("com.mysql.jdbc.Driver");
 Connection con = DriverManager.getConnection(
 "jdbc:mysql://localhost:3306/servlet", "root", "mukesh");

 PreparedStatement ps = con
 .prepareStatement("insert into USERDETAILS values(?,?,?,?)");

 ps.setString(1, n);
 ps.setString(2, p);
 ps.setString(3, e);
 ps.setString(4, c);

 int i = ps.executeUpdate();
 if (i > 0)
 out.print("You are successfully registered...");

 } catch (Exception e2) {


 System.out.println(e2);
 }

 out.close();
 }

89
 }
Servlet Program
Index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="AddServlet" method="get" align="center">
Enter First Number:<input type="text" name="num1" align="center">
Enter Second Number:<input type="text" name="num2" algin="center">
<input type="submit" value="Add" align="center">
</form>
</body>
</html>

90
AddServlet.java
package com.java1; IOException {
import java.io.PrintWriter; PrintWriter pw = response.getWriter();
import java.io.IOException; int i = Integer.parseInt(request.getParameter("num1"));
import jakarta.servlet.RequestDispatcher; int j = Integer.parseInt(request.getParameter("num2"));
import jakarta.servlet.ServletException; int k = i + j;
import jakarta.servlet.annotation.WebServlet; pw.println("result = "+k);
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet; }
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; }
import jakarta.servlet.http.HttpSession;

/** * Servlet implementation class AddServlet*/


@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/** * Default constructor. */
public AddServlet() {
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,

91
RequestDispatcher
 RequestDispatcher is an interface that allows servlets to
forward or include requests and responses between
different servlets or web resources within the same web
application.
 The RequestDispatcher interface is part of the Java
Servlet API, which provides a way for servlets to handle
HTTP requests and generate dynamic web content.
 The RequestDispatcher is typically used when a servlet
needs to transfer control to another servlet or resource
within the same web application, such as forwarding a
request to another servlet to generate the response or
including the response of another servlet within the
current response. 92
RequestDispatcher
 There are two main methods provided by the RequestDispatcher
interface:
 forward(ServletRequest request, ServletResponse response): This
method forwards the request and response objects to another
servlet or resource, allowing the subsequent servlet or resource to
generate the response. The original request and response objects
are no longer available to the calling servlet after the forward is
performed.
 include(ServletRequest request, ServletResponse response): This
method includes the response of another servlet or resource within
the current response. The calling servlet retains control and
continues processing after the included response is merged with its
own response.

93
As you see in the above figure, response of
second servlet is sent to the client. Response of
the first servlet is not displayed to the user.

94
As you can see in the above figure, response of second
servlet is included in the response of the first servlet
that is being sent to the client.

95
Request Dispatacher
AddServlet.java public AddServlet() {
// TODO Auto-generated constructor stub
package com.java1; }
import java.io.PrintWriter; protected void doGet(HttpServletRequest request,
import java.io.IOException; HttpServletResponse response) throws
import jakarta.servlet.RequestDispatcher; ServletException, IOException {
import jakarta.servlet.ServletException; PrintWriter pw = response.getWriter();
import jakarta.servlet.annotation.WebServlet; int i =
Integer.parseInt(request.getParameter("num1"));
import jakarta.servlet.http.Cookie;
int j =
import jakarta.servlet.http.HttpServlet; Integer.parseInt(request.getParameter("num2"));
import jakarta.servlet.http.HttpServletRequest; int k = i + j;
import jakarta.servlet.http.HttpServletResponse; pw.println("result = "+k);
import jakarta.servlet.http.HttpSession; request.setAttribute("k",k);
RequestDispatcher rd =
@WebServlet("/AddServlet") request.getRequestDispatcher("/Square");
public class AddServlet extends HttpServlet { rd.forward(request, response);
private static final long
serialVersionUID = 1L; }

/** * Default constructor. */

96
Request Dispatacher
Square.java public class Square extends HttpServlet {
package com.java1; private static final long
import java.io.PrintWriter; serialVersionUID = 1L;
import java.io.IOException; protected void doGet(HttpServletRequest
import jakarta.servlet.ServletException; request, HttpServletResponse response)
throws ServletException, IOException {
import
jakarta.servlet.annotation.WebServlet; PrintWriter pw = response.getWriter();
import jakarta.servlet.http.Cookie; int k = (int) request.getAttribute("k");
import jakarta.servlet.http.HttpServlet; k = k * k;
import pw.println("result = "+k);
jakarta.servlet.http.HttpServletRequest; }
import
jakarta.servlet.http.HttpServletResponse; }
import jakarta.servlet.http.HttpSession;
@WebServlet("/Square")

97
Send Redirect

 sendRedirect() is a method provided by the HttpServletResponse


interface that allows a servlet to send a redirect response to the
client's browser, instructing it to request a different URL. This is
often used to redirect a user to a different web page or resource
after a certain action has been performed in the servlet.The
sendRedirect() method is typically used when a servlet needs to
redirect a user to a different URL or web page, such as after
processing a form submission, handling a login request, or
completing a transaction..
 It's important to note that sendRedirect() sends a new response to
the client's browser, and the browser makes a new request to the
specified URL. This means that the original request and response
objects are not available in the redirected page or resource. If you
need to pass data between servlets or resources during a redirect,
you can use query parameters, session attributes, or other methods
of data persistence. 98
SendRedirect
AddServlet.java /** * Default constructor. */
public AddServlet() {
package com.java1; // TODO Auto-generated constructor stub
import java.io.PrintWriter; }
import java.io.IOException; protected void doGet(HttpServletRequest request,
import jakarta.servlet.RequestDispatcher; HttpServletResponse response) throws
import jakarta.servlet.ServletException; ServletException, IOException {
import jakarta.servlet.annotation.WebServlet; PrintWriter pw = response.getWriter();
import jakarta.servlet.http.Cookie; int i =
Integer.parseInt(request.getParameter("num1"));
import jakarta.servlet.http.HttpServlet;
int j =
import jakarta.servlet.http.HttpServletRequest; Integer.parseInt(request.getParameter("num2"));
import jakarta.servlet.http.HttpServletResponse; int k = i + j;
import jakarta.servlet.http.HttpSession; response.sendRedirect("Square?k=" + k);

@WebServlet("/AddServlet") }
public class AddServlet extends HttpServlet {
private static final long
serialVersionUID = 1L;

99
SendRedirect
Square.java public class Square extends HttpServlet {
package com.java1; private static final long
import java.io.PrintWriter; serialVersionUID = 1L;
import java.io.IOException; protected void doGet(HttpServletRequest
import jakarta.servlet.ServletException; request, HttpServletResponse response)
throws ServletException, IOException {
import
jakarta.servlet.annotation.WebServlet; PrintWriter pw = response.getWriter();
import jakarta.servlet.http.Cookie; int k = (int) request.getAttribute("k");
import jakarta.servlet.http.HttpServlet; int k =
Integer.parseInt(request.getParameter("k"));
import
jakarta.servlet.http.HttpServletRequest; k = k * k;
import pw.println("result = "+k);
jakarta.servlet.http.HttpServletResponse; }
import jakarta.servlet.http.HttpSession;
@WebServlet("/Square") }

100
Session Management
AddServlet.java
/** * Default constructor. */
package com.java1; public AddServlet() {
import java.io.PrintWriter; // TODO Auto-generated constructor
stub
import java.io.IOException;
}
import jakarta.servlet.RequestDispatcher;
protected void doGet(HttpServletRequest
import jakarta.servlet.ServletException;
request, HttpServletResponse response)
import throws ServletException, IOException {
jakarta.servlet.annotation.WebServlet;
PrintWriter pw = response.getWriter();
import jakarta.servlet.http.Cookie;
int i =
import jakarta.servlet.http.HttpServlet; Integer.parseInt(request.getParameter("num
import 1"));
jakarta.servlet.http.HttpServletRequest; int j =
import Integer.parseInt(request.getParameter("num
jakarta.servlet.http.HttpServletResponse; 2"));
import jakarta.servlet.http.HttpSession; int k = i + j;
HttpSession session = request.getSession();
@WebServlet("/AddServlet") session.setAttribute("k", k);
public class AddServlet extends HttpServlet response.sendRedirect("Square");
{ 101
private static final long }
Session Management
Square.java private static final long
package com.java1; serialVersionUID = 1L;
import java.io.PrintWriter; protected void
import java.io.IOException; doGet(HttpServletRequest request,
HttpServletResponse response) throws
import jakarta.servlet.ServletException; ServletException, IOException {
import PrintWriter pw = response.getWriter();
jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
HttpSession session =
import jakarta.servlet.http.HttpServlet; request.getSession();
import int k = (int) session.getAttribute("k");
jakarta.servlet.http.HttpServletRequest;
k = k * k;
import
jakarta.servlet.http.HttpServletRespons pw.println("result = "+k);
e; }
import jakarta.servlet.http.HttpSession;
@WebServlet("/Square") } 102
public class Square extends
Cookies
 Cookies are the textual information that is stored in key-value pair
format to the client’s browser during multiple requests. It is one of
the state management techniques in session tracking.
 Basically, the server treats every client request as a new one so to
avoid this situation cookies are used. When the client generates a
request, the server gives the response with cookies having an id
which are then stored in the client’s browser.
 Thus if the client generates a second request, a cookie with the
matched id is also sent to the server. The server will fetch the cookie
id, if found it will treat it as an old request otherwise the request is
considered new.
 For example when you log in to a website and select "Remember
Me" or "Keep me signed in" option. The website may use a cookie to
remember your login information, so that you don't have to enter it
every time you visit the site.
103
104
Cookie
AddServlet.java }
protected void doGet(HttpServletRequest request,
package com.java1; HttpServletResponse response) throws ServletException,
import java.io.PrintWriter; IOException {
import java.io.IOException; PrintWriter pw = response.getWriter();
import jakarta.servlet.RequestDispatcher; int i = Integer.parseInt(request.getParameter("num1"));
import jakarta.servlet.ServletException; int j = Integer.parseInt(request.getParameter("num2"));
import jakarta.servlet.annotation.WebServlet; int k = i + j;
import jakarta.servlet.http.Cookie; pw.println("result = "+k);
import jakarta.servlet.http.HttpServlet; Cookie cookie = new Cookie("k",k + "");
import jakarta.servlet.http.HttpServletRequest; response.addCookie(cookie);
import jakarta.servlet.http.HttpServletResponse; response.sendRedirect("Square");
import jakarta.servlet.http.HttpSession;
}
@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
private static final long serialVersionUID =
1L;

/** * Default constructor. */


public AddServlet() {
// TODO Auto-generated constructor stub

105
Cookie
Square.java serialVersionUID = 1L;
package com.java1; protected void doGet(HttpServletRequest
import java.io.PrintWriter; request, HttpServletResponse response)
import java.io.IOException; throws ServletException, IOException {
import jakarta.servlet.ServletException; PrintWriter pw = response.getWriter();
import //int k = 0;
jakarta.servlet.annotation.WebServlet; //Cookie cookies[] = request.getCookies();
import jakarta.servlet.http.Cookie; //for(Cookie c : cookies) {
import jakarta.servlet.http.HttpServlet; //if(c.getName().equals("k"))
import //k = Integer.parseInt(c.getValue());
jakarta.servlet.http.HttpServletRequest; //}
import //k = k * k;
jakarta.servlet.http.HttpServletResponse; pw.println("result = "+k);
import jakarta.servlet.http.HttpSession; }
@WebServlet("/Square")
public class Square extends HttpServlet { }
private static final long
106

You might also like