0% found this document useful (0 votes)
10 views45 pages

Module-3

Introduction to Servlets

Uploaded by

Ramu Vankudoth
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
10 views45 pages

Module-3

Introduction to Servlets

Uploaded by

Ramu Vankudoth
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 45

MALLA REDDY ENGINEERING COLLEGE

(An UGC Autonomous Institution) Main Campus

Maisammaguda, Dhulapally(Post via Kompally), Secunderabad –


500100

Department of Computer Science & Engineering –Data Science

Subject: Web Technologies

Dr.Ramu Vankudoth
Assistant Professor
Module – 3

Introduction to Servlet

• Servlet Technology is used to create web applications.


• Servlet technology 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.
• As Servlet Technology uses Java, web applications made using Servlet
are Secured, Scalable and Robust.
CGI (Common Gateway Interface)

The Common Gateway Interface (CGI) standard is a data-passing specification used when a Web server must
send or receive data from an application such as a database. A CGI script passes the request from the Web
server to a database, gets the output and returns it to the Web client.
CGI(Common Gateway Interface) programming was used to create web applications.
Here's how a CGI program works :
• User clicks a link that has URL to a dynamic page instead of a static page.
• The URL decides which CGI program to execute.
• Web Servers run the CGI program in separate OS shell. The shell includes OS environment
and the process to execute code of the CGI program.
• The CGI response is sent back to the Web Server, which wraps the response in an HTTP
response and send it back to the web browser.
Life cycle of a Servlet

• The entire life cycle of a Servlet is managed by the Servlet


container which uses the javax.servlet.Servlet interface to understand
the Servlet object and manage it.
• So, before creating a Servlet object, let’s first understand the life cycle of
the Servlet object which is actually understanding how the Servlet
container manages the Servlet object.
• The Servlet life cycle mainly four stages,
• Loading a Servlet.
• Instance Creation a Servlet.
• Initializing the Servlet.
• Request handling.
1. Loading Servlet Class : A Servlet class is loaded when first request for the
servlet is received by the Web Container.
2. Servlet instance creation :After the Servlet class is loaded, Web Container
creates the instance of it. Servlet instance is created only once in the life
cycle.
3. Call to the init() method : init() method is called by the Web Container on
servlet instance to initialize the servlet.
Signature of init() method :

public void init(ServletConfig config) throws ServletException


4. Call to the service() method : The containers call the service() method
each time the request for servlet is received. The service() method will then
call the doGet() or doPost() methods based on each type of the HTTP request,
as explained in previous method.
Signature of service() method :

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException

5. Call to destroy() method: The Web Container call the destroy() method
before removing servlet instance, giving it a chance for cleanup activity.
Create Servlet Application using tomcat server or deploying a servlet

To create a Servlet application you need to follow the five steps.


1. Create directory structure for your application.
2. Create a Servlet.
3. Compile the Servlet.
4. Create Deployement Descriptor for your application.
5. Start the server and deploy the application.
1. Creating the 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.
• Create the below directory structure inside Apache-Tomcat\
webapps directory.
• All HTML, static files(images, css etc) are kept directly under Web
application folder.
• While all the Servlet classes are kept inside classes folder.
• The web.xml (deployement descriptor) file is kept under WEB-
INF folder.
2. Creating a Servlet
There are three different ways to create a servlet.
1. By implementing Servlet interface
2. By extending GenericServlet class
3. By extending HttpServlet class
Write below code in a notepad file and save it
as MyServlet.java anywhere on your Computer. Compile it(explained
in next step) from there and paste the class file
into WEB-INF/classes/ directory that you have to create
inside Tomcat/webapps directory.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResposne response)
throws ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello Readers</h1>");
out.println("</body></html>");
}
}
3. Compiling a Servlet
1. To compile a Servlet a JAR file is required. Different servers require
different JAR files.
2. In Apache Tomcat server servlet-api.jar file is required to compile a
servlet class.
Steps to compile a Servlet:
•Set the Class Path.
• Download servlet-api.jar file.
• Paste the servlet-api.jar file inside Java\jdk\jre\lib\ext directory.
Compile the Servlet class.

After compiling your Servlet class you will have to paste the class file
into WEB-INF/classes/ directory.
4. Create Deployment Descriptor
root tag of web.xml file. All other tag come inside it

<web-app>
This tag maps internal name to full qualified class name

<servlet> Give a internal name to your servlet


<servlet-name>Ramul</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet> Servlet class that you have created

This tag maps internal name to public URL name

<servlet-mapping>
<servlet-name>Ramul</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping> URL name. This what the user will see to get to the servlet.

</web-app>
5. Start the Server
1. Double click on the startup.bat file to start your Apache Tomcat Server.
2. Or, execute the following command on your windows machine using RUN prompt.

http://localhost:8080/Ramu/
Servlet API

Servlet API consists of two important packages that encapsulates all the important classes and
interface, namely :
• javax.servlet
• javax.servlet.http
Some Important Classes and Interfaces of javax.servlet

INTERFACES CLASSES
Servlet ServletInputStream
ServletContext ServletOutputStream
ServletConfig ServletRequestWrapper
ServletRequest ServletResponseWrapper
ServletResponse ServletRequestEvent
ServletContextListener ServletContextEvent
CLASSES
• ServletInputStream - It provides an input stream for reading binary data from a client
request, including an efficient readLine method for reading data one line at a time.
• ServletOutputStream - It provides an output stream for sending binary data to the client.
• ServletRequestWrapper - It provides a convenient implementation of the ServletRequest
interface that can be subclassed by developers wishing to adapt the request to a Servlet.
• Servlet ResponseWrapper - It provides a convenient implementation of the ServletResponse
interface that can be subclassed by developers wishing to adapt the Response to a Servlet.
• ServletRequestEvent - This event indicates lifecycle events for a ServletRequest.
• ServletContextEvent - It provides an event class for notifications about changes to the servlet
context of a web application.
Interface:
• Servlet: It defines methods that all servlets must implement.
• ServletConfig: It is a servlet configuration object used by a servlet container to pass
information to a servlet during initialization.
• ServletContext: It gives a set of methods that a servlet uses to communicate with its
servlet container.
• ServletRequest: It defines an object to provide client request information to a servlet.
• ServletResponse: It defines an object to a servlet in sending a response to the client.
• ServeltRequestListener: It is an interface for receiving notifications events about
requests coming into and going out of the scope of a web application.
Some Important Classes and Interface of javax.servlet.http

It contains a number of classes and interfaces. It describes and defines the contracts
between a servlet class running under the HTTP protocol and the runtime
environment.

CLASSES INTERFACES
HttpServlet HttpServletRequest
HttpServletResponse HttpSessionAttributeListener
HttpSession HttpSessionListener
Cookie HttpSessionEvent
Reading Servlet parameters

Servlets parse the form(client) data automatically using the following methods depending on
the situation −
1. getParameter() − You call request.getParameter() method to get the value of a form
parameter. Single value for a parameter
2. getParameterValues() − Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.
3. getParameterNames() − Call this method if you want a complete list of all parameters in
the current request.
4. Client pass some information from browser to web server uses GET Method or POST
Method. request.getParameter("name")
login.html

<html>
<head>
<title>Login page</title>
</head>
<body>
<h1> Login Form </h1>
<form method="post" action="login">
Username: <input type="text" name="username">
Password: <input type="password" name="pass">
</form>
</body>
</html>
LoginDemo.java

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class LoginDemo extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
String name=request.getParameter("username"); //will return value
out.println("Welcome "+name);
out.close();
}
}
web.xml

<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>LoginDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
Reading Initialization Paraeters in Servlet

Both ServletContext and ServletConfig are basically the configuration objects which are
used by the servlet container to initialize the various parameter of a web application.

ServletConfig
1. An object of ServletConfig is created by the web container for each servlet.
2. This object can be used to get configuration information from web.xml file.
3. If the configuration information is modified from the web.xml file, we don't need
to change the servlet.
4. So it is easier to manage the web application if any specific content is modified
from time to time.
Methods of ServletConfig interface
1. public String getInitParameter(String name): Returns the parameter value for the
specified parameter name.
2. public Enumeration getInitParameterNames(): Returns an enumeration of all the
initialization parameter names.
3. public String getServletName(): Returns the name of the servlet
ServletContext
ServletContext object can be used to get configuration information from web.xml file.
There is only one ServletContext object per web application.
If any information is shared to many servlet, it is better to provide it from the web.xml file using
the element.
Methods commonly used in ServletContext interface
1. public String getInitParameter(String name):Returns the parameter value for the specified
parameter name.
2. public Enumeration getInitParameterNames():Returns the names of the context's initialization
parameters.
3. public void setAttribute(String name,Object object):sets the given object in the application
scope.
4. public Object getAttribute(String name):Returns the attribute for the specified name.
Handling HTTP Requests and Responses
Handling HTTP Requests and Responses

Handling HTTP Requests and Responses:


• The HttpServlet class provides specialized methods that handle the various types of
HTTP requests. A servlet developer typically overrides one of these methods.
• These methods are doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ),
and doTrace( ).
• A complete description of the different types of HTTP requests is beyond the scope.
• However, the GET and POST requests are commonly used when handling form input.
Handling HTTP GET Requests:
• Here we will develop a servlet that handles an HTTP GET request. The servlet is
invoked when a form on a Web page is submitted.
The example contains two files.
• A Web page is defined in ColorGet.htm and a servlet is defined in ColorGetServlet.java.
• The HTML source code for ColorGet.htm is shown in the following listing.
• It defines a form that contains a select element and a submit button.
• The action parameter of the form tag specifies a URL.
• The URL identifies a servlet to process the HTTP GET request
Compile the servlet and perform these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display the Web page in a browser.
3. Select a color.
4. Submit the Web page.
• After completing these steps, the browser will display the response that is dynamically
generated by the servlet.
• One other point: Parameters for an HTTP GET request are included as part of the URL
that is sent to the Web server.
• Assume that the user selects the red option and submits the form. The URL sent from
the browser to the server is
http://localhost:8080/examples/servlet/ColorGetServlet?color=Red
Handling HTTP POST Requests:
Here we will develop a servlet that handles an HTTP POST request.
• The servlet is invoked when a form on a Web page is submitted.
The example contains two files.
• A Web page is defined in ColorPost.htm and a servlet is defined in
ColorPostServlet.java.
• The HTML source code for ColorPost.htm is shown in the following listing.
• It is identical to ColorGet.htm except that the method parameter for the form tag
explicitly specifies that the POST method should be used, and the action parameter
for the form tag specifies a different servlet.
Using Cookies and Sessions

Cookies in Servlets
Cookies are small pieces of data stored on the client-side. When a client makes a request, the server can
send cookies, which the browser stores. These cookies are sent back to the server on subsequent requests,
enabling session tracking. Retrieving a Cookie
Cookie[] cookies = request.getCookies();
Creating a Cookie if (cookies != null) {
for (Cookie cookie : cookies) {
Cookie cookie = new Cookie("username", “Ramu"); if (cookie.getName().equals("username")) {
cookie.setMaxAge(60*60*24); // 1 day String value = cookie.getValue();
response.addCookie(cookie); // Use the cookie value
}
}
}
Deleting a Cookie: To delete a cookie, set its maximum age to zero

Cookie cookie = new Cookie("username", "");


cookie.setMaxAge(0); response.addCookie(cookie);

Sessions in Servlets
Sessions are server-side objects used to maintain a user's state across multiple HTTP requests. Each user
has a unique session ID, which can be tracked by cookies or URL rewriting.
Creating/Retrieving a Session Retrieving Session Data

HttpSession session = request.getSession(); String username = (String) session.getAttribute("username");


session.setAttribute("username", "Ramu");
Connecting to a database using JDBC

There are 5 steps to connect any java application with the database using JDBC. These
steps are as follows:
1. Register the Driver class
2. Create connection
3. Create statement
4. Execute queries
5. Close connection
1. Register the driver class

The forName() method of Class class is used to register the driver


class. This method is used to dynamically load the driver class.

Syntax of forName() method


public static void forName(String className)throws ClassNotFoundException

Example to register the OracleDriver class


Here, Java program is loading oracle driver to esteblish database connection.

Class.forName("oracle.jdbc.driver.OracleDriver");
2. Create the connection object

The getConnection() method of DriverManager class is used to


establish connection with the database.
Syntax of getConnection() method

1) public static Connection getConnection(String url)throws SQLException


2) public static Connection getConnection(String url,String name,String password)
throws SQLException
Example to establish connection with the Oracle database

Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"system","password");
3) Create the Statement object

• The createStatement() method of Connection interface is used to create statement.


• The object of statement is responsible to execute queries with the database.

Syntax of createStatement() method

public Statement createStatement()throws SQLException

Example to create the statement object


Statement stmt=con.createStatement();
4) Execute the query

The executeQuery() method of Statement interface is used to execute queries to the


database. This method returns the object of ResultSet that can be used to get all the
records of a table.

Syntax of executeQuery() method


public ResultSet executeQuery(String sql)throws SQLException
Example to execute query

ResultSet rs=stmt.executeQuery("select * from emp");


while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.

Syntax of close() method


public void close()throws SQLException

Example to close connection


con.close();

You might also like