0% found this document useful (0 votes)
92 views61 pages

Java Servlets

This document provides an overview of Java servlets, including their introduction, life cycle, and deployment. Key points include: - Servlets are Java programs that run on a web server and respond to HTTP requests. They extend the capabilities of servers to create dynamic web content. - The servlet life cycle includes initialization via the init() method, processing requests via service() and doGet/doPost methods, and destruction via the destroy() method. - To deploy a servlet, the class must be compiled and placed in the correct directory structure. A deployment descriptor (web.xml) maps URLs to servlet classes. The application is then deployed to a servlet container like Tomcat.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views61 pages

Java Servlets

This document provides an overview of Java servlets, including their introduction, life cycle, and deployment. Key points include: - Servlets are Java programs that run on a web server and respond to HTTP requests. They extend the capabilities of servers to create dynamic web content. - The servlet life cycle includes initialization via the init() method, processing requests via service() and doGet/doPost methods, and destruction via the destroy() method. - To deploy a servlet, the class must be compiled and placed in the correct directory structure. A deployment descriptor (web.xml) maps URLs to servlet classes. The application is then deployed to a servlet container like Tomcat.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

Java Servlets

Topics
• Introduction
• Overview Servlet Life Cycle
• A Simple Servlet
• Reading data from client
• Reading HTTP request headers
• Sending data to client
• Writing HTTP response headers
• Session
• cookies
Introduction

• A Java Servlet is a server side program that


responds to HTTP requests. It runs inside a
Servlet container.
Introduction
• Servlet is a technology used to create web
application
• Servlet is an API that provides many interfaces
and classes
• Servlet is a an interface that must be
implemented for creating any servlet
• Servlet is a class that extends the capabilities of
servers and responds to incoming request.
• Servlet is a web component that is deployed on
the server to create dynamic web pages
What is a web application??
• A web application is composed of web
components like servlet JSP etc. & other
components such as HTML
• Web components typically exe in Web
Server and respond to HTTP request.
CGI
• CGI technology enables the web server to call an
external program and pass HTTP request info to
external program to process the request
• For each request it starts a new process
• Disadvantages
– If no. of clients increase it takes more time for sending
response
– For each request it starts a process . A web server is
limited to start process
– It uses platform dependent language eg. Perl, c++
CGI
Advantages of servlet
• Advantages of servlet

– Better performance- because it created a thread


for each request not process.
– Portability – because it used java language
– Robust- servlets are managed by JVM so no need
to worry about memory leak, garbage collection
etc.
– Secure – because it uses java language
Basics of Web
• HTTP
• HTTP request types
• Diff between Get & Post method
• Content Type
• XML
• Deployment
HTTP

• Http is the protocol that allows web servers


and browsers to exchange data over the web.
• It is a request response protocol.
• Http uses reliable TCP connections by default
on TCP port 80.
• It is stateless means each request is
considered as the new request. In other
words, server doesn't recognize the user by
default.
HTTP request types
• Every request has a header that tells the status of
the client. There are many request methods. Get
and Post requests are mostly used.
• The http request methods are:
• GET
• POST

HTTP Request Description


GET Asks to get the resource at the requested URL.

Asks the server to accept the body info attached. It is like


POST
GET request with extra info sent with the request.
Diff bw Get & Post method
GET POST
1) In case of Get request, only limited In case of post request, large amount
amount of data can be sent because of data can be sent because data is
data is sent in header. sent in body.

2) Get request is not secured Post request is secured because data


because data is exposed in URL bar. is not exposed in URL bar.

3) Get request can be bookmarked Post request cannot be bookmarked


4) Get request is idempotent. It
means second request will be
Post request is non-idempotent
ignored until response of first request
is delivered.
5) Get request is more efficient and Post request is less efficient and used
used more than Post less than get.
As we know that data is sent in request header in case
of get request. It is the default request type.
As we know, in case of post request original data is sent
in message body.
Content Type
• Content Type is also known as MIME (Multipurpose internet Mail
Extension) Type. It is a HTTP header that provides the description
about what are you sending to the browser.
• There are many content types:
• text/html
• text/plain
• application/msword
• application/vnd.ms-excel
• application/jar
• application/pdf
• application/octet-stream
• application/x-zip
• images/jpeg
• video/quicktime etc.
Servlet Container
• Java servlet containers are
usually running inside a Java
web server.
• Tomcat
– 66% of the web sites on the
Internet use Apache
– Open source
– Free
Servlet Life Cycle
Servlet API
• Servlet API consists 2 important packages that
has all important classes and interfaces.
– javax.servlet
– javax.servlet.http
Classes and interfaces in javax.servlet
Class Interfaces

GenericServlet
Filter
ServletContextAttributeEvent
FilterChain
ServletContextEvent
FilterConfig
ServletInputStream
RequestDispatcher
ServletOutputStream
Servlet
ServletRequestAttributeEvent
ServletConfig
ServletRequestEvent
ServletContext
ServletRequestWrapper
ServletContextAttributeListener
ServletResponseWrapper
ServletContextListener
ServletRequest
ServletRequestAttributeListener
ServletRequestListener
ServletResponse
SingleThreadModel
Classes and interfaces in
javax.servlet.http
Class Interfaces

Cookie HttpServletRequest
HttpServlet HttpServletResponse
HttpServletRequestWrapper HttpSession
HttpServletResponseWrapper HttpSessionActivationListener
HttpSessionBindingEvent HttpSessionAttributeListener
HttpSessionEvent HttpSessionBindingListener
HttpUtils HttpSessionContext
HttpSessionListener
The init() method :

• The init method is designed to be called only


once.
• It is called when the servlet is first created,
and not called again for each user request.
• So, it is used for one-time initializations
• The init method definition looks like this:
public void init() throws ServletException
{ // Initialization code... }
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.
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{// Service code... }
The service() method :
• The service () method is called by the container
and service method invokes doGet, doPost, etc.
methods as appropriate.
• So you have nothing to do with service() method
but you override either doGet() or doPost()
depending on what type of request you receive
from the client.
• The doGet() and doPost() are most frequently
used methods with in each service request. Here
is the signature of these two methods.
The service() method :
• public void doGet(HttpServletRequest
request, HttpServletResponse response)
throws ServletException, IOException { //
Servlet code }
• 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 your servlet a chance to close
database connections, halt background threads,
and perform other such cleanup activities.
• After the destroy() method is called, the servlet
object is marked for garbage collection.
• The destroy method definition looks like this:
• public void destroy() { // Finalization code... }
A Simple Servlet skeleton
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends GenericServlet {


public void int() throws ServletException
{
// Initialization code...
}
public void service( ) throws ServletException, IoException
{
// do something in here
}
public void destroy()
{
}
}
1. Extending GenericSevlet class
2. Extending HttpSevlet class
Deploying servlet on Tomcat server

1. Create a directory structure


2. Create a servlet
3. Compile the servlet
4. Create a deployment descriptor
5. Start the server and deploy the
application
Create a directory structure
• The sun microsystem
defines a unique
standard to be followed
by all server vendors
• The directory structure
where to put different
types of files so that
web container may get
information and
respond to the client
Create a servlet

• 3 ways

1. By inheriting HttpServlet class


2. By inheriting GenericServlet class
3. By implementing Servlet interface
Compile the servlet
• To compile a servlet a jar is need to be loaded.
• Different server require different .jar file
• Apache tomcat servlet-api.jar
• Download servlet-api.jar
• paste it inside \Java\jdk\jre\lib\ext
• Compile DemoServlet.java
• Place the DemoServlet.class file in \WEB-
INF\classes dir
Create a deployment descriptor(DD)

• DD is an XML document that is used by web


container to get info about which servlet to
invoke
• DD is used for several purpose such as
mapping URL to servlet class.
web.xml file
<web-app>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FisrtServlet</servlet-name>
<url-pattern>welcome</url-pattern>
</servlet-mapping>
</web-app>
Start the server and deploy the
application
• Starting apache-tomcat 1st time JAVA_HOME
must be set in Environment variables
• C:\apache-tomcat-7.0.32\bin
• Startup.bat
• Copy your entire project folder to web-app
folder
• Accessing the servlet
– Open browser
http://localhost:8080/First/welcome
Web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

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

<servlet-mapping>
<servlet-name>FisrtServlet</servlet-name>
<url-pattern>logon.html</url-pattern>
</servlet-mapping>
</web-app>
Reading data from client
• ServletRequest Interface
– An object of ServletRequest is used to provide the
client request information to a servlet such as
• Parameter names & values
• Content type &Content length
• Header information
• Attributes etc
• Methods of ServletRequest interface
• Methods of ServletRequest interface
– String getParameter( )
Returns the value of a request parameter as
a String, or null if the parameter does not exist.
– String[] getParameterValues( )
Returns an array of String objects containing
all of the values the given request parameter . It is
mainly used to obtain values of Multi select list
box.
– String getContentType()
Returns the MIME type of the body of the
request, or null if the type is not known.
Example to display name of user
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";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<h1 align=\"center\">" + title + "</h1>\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>");
}
}
http Status codes
Code: Message: Description:
Only a part of the request has been received by the
100 server, but as long as it has not been rejected, the
Continue client should continue with the request

101 The server switches protocol.


Switching Protocols

200 OK The request is OK


201 The request is complete, and a new resource is created
Created

202 The request is accepted for processing, but the


Accepted processing is not complete.
400 Bad Request The server did not understand the request
401 Unauthorized The requested page needs a username and a password
402 Payment Required You can not use this code yet
403 Forbidden Access is forbidden to the requested page
404 Not Found The server can not find the requested page.
405 Method Not Allowed The method specified in the request is not allowed.

406 The server can only generate a response that is not accepted by the
Not Acceptable
client.
407 Proxy Authentication You must authenticate with a proxy server before this request can be
Required served.
408 Request Timeout The request took longer than the server was prepared to wait.

409 Conflict The request could not be completed because of a conflict.

500 The request was not completed. The server met an unexpected
Internal Server Error condition
501 The request was not completed. The server did not support the
Not Implemented functionality required.

502 The request was not completed. The server received an invalid
Bad Gateway response from the upstream server
Session tracking
• Session means particular
interval of time.
• Session tracking is a way to
maintain state of a user.
• Http is a stateless protocol,
each request to server, server
treats the request as a new
request.
• So we need to maintain the
state of the user to recognize
a particular user
• Techniques
– Cookies
– Http Sessions
1. Cookies
• A cookie is a small piece of information
that are sent in response from web
server to client
• Cookie are stored on client computer.
• They have lifespan and are destroyed by
the client browser at end of lifespan
• A cookie has name, value, attributes like
comment, path max age, version
number
• Advantage
– Simplest technique for maintain state
– Cookies are maintained at client side
• Disadvantage
– It will not work if cookie is disabled from
browser
– Only textual info can be set in a cookie
object
Cookies
First.html
• <form action="servlet1" method="post">
• Name:<input type="text" name="userName"/><br/>
• <input type="submit" value="go"/>
• </form>
FirstServelt.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
out.print("<form action='servlet2'>"); //creating submit button
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 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);}
}
}
<web-app>
Web.xml
<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>
Setting cookies with servlet involves :

• Creating a Cookie object:


Cookie ck = new Cookie(“Name",”value”);
• Setting the maximum age: You use setMaxAge to specify
how long (in seconds) the cookie should be valid. Following
would set up a cookie for 24 hours.
ck.setMaxAge(60*60*24);
• Sending the Cookie into the HTTP response headers:
response.addCookie(ck);
Reading a cookie

• Getting cookies from client request


Cookie[] ck = request.getCookies();
– Next the servlet can step thru array of cookie objects & retrieve
attribute of each cookie by callling getXXX( )
– String getName()
Returns the name of the cookie.
– int getMaxAge()
Returns the maximum age of the cookie, specified in seconds.
– String getValue()
Returns the value of the cookie.
– int getVersion()
Returns the version of the protocol this cookie complies with.
public class ReadCookies extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


{
Cookie cookie = null;
Cookie[] cookies = null;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading Cookies Example";
String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" );
if( cookies != null )
{
out.println("<h2> Found Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++)
{
cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
}else
{
out.println( "<h2>No cookies founds</h2>");
}
out.println("</body>");
out.println("</html>");
}
}
2. HTTPSession
• HttpSession object is used to store entire session
with a specific client.
• We can store, retrieve, remove attribute from
HttpSession object.
• On the client’s first request the webserver generates
a unique session ID and gives it back to the client
• The client sends back the session ID with each
request
HttpSession interface
• Creating a new session
HttpSession session = request.getSession( );
Sl.No
Method & Description
.
public long getCreationTime()
This method returns the time when this session was created, measured in
1
milliseconds since midnight January 1, 1970 GMT.

public String getId()


This method returns a string containing the unique identifier assigned to this
2
session.

public long getLastAccessedTime()


This method returns the last time the client sent a request associated with
3
this session, as the number of milliseconds since midnight January 1, 1970
GMT.
Web Application
• index.html
• link.html
• login.html
• Registration.html
• Connect.java
• LoginServlet.java
• LogoutServlet.java
• ProfileServlet.java
• NewRegistration.java
• web.xml
Example of Registration form in servlet
• CREATE TABLE "REGISTERUSER"
• ( "NAME" VARCHAR2(4000),
• "PASS" VARCHAR2(4000),
• "EMAIL" VARCHAR2(4000),
• "COUNTRY" VARCHAR2(4000)
• )
• /
Register.html
<html>
<body>
<form action="servlet/Register" method="post">

Name:<input type="text" name="userName"/><br/><br/>


Password:<input type="password" name="userPass"/><br/><br/>
Email Id:<input type="text" name="userEmail"/><br/><br/>
Country:
<select name="userCountry">
<option>India</option>
<option>USA</option>
<option>Srilanka</option>
<option>Japan</option>
<option>other</option>
</select>
<br/><br/>
<input type="submit" value="register"/>

</form>
</body>
</html>
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class Register 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");
String e=request.getParameter("userEmail");
String c=request.getParameter("userCountry");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

PreparedStatement ps=con.prepareStatement( "insert into registeruser 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();
}
• <web-app>

• <servlet>
• <servlet-name>Register</servlet-name>
• <servlet-class>Register</servlet-class>
• </servlet>

• <servlet-mapping>
• <servlet-name>Register</servlet-name>
• <url-pattern>/servlet/Register</url-pattern>
• </servlet-mapping>

• <welcome-file-list>
• <welcome-file>register.html</welcome-file>
• </welcome-file-list>

• </web-app>

You might also like