Module-3
Module-3
Dr.Ramu Vankudoth
Assistant Professor
Module – 3
Introduction to Servlet
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
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
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-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
<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
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
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
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
Class.forName("oracle.jdbc.driver.OracleDriver");
2. Create the connection object
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",
"system","password");
3) Create the Statement object
By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.