Java Programming_Lab 5_1 Servlet
Java Programming_Lab 5_1 Servlet
Java Programming 1
Lab 5
Problem Statement
Develop a simple web application using the concept of Servlets, JSP, and database
connectivity
Java Programming 2
Objective of the Assignment
Java Programming 3
Web Terminology
Java Programming 4
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.
Java Programming 5
HTTP (Hyper Text Transfer Protocol)
Java Programming 6
HTTP Requests
• The request sent by the computer to a web server, contains all sorts of potentially
interesting information; it is known as HTTP requests.
• Two common methods for the request-response between a server and client are:
Java Programming 7
Servlet
Java Programming 9
Servlet Container
• It provides the runtime environment for JavaEE (j2ee) applications. The
client/user can request only a static WebPages from the server. If the user wants
to read the web pages as per input then the servlet container is used in java.
• The servlet container is the part of web server which can be run in a separate
process.
Java Programming 10
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.
Java Programming 11
Interfaces in javax.servlet.http package Classes in javax.servlet.http package
1. HttpServletRequest 1. HttpServlet
2. HttpServletResponse 2. Cookie
3. HttpSession 3. HttpServletRequestWrapper
4. HttpSessionListener 4. HttpServletResponseWrapper
5. HttpSessionAttributeListener 5. HttpSessionEvent
6. HttpSessionBindingListener 6. HttpSessionBindingEvent
7. HttpSessionActivationListener 7. HttpUtils (deprecated now)
8. HttpSessionContext (deprecated now)
Java Programming 12
Servlet Interface
Java Programming 13
Servlet Example using Servlet Interface
import java.io.*;
import javax.servlet.*;
PrintWriter out=res.getWriter();
public class First implements Se
out.print("<html><body>");
rvlet{
out.print("<b>hello simple servlet</b>");
ServletConfig config=null;
out.print("</body></html>");
public void init(ServletConfig conf
}
ig){
public void destroy()
this.config=config;
{System.out.println("servlet is destroyed");}
System.out.println("servlet is initial
public ServletConfig getServletConfig()
ized");
{return config;}
}
public String getServletInfo()
{return "copyright 2007-1010";}
public void service(ServletReques
t req,ServletResponse res)
}
throws IOException,ServletExcepti
on{
res.setContentType("text/html");
Java Programming 14
GenericServlet Class
• GenericServlet class
implements Servlet, ServletConfig and Serializable interfaces.
• 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.
1. public void init(ServletConfig config) is used to initialize the servlet.
• There are many methods in GenericServlet class.
2. 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.
3. public void destroy() is invoked only once throughout the life cycle and indicates that servlet is being
destroyed.
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
5. public String getServletInfo() returns information about servlet such as writer, copyright, version etc.
6. public void init() it is a convenient method for the servlet programmers, now there is no need to call
super.init(config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for the given parameter
name.
9. public Enumeration getInitParameterNames() returns all the parameters defined in the web.xml file.
10.public String getServletName() returns the name of the servlet object.
11.public void log(String msg) writes the given message in the servlet log file.
12.public void log(String msg,Throwable t) writes the explanatory message in the servlet log file and a
stack trace.
Java Programming 15
GenericServlet Class Example
import java.io.*;
import javax.servlet.*;
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
Java Programming 16
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.
• There are many methods in HttpServlet class.
1. 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.
2. 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.
3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET request. It is invoked
by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST request. It is invoked
by the web container.
5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD request. It is
invoked by the web container.
6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the OPTIONS request. It is
invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT request. It is invoked by
the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the TRACE request. It is
invoked by the web container.
9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the DELETE request. It is
invoked by the web container.
10. protected long getLastModified(HttpServletRequest req) returns the time when HttpServletRequest was last
modified since midnight January 1, 1970 GMT.
Java Programming 17
Servlet Life Cycle
• The web container maintains the life cycle of a servlet instance.
• There are three states of a servlet: new, ready and end.
• The servlet is in new state if servlet instance is created. After invoking
the init() method, Servlet comes in the ready state. In the ready state,
servlet performs all the tasks. When the web container invokes the
destroy() method, it shifts to the end state.
Java Programming 18
Steps to create Servlet
Java Programming 19
Step 1. Create a directory structure
• 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.
Java Programming 20
Step 2. Create a servlet
• The servlet can be created by three ways:
- By implementing Servlet interface
- By inheriting GenericServlet class
- By inheriting HttpServlet class Mostly used approach
//DemoServlet.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletRespo
nse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//
get the stream to write the data
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/classes directory.
Java Programming 22
Step 4. Create a 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.
</web-app>
Java Programming 23
Step 5. Start the server and deploy the project
Java Programming 24
Step 5. Start the server and deploy the project
• Go to My Computer properties -> Click on advanced system settings tab -> then environment
variables -> Click on the new tab of user variable -> Write JAVA_HOME in variable name and
paste the path of jdk folder in variable value -> click ok -> click ok -> click ok.
Java Programming 25
Step 5. Start the server and deploy the project
You can also create war file, and paste it inside the webapps directory. To do so, you need to use jar
tool to create the war file. Go inside the project directory (before the WEB-INF), then write:
Creating war file has an advantage that moving the project from one location to another takes less
time.
To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin
directory.
Java Programming 26
Step 6. Access the Servlet
Java Programming 27
Creating Servlet Example in Eclipse
• Create a Dynamic web project
• create a servlet
• add servlet-api.jar file
• Run the servlet
1) Create the dynamic web project:
For creating a dynamic web project click on File Menu -> New -> Project..-> Web ->
dynamic web project -> write your project name e.g. first -> Finish .
Java Programming 28
Creating Servlet Example in Eclipse
Java Programming 29
Creating Servlet Example in Eclipse
Java Programming 30
Creating Servlet Example in Eclipse
2) Create the servlet in eclipse IDE:
For creating a servlet, explore the project by clicking the + icon -> explore the Java
Resources -> right click on src -> New -> servlet -> write your servlet name e.g.
Hello -> uncheck all the checkboxes except doGet() -> next -> Finish.
Java Programming 31
Creating Servlet Example in Eclipse
Java Programming 32
Creating Servlet Example in Eclipse
Java Programming 33
Creating Servlet Example in Eclipse
Java Programming 34
Creating Servlet Example in Eclipse
3) add jar file in eclipse IDE:
For adding a jar file, right click on your project -> Build Path -> Configure Build Path ->
click on Libraries tab in Java Build Path -> click on Add External JARs button -> select
the servlet-api.jar file under tomcat/lib -> ok.
Java Programming 35
Creating Servlet Example in Eclipse
3) add jar file in eclipse IDE:
For adding a jar file, right click on your project -> Build Path -> Configure Build Path ->
click on Libraries tab in Java Build Path -> click on Add External JARs button -> select
the servlet-api.jar file under tomcat/lib -> ok.
Java Programming 36
Creating Servlet Example in Eclipse
Java Programming 37
Creating Servlet Example in Eclipse
Java Programming 38
Creating Servlet Example in Eclipse
4) Start the server and deploy the project:
For starting the server and deploying the project in one step, Right click on your
project -> Run As -> Run on Server -> choose tomcat server -> next -> addAll ->
finish.
Java Programming 39
Creating Servlet Example in Eclipse
Java Programming 40
Creating Servlet Example in Eclipse
Java Programming 41
How to configure tomcat server in Eclipse ?
For configuring the tomcat server in eclipse IDE, click on servers tab at the bottom
side of the IDE -> right click on blank area -> New -> Servers -> choose tomcat then
its version -> next -> click on Browse button -> select the apache tomcat root folder
previous to bin -> next -> addAll -> Finish.
Java Programming 42
How to configure tomcat server in Eclipse ?
Java Programming 43
How to configure tomcat server in Eclipse ?
Java Programming 44
How to configure tomcat server in Eclipse ?
Java Programming 45
How to configure tomcat server in Eclipse ?
Now tomcat7 server has been configured in eclipse IDE.
Java Programming 46
Thank You!!
Java Programming 47