6 Servlets
6 Servlets
Introduction
Java Servlets are programs that run on a Web or
Application server and act as a middle layer between a
requests coming from a Web browser or other HTTP client
and databases or applications on the HTTP server.
Using Servlets, we can collect input from users through
web page forms, present records from a database or another
source, and create web pages dynamically.
Properties of Servlets :
Servlets work on the server-side.
Servlets capable of handling complex request obtained from
web server.
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 elements such as
HTML, CSS, and JavaScript.
The web components typically execute in Web Server and
respond to the HTTP request.
Servlets
Execution of Servlets :
Execution of Servlets involves the six basic steps:
The clients send the request to the web server.
The web server receives the request.
The web server passes the request to the corresponding servlet.
The servlet processes the request and generate the response in the
form of output.
The servlet send the response back to the web server.
The web server sends the response back to the client and the client
browser displays it on the screen.
Architecture of Servlet
CGI (Common Gateway Interface)
CGI is actually an external application which is written
by using any of the programming languages like C or C+
+.
This is responsible for processing client requests and
generating dynamic content.
Disadvantages of CGI
There are many problems in CGI technology:
If the number of clients increases, it takes more time for sending the
response.
For each request, it starts a process, and the web server is limited to
start processes.
It uses platform dependent language e.g. C, C++, perl.
How CGI works
Advantages of Servlet
Better performance: because it creates a thread for
each request, not process.
Portability: because it uses Java language.
Robust: JVM manages Servlets, so we don't need to
worry about the memory leak, garbage collection, etc.
Secure: because it uses java language.
Servlet
Life Cycle of a Servlet
A servlet life cycle can be defined as the entire process
from its creation till the destruction. The following are the
paths followed by a servlet.
The servlet is initialized by calling the init() method.
The servlet calls service() method to process a client's
request.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector
of the JVM.
Architecture Diagram
Architecture Diagram
First the HTTP requests coming to the server are delegated
to the servlet container.
The servlet container loads the servlet before invoking the
service() method.
Then the servlet container handles multiple requests by
spawning multiple threads, each thread executing the
service() method of a single instance of the servlet.
Life cycle methods
The init() Method
The init method is called only once.
It is called only when the servlet is created, and not called
for any user requests afterwards.
So, it is used for one-time initializations, just as with the
init method of applets.
The init() method simply creates or loads some data that
will be used throughout the life of the servlet.
public void init() throws ServletException { // Initialization
code... }
Life cycle methods
The service() Method
The service() method is the main method to perform the actual
task.
The servlet container (i.e. web server) calls the service() method
to handle requests coming from the client( browsers) and to
write the formatted response back to the client.
Each time the server receives a request for a servlet, the server
spawns a new thread and calls service.
The service() method checks the HTTP request type (GET,
POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut,
doDelete, etc. methods as appropriate.
public void service(ServletRequest request,
ServletResponse response) throws ServletException,
IOException { }
Life cycle methods
The doGet() and doPost() are most frequently used methods
with in each service request.
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.
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException { // Servlet code }
The doPost() Method
A POST request results from an HTML form that
specifically lists POST as the METHOD and it should be
handled by doPost() method.
Life cycle methods
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException { // Servlet code }
The destroy() Method
The destroy() method is called only once at the end of the
life cycle of a servlet.
This method gives the servlet a chance to close database
connections, halt background threads, write cookie lists
or hit counts to disk, and perform other such cleanup
activities.
public void destroy() { // Finalization code... }
Java Servlet classes
Servlets are Java classes which service HTTP requests and
implement the javax.servlet.Servlet interface.
Web application developers typically write servlets that
extend javax.servlet.http.HttpServlet, an abstract class that
implements the Servlet interface and is specially designed
to handle HTTP requests.
GET and POST
Two common methods for the request-response between a
server and client are:
GET- It requests the data from a specified resource
POST- It submits the processed data to a specified resource
Anatomy of Get Request
GET /RegisterDao.jsp?name1=value1&name2=value2
The GET method sends the encoded user information
appended to the page request. The page and the encoded
information are separated by the ?
Never use the GET method if you have password or other
sensitive information to pass to the server.
Anatomy of Post Request
A generally more reliable method of passing information to a
backend program is the POST method.
This packages the information in exactly the same way as
GET method, but instead of sending it as a text string after
a ? (question mark) in the URL it sends it as a separate
message.
This message comes to the backend program in the form of
the standard input which you can parse and use for your
processing.
POST/RegisterDao.jsp HTTP/1.1
1) In case of Get request, only limited In case of post request, large amount of
amount of data can be sent because data is data can be sent because data is sent in
sent in header. body.
2) Get request is not secured because data Post request is secured because data is not
is exposed in URL bar. exposed in URL bar.
3) Get request can be bookmarked. Post request cannot be bookmarked.
5) Get request is more efficient and used Post request is less efficient and used less
more than Post. than get.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>Welcome</body></html>”);
out.close();
}
Deployment container – gets the
information about the servlet to be invoked
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
GET Method Example Using Form
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloForm extends HttpServlet { public void
doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
out.println("<html>\n" + "<head><title>" + title + "</title></head>\
n“ + "<h1 align = \"center\">" + title + "</h1>\n" + "<ul>\n" + "
<li><b>First Name</b>: " + request.getParameter("first_name") +
"\n" + " <li><b>Last Name</b>: " +
request.getParameter("last_name") + "\n" + "</ul>\n" + "</body>"
+ "</html>" ); } }
HTML Code
<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body> irst Name: Last Name:
</html>
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
OUTPUT:
Using GET Method to Read Form Data
First Name: ARUN
Last Name: KUMAR
POST Method Example Using Form
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloForm extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using GET Method to Read Form Data";
out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n“ + "<h1
align = \"center\">" + title + "</h1>\n" + "<ul>\n" + " <li><b>First Name</b>: " +
request.getParameter("first_name") + "\n" + " <li><b>Last Name</b>: " +
request.getParameter("last_name") + "\n" + "</ul>\n" + "</body>" "</html>" ); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
}
}
HTML Code
<html>
<body>
<form action = "HelloForm" method = "POST">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
Passing Checkbox Data to Servlet Program
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CheckBox extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Checkbox Data";
out.println("<html>\n" + "<head><title>" + title + "</title></head>\n" + "<h1 align = \"center\">" + title
+ "</h1>\n" + "<ul>\n" + " <li><b>
Maths Flag : </b>: " + request.getParameter("maths") + "\n" + " <li><b>
Physics Flag: </b>: " + request.getParameter("physics") + "\n" + " <li><b>
Chemistry Flag: </b>: " + request.getParameter("chemistry") + "\n" + "</ul>\n" + "</body>"
"</html>" );
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
doGet(request, response);
} }
HTML Code
<html>
<body>
<form action = "CheckBox" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" checked = "checked" /> Maths
<input type = "checkbox" name = "physics" /> Physics
<input type = "checkbox" name = "chemistry" checked = "checked" /> Chemistry
<input type = "submit" value = "Select Subject" />
</form>
</body>
</html>
OUTPUT:
Reading Checkbox Data
Maths Flag : : on
Physics Flag: : null
Chemistry Flag: : on
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:
Why use Session Tracking?
To recognize the user It is used
to recognize the particular user.
Disadvantage of Cookies
It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object.
Cookie class
javax.servlet.http.Cookie class provides the functionality
of using cookies. It provides a lot of useful methods for
cookies.
Useful Methods of CookieDescription
Method class
public void setMaxAge(int Sets the maximum age of the cookie in
expiry) seconds.
public String getName() Returns the name of the cookie. The
name cannot be changed after
creation.
public String getValue() Returns the value of the cookie.
public void setName(String changes the name of the cookie.
name)
public void setValue(String changes the value of the cookie.
value)
Cookies
How to create Cookie?
Cookie ck=new Cookie("user","sonoo jaiswal");//
creating cookie object
response.addCookie(ck);//adding cookie in the response
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing
name and value of cookie
}
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.
index.html
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
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);
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
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();
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
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.
Example
Advantage of URL Rewriting
It will always work whether cookie is disabled or not
(browser independent).
Extra form submission is not required on each pages.