Servlet Notes

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 4

SERVLET

A website is a collection of static files(webpages) such as HTML pages, images,


graphics etc. A Web application is a web site with dynamic functionality on the
server. Google, Facebook, Twitter are examples of web applications.

HTTP is a protocol that clients and servers use on the web to communicate.

HTTP is a stateless protocol i.e HTTP supports only one request per connection.
This means that with HTTP the clients connect to the server to send one request and
then disconnects. This mechanism allows more users to connect to a given server
over a period of time.

The client sends an HTTP request and the server answers with an HTML page to the
client, using HTTP.

HTTP Methods
HTTP request can be made using a variety of methods, but the ones you will use most
often are Get and Post. The method name tells the server the kind of request that
is being made, and how the rest of the message will be formated.

GET Request to retrieve information from server using a given URI.

POST Request for server to accept the entity enclosed in the body of HTTP method.

URL SYNTEX:

Servlet Technology is used to create web applications. Servlet technology uses Java
language to create web applications

Web applications are helper applications that resides at web server and build
dynamic web pages. A dynamic page could be anything like a page that randomly
chooses picture to display or even a page that displays the current time.

Methods of Servlet interface

LIFECYCLE OF SERVLET METHOD:

S.No. Method Description


1. public void init(ServletConfigconfig): It is used for initializing the
servlet. It is invoked only once by the web container in a servlet life
cycle.

2. public void service(ServletRequestreq, ServletResponse res): It is used


for providing a response to all the incoming request. It is invoked every
time by the web container for each request.

3. public void destroy(): It is used for destroying the servlet. It is


invoked only once in a life cycle of a servlet.

-->NON LIFECYCLE METHOD :

4. public ServletConfiggetServletConfig(): It is used to get the object of


ServletConfig.

5. Public String getServletInfo(): It is used to get information about


writer, copyright etc of a servlet.
web.xml file is a deployment descripter.

HTTPSERVLET ::

HttpServlet is also an abstract class. This class gives implementation of various


service() methods of Servlet interface.

To create a servlet, we should create a class that extends HttpServlet abstract


class. The Servlet class that we will create, must not override service() method.
Our servlet class will override only the doGet() and/or doPost() methods.

The service() method of HttpServlet class listens to the Http methods (GET, POST
etc) from request stream and invokes doGet() or doPost() methods based on Http
Method type.

Httpservlet Api and creating first Servlet Class

Methods of HttpServlet interface


S.No. Method Description
1 public void service(ServletRequest req,ServletResponse res): It is used
for securing the service method by creating objects of request and
response.
2 protected void service(HttpServletRequest req, HttpServletResponse res):
It is used for receiving a service method.
3 protected void doGet(HttpServletRequest req, HttpServletResponse res): It
is invoked by the web container and it is used for handling the GET
request.
4 protected void doPost(HttpServletRequest req, HttpServletResponse res):
It is invoked by the web container and it handles the POST request.
5 protected void doHead(HttpServletRequest req, HttpServletResponse res):
It is invoked by the web container and it handles the HEAD request.
6 protected void doOptions(HttpServletRequest req, HttpServletResponse res):
It is invoked by the web container and it handles the OPTIONS request.
7 protected void doPut(HttpServletRequest req, HttpServletResponse res): It
is invoked by the web container and it handles the OPTIONS request.
8 protected void doTrace(HttpServletRequest req, HttpServletResponse res):
It is invoked by the web container and it handles the TRACE request
9 protected void doDelete(HttpServletRequest req, HttpServletResponse res):
It is invoked by the web container and it handles the DELETE request.
10 protected long getLastModified(HttpServletRequest req): It is used for
getting the time of last modified HttpServletRequest.

HttpSession getSession(): returns the current HttpSession associated with this


request or, if there is no current session and create is true, returns a new
session

Cookies getCookies() returns an array containing all of the Cookie objects the
client sent with this request

PrintWriter getWriter() returns a PrintWriter object that can send character text
to the client.

Difference between Context Init Parameters and Servlet Init Parameter

Context Init parameters Servlet Init parameter


Available to all servlets and JSPs that are part of web. Available to only
servlet for which the <init-param> was configured
Context Init parameters are initialized within the <web-app> not within a specific
<servlet> elements Initialized within the <servlet> for each specific servlet.
ServletContext object is used to get Context Init parameters ServletConfig
object is used to get Servlet Init parameters
Only one ServletContext object for entire web app Each servlet has its own
ServletConfig object

An attribute is an object that is used to share information in a web app. Attribute


allows Servlets to share information among themselves. Attributes can be SET and
GET from one of the following scopes :

request
session
application

Session : We all know that HTTP is a stateless protocol. All requests and responses
are independent. But sometimes you need to keep track of client's activity across
multiple requests. For eg. When a User logs into your website, not matter on which
web page he visits after logging in, his credentials will be with the server, until
he logs out. So this is managed by creating a session.

There are four different techniques used by Servlet application for session
management. They are as follows:

Cookies
Hidden form field
URL Rewriting
HttpSession

HTTPSESSION :: HttpSession object is used to store entire session with a specific


client. We can store, retrieve and remove attribute from HttpSession object. Any
servlet can have access to HttpSession object throughout the getSession() method of
the HttpServletRequest object.

form user input ma jo name="userName" hai vo


servlet mai String n=req.getparameter("userName") same aavu joiey
means form and getparameter ma same aave name or variable
aa name ne vairable ma store karyo n ma
session.setAttribute("key",value);
key= ma koi bhi navu name aapi sakiye che and value jema adho data n variable ma
store karelo che ae

session.setAttribute("karan",n);
data ne bija servlet page ma lai java mate response.sendRedirect("url mapping
name");use thay or requestDispatcher
ana sivay out.print("<a href='servlet2'>visit</a>"); url mappkaryu

servlet na bija page ma data get karva mate


session.getAttribute("karan"); aa key ma bado data aavi jay che aa object
tarike kam kare che so ane typecast karvu pade
out.print("hello"+n)

Cookies
Cookies are small pieces of information that are sent in response from the web
server to the client. Cookies are the simplest technique used for storing client
state.

Cookies are stored on client's computer. They have a lifespan and are destroyed by
the client browser at the end of that lifespan.

Cookies are created using Cookie class present in Servlet API. Cookies are added to
response object using the addCookie() method. This method sends cookie information
over the HTTP response stream. getCookies() method is used to access the cookies
that are added to response object.

Creating a new Cookie :

Cookie ck =new Cookie("username",name);

Sending the cookie to the client

response.addCookie(ck);

Getting cookies from client request

Cookie[] ks=request.getCookies();

Types of Cookies
There are two types of cookies. They are as following:

Session
Persistent
1) Session cookies:
The session cookies do not have any expiration time. It is present in the browser
memory. When the web browser is closed then the cookies are destroyed
automatically.

2) Persistent Cookies:
The Persistent cookies have an expiration time. It is stored in the hard drive of
the user and it is destroyed based on the expiry time.

How cookies works?


When a user Start a web and request information from the website. The website
server replies and it sends a cookie. This cookie is put on the hard drive. Next
time when you return to the same website your computer will send the cookies back.
Now the website server identifies the data and sale your information to other
sellers.

URL REWRITING :

response.sendRedirect("First?user_name="+ name);

("URL MAPPING NAME?KOI BHI NAM="+VARIABLE);