0% found this document useful (0 votes)
3 views

Java Programming_Lab 5_1 Servlet

The document outlines an assignment for a Java Programming course focused on developing a web application using Servlets, JSP, and MySQL database connectivity. It covers key concepts such as server-side scripting, HTTP protocols, and the lifecycle of Servlets, along with practical steps for creating and deploying a Servlet application. Additionally, it provides examples of Servlet classes and methods, as well as instructions for setting up the Apache Tomcat server for deployment.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Programming_Lab 5_1 Servlet

The document outlines an assignment for a Java Programming course focused on developing a web application using Servlets, JSP, and MySQL database connectivity. It covers key concepts such as server-side scripting, HTTP protocols, and the lifecycle of Servlets, along with practical steps for creating and deploying a Servlet application. Additionally, it provides examples of Servlet classes and methods, as well as instructions for setting up the Apache Tomcat server for deployment.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

Course: Java Programming(CET2031B)

SCHOOL OF COMPUTER ENGINEERING AND TECHNOLOGY

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

• To understand server-side scripting


• To understand the concept of Servlet and JSP
• To learn the working of Servlet and JSP
• To learn the database connectivity using MySQL
• To develop web application using Servlet, JSP and database
connectivity

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)

• The Hypertext Transfer Protocol (HTTP) is application-level protocol for


collaborative, distributed, hypermedia information systems. It is the data
communication protocol used to establish communication between client and
server.
• HTTP is TCP/IP based communication protocol, which is used to deliver the data
like image files, query results, HTML files, etc. on the World Wide Web (WWW)
with the default port is TCP 80. It provides the standardized way for computers to
communicate with each other.

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

• Servlet is a technology which is used


to create a web application.
• Servlet is an API that provides many
interfaces and classes including
documentation.
• Servlet is a class that extends the
capabilities of the servers and
responds to the incoming requests. It
can respond to any requests.
• Servlet is a web component that is
deployed on the server to create a
dynamic web page.
Java Programming 8
Advantages of Servlet
• The web container creates threads for handling the multiple requests to the Servlet. The
advantages of Servlet are as follows:
• 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.

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.

Interfaces in javax.servlet package Classes in javax.servlet package


1. Servlet 1. GenericServlet
2. ServletRequest 2. ServletInputStream
3. ServletResponse 3. ServletOutputStream
4. RequestDispatcher 4. ServletRequestWrapper
5. ServletConfig 5. ServletResponseWrapper
6. ServletContext 6. ServletRequestEvent
7. SingleThreadModel 7. ServletContextEvent
8. Filter 8. ServletRequestAttributeEvent
9. FilterConfig 9. ServletContextAttributeEvent
10.FilterChain 10.ServletException
11.ServletRequestListener 11.UnavailableException
12.ServletRequestAttributeListener
13.ServletContextListener
14.ServletContextAttributeListener

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

• Servlet interface provides common behavior to all the servlets.


• Servlet interface defines methods that all servlets must implement.
• Servlet interface needs to be implemented for creating any servlet (either directly or indirectly).
• There are 5 methods in 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.*;

public class First extends GenericServlet{


public void service(ServletRequest req,ServletResponse
res)
throws IOException,ServletException{

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.

• Load Servlet Class: The classloader is responsible to load the


servlet class. The servlet class is loaded when the first request for the
servlet is received by the web container.
• Create Servlet Instance: The web container creates the instance
of a servlet after loading the servlet class. The servlet instance is
created only once in the servlet life cycle.
• Call init() method: The web container calls the init method only
once after creating the servlet instance. The init method is used to
initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface.
• Call service() method: The web container calls the service
method each time when request for the servlet is received. If servlet is
not initialized, it follows the first three steps as described above then
calls the service method. If servlet is initialized, it calls the service
method. The servlet is initialized only once.
• Call destroy() method: The web container calls the destroy
method before removing the servlet instance from the service. It gives
the servlet an opportunity to clean up any resource for example
memory, thread etc.

Java Programming 18
Steps to create Servlet

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 project
6.Access the 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.

• The Sun Microsystem defines a


unique standard to be followed by
all the server vendors.

• The servlet class file must be in the


classes folder.

• The web.xml file must be under the


WEB-INF folder.

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

//writing html in the stream


pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");

pw.close();//closing the stream


Java Programming 21
}}
Step 3. Compile the servlet
• For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar
files:

Two ways to load the jar file:

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> <web-app> represents the whole application.

<servlet> <servlet> is sub element of <web-app> and represents the servlet.

<servlet-name>MITWPU</servlet- <servlet-name> is sub element of <servlet> represents the name


name> of the servlet.

<servlet-class>DemoServlet</servlet- <servlet-class> is sub element of <servlet> represents the class of


the servlet.
class>
</servlet> <servlet-mapping> is sub element of <web-app>. It is used to
map the servlet.

<servlet-mapping> <url-pattern> is sub element of <servlet-mapping>. This pattern is


used at client side to invoke the servlet.
<servlet-name>MITWPU</servlet-
name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

</web-app>

Java Programming 23
Step 5. Start the server and deploy the project

• We will use Apache Tomcat Server to deploy the project

• To install Apache Tomcat using Windows Service Installer, proceed as follows:

1. Navigate to Apache Tomcat site at http://tomcat.apache.org/index.html and n the left-hand


Download menu, click the latest available Tomcat version.
2. Locate the Binary Distributions area and in the Core list click the 32-bit/64-bit Windows Service
Installer link.
3. Save the apache-tomcat exe file in a temporary folder.
4. Run the exe file and follow the instructions of the installation wizard.
5. Click Next to move to the next step or return to the previous step by clicking the Back button.
6. In the License Agreement window, click I Agree.
7. In the Choose Components dialog, leave the default Normal type of installation.
8. Experienced Tomcat users can also select another installation type from the drop-down list.
9. In the Configuration dialog, leave the settings at their default values.
10. In the next window the Wizard displays the folder where Tomcat will be installed – the
Destination Folder.
11. This folder is referred as <TOMCAT_HOME> further in this document.
12. Click Install to start the installation.
13. Click Finish to complete.

Java Programming 24
Step 5. Start the server and deploy the project

• Configure Tomcat Server


1. set JAVA_HOME or JRE_HOME in environment variable (It is required to start server).
2. Change the port number of tomcat (optional). It is required if another server is running
on same port (8080).

1. How to set JAVA_HOME in environment variable?

• 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.

• There must not be semicolon (;) at the end of the path.


• After setting the JAVA_HOME double click on the startup.bat file in apache tomcat/bin.

2. How to change port number of apache tomcat


• Changing the port number is required if there is another server running on the same system with
same port number.
• Open server.xml file in notepad. It is located inside the apache-tomcat/conf directory . Change
the Connector port = 8080 and replace 8080 by any four digit number instead of 8080. Let us
replace it by 9999 and save this file.

Java Programming 25
Step 5. Start the server and deploy the project

• Deploy the servlet project


There are several ways to deploy the project.
- By copying the project folder into the webapps directory  Use this now..
- By copying the war folder into the webapps directory
- By selecting the folder path from the server
- By selecting the war file from the server

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:

projectfolder> jar cvf myproject.war *

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

• Open browser and write http://hostname:portno/contextroot/urlpatternofservlet.


For example: http://localhost:9999/demo/welcome

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

You might also like