Servlets JSP
Servlets JSP
SACHIN KHARADE
Servlet
• Servlet is used to create web applications.
Servlet 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.
SACHIN KHARADE
Types of Servlet
• There are two main servlet types, generic and HTTP
• Generic servlets
SACHIN KHARADE
Types of Servlet (cont’d…)
• HTTP servlets
SACHIN KHARADE
Servlet Life Cycle
• The life cycle of a servlet is controlled by the container in
which the servlet has been deployed. When a request is
mapped to a servlet, the container performs the
following steps.
• If an instance of the servlet does not exist, the Web
container
– Loads the servlet class.
– Creates an instance of the servlet class.
– Initializes the servlet instance by calling the init method.
Initialization is covered in Initializing a Servlet.
• Invokes the service method, passing a request and
response object.
• If the container needs to remove the servlet, it finalizes
the servlet by calling theSACHIN
servlet's
KHARADE
destroy method.
Servlet life cycle methods
The init() method
• The init method is designed to be called only once. It is called when the servlet is first
created. So, it is used for one-time initializations, just as with the init method of
applets.
• The servlet is normally created when a user first invokes a URL corresponding to the
servlet, but you can also specify that the servlet be loaded when the server is first
started.
• When a user invokes a servlet, a single instance of each servlet gets created, with
each user request resulting in a new thread that is handed off to doGet or doPost as
appropriate. The init() method simply creates or loads some data that will be used
throughout the life of the servlet.
• The init method definition looks like this:
SACHIN KHARADE
Http Request Methods
Every request has a header that tells the status of the client. There are
many request methods. Get and Post requests are mostly used.
SACHIN KHARADE
The doGet() Method
A GET request results from a normal request for a URL or from an HTML
form that has no METHOD specified and it should be handled by doGet()
method.
SACHIN KHARADE
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Public class HelloWorld extends HttpServlet
{
String message;
publicvoid init() throws ServletException
{
message ="Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out= response.getWriter();
out.println("<h1>"+ message +"</h1>");
}
public void destroy()
{ }
}
SACHIN KHARADE
Servlet Deployment
By default, a servlet application is located at the path
<Tomcat-installation-directory>/webapps/ROOT
and the class file would reside in
<Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes
It works at client side because it uses the url bar of the browser
to make another request. So, it can work inside and outside the
server.
SACHIN KHARADE
Difference between forward() and sendRedirect()
method
There are many differences between the forward() method of
RequestDispatcher and sendRedirect() method of HttpServletResponse
interface. They are given below:
It can work within the server only. It can be used within and outside
the server.
Example: Example:
request.getRequestDispacher("ser response.sendRedirect("servlet2");
vlet2").forward(request,response);
SACHIN KHARADE
Syntax of sendRedirect() method
response.sendRedirect("http://www.javatpoint.com");
SACHIN KHARADE
example of sendRedirect method in servlet
SACHIN KHARADE
DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.sendRedirect("http://www.google.com");
pw.close();
}
}
SACHIN KHARADE
index.html
<!DOCTYPE html>
<html>
<head>
<title>sendRedirect example</title>
</head>
<body>
<form action="MySearcher">
<input type="text" name="name">
<input type="submit" value="Google Search">
</form>
</body>
</html>
SACHIN KHARADE
MySearcher.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
String name=request.getParameter("name");
response.sendRedirect("https://www.google.co.in/#q="+name);
}
}
SACHIN KHARADE
Session and Cookies
Session simply means a particular interval of time.
The session itself resides in the server. For each request, the client
transmits the session ID in a cookie or, if the browser does not
allow cookies, the server automatically writes the session ID into
the URL.
SACHIN KHARADE
Session and Cookies (cont’d…)
SACHIN KHARADE
Cookie class
javax.servlet.http.Cookie class provides the functionality of using
cookies. It provides a lot of useful methods for cookies.
Constructor Description
SACHIN KHARADE
Useful Methods of Cookie class
Following are given some commonly used methods of the Cookie class.
Method Description
Sets the maximum age of the
public void setMaxAge(int expiry)
cookie in seconds.
SACHIN KHARADE
Other methods required for using Cookies
1.For adding cookie or getting the value from the cookie, we need
some methods provided by other interfaces. They are:
SACHIN KHARADE
Creating Cookie
Cookie ck=new Cookie("user","sonu");//creating cookie object
response.addCookie(ck);//adding cookie in the response
Deleting Cookie
It is mainly used to logout or signout the user.
HTTP is stateless that means each request is considered as the new request.
SACHIN KHARADE
Figure Servlet chaining
Servlet Filters
When a servlet converts one type of content into another, the technique is
called filtering .
A filter is an object that is invoked at the preprocessing and postprocessing of a
request.
It is mainly used to perform filtering tasks such as conversion, logging,
compression, encryption and decryption, input validation etc.
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we
remove the entry of filter from the web.xml file, filter will be removed
automatically and we don't need to change the servlet.
SACHIN KHARADE
Defining Filter
<filter>
<filter-name>...</filter-name>
<filter-class>...</filter-class>
</filter>
<filter-mapping>
<filter-name>...</filter-name>
<url-pattern>...</url-pattern>
</filter-mapping>
</web-app>
SACHIN KHARADE
Example of authenticating user using filter
SACHIN KHARADE
index.html
<form action="servlet1">
Name:<input type="text" name="name"/><br/>
Password:<input type="password" name="password"/><br/>
</form>
SACHIN KHARADE
MyFilter.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
PrintWriter out=resp.getWriter();
String password=req.getParameter("password");
if(password.equals("admin")){
chain.doFilter(req, resp);//sends request to next resource
}
else{
out.print("username or password error!");
RequestDispatcher rd=req.getRequestDispatcher("index.html");
rd.include(req, resp);
}
}
public void destroy() {}
} SACHIN KHARADE
AdminServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("welcome ADMIN");
out.close();
}
}
SACHIN KHARADE
web.xml
<web-app>
<servlet>
<servlet-name>AdminServlet</servlet-name>
<servlet-class>AdminServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AdminServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
</web-app>
SACHIN KHARADE