Professional Documents
Culture Documents
Servlet Notes
Servlet Notes
Introduction
In the early days of the Web, most business Web pages were simply forms of advertising
tools and content providers offering customers useful manuals, brochures and catalogues.
In other words, these business-web-pages had static content and were called "Static
WebPages".
Later, the dot-com revolution enabled businesses to provide online services for their
customers; and instead of just viewing inventory, customers could also purchase it. This new
phase of the evolution created many new requirements;
Web sites had to be reliable, available, secure, and, if it was at all possible, fast. At this time,
the content of the web pages could be generated dynamically, and were called "Dynamic
WebPages".
JSP is a server side technology which helps to create a webpage dynamically using java as
the programming language.
JSP is a specification from Sun Microsystems. It is an extension to Servlet API.
Servlet technology is used to create web application (resides at server side and generates
dynamic web page).
What is a Servlet?
1. Servlet is a technology i.e. used to create web application.
2. Servlet is an API that provides many interfaces and classes including
documentations.
3. Servlet is an interface that must be implemented for creating any servlet.
4. Servlet is a class that extends the capabilities of the servers and responds to the
incoming request. It can respond to any type of requests.
5. Servlet is a web component that is deployed on the server to create dynamic web
page.
What is CGI?
CGI is not the program itself. CGI is simply the interface between the Web page or browser
and the Web server that runs the program.
CGI technology enables the web server to call an external program and pass HTTP request
information to the external program to process the request. For each request, it starts a new
process.
Disadvantages of CGI
There are many problems in CGI technology:
1. If number of clients increases, it takes more time for sending response.
2. For each request, it starts a process and Web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.
Advantages of Servlet
There are many advantages of servlet over CGI. The web container creates threads for
handling the multiple requests to the servlet. Threads have a lot of benefits over the
Processes such as they share a common memory area, lightweight, cost of communication
between the threads are low. The basic benefits of servlet are as follows:
The advantages of servlets are discussed below.
1. Portability
2. Powerful
3. Efficiency
4. Safety
5. Integration
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 2
www.vertexitservices.com
Advanced Java
6. Extensibility
7. Inexpensive
8. Secure
9. Performance
Portability
Servlets are highly portable crosswise operating systems and server implementations
because the servlets are written in java and follow well known standardized APIs. Servlets
are writing once, run anywhere (WORA) program, because we can develop a servlet on
Windows machine running the tomcat server or any other server and later we can deploy
that servlet simply on any other operating system like Unix. Servlets are extremely portable
so we can run in any platform. So we can call servlets are platform independent one.
Servlets are written entirely in java.
Powerful
We can handle several things with the servlets which were difficult or sometimes impossible
to do with CGI. For example the CGI programs can’t talk directly to the web server but the
servlets can directly talk to the web server. Servlets can share data among each other, they
make the database connection pools easy to implement. By using the session tracking
mechanism servlets can maintain the session which helps them to maintain information
from request to request. Servlets can do many things which are difficult to implement in the
CGI programs.
Efficiency
The servlets invocation is highly efficient as compared to CGI programs. The servlet remains
in the server’s memory as a single object instance, when the servlet get loaded in the server.
The servlets are highly scalable because multiple concurrent requests are handled by
separate threads. That is we can handle N number of threads by using a single servlet class
Safety
As servlets are written in java, servlets inherit the strong type safety of java language. In java
automatic garbage collection mechanism and a lack of pointers protect the servlets from
memory management problems. In servlets we can easily handle the errors due to the
exception handling mechanism. If any exception occurs then it will throw an exception by
using the throw statement.
Integration
Servlets are tightly integrated with the server. Servlet can use the server to translate the file
paths, perform logging, check authorization, and MIME type mapping etc.
Extensibility
The servlet API is designed in such a way that it can be easily extensible. As it stands today,
the servlet API support Http Servlets, but in later date it can be extended for another type of
servlets. Java Servlets are developed in java which is robust, well-designed and object
oriented language which can be extended or polymorphed into new objects. So the java
servlets take all these advantages and can be extended from existing class to provide the
ideal solutions. So servlets are more extensible and reliable.
Inexpensive
There are number of free web servers available for personal use or for commercial purpose.
Web servers are relatively expensive. So by using the free available web servers you can add
servlet support to it.
Secure
Servlets are server side components, so it inherits the security provided by the web server.
Servlets are also benefited with Java Security Manager.
Performance
Servlets are faster than CGI programs because each scripts in CGI produces a new process
and these processes takes a lot of time for execution. But in case of servlets it creates only
new thread. Due to interpreted nature of java, programs written in java are slow. But the
java servlets runs very fast. These are due to the way servlets run on web server. For any
program initialization takes significant amount of time. But in case of servlets initialization
takes place first time it receives a request and remains in memory till times out or server
shut downs. After servlet is loaded, to handle a new request it simply creates a new thread
and runs service method of servlet. In comparison to traditional CGI scripts which creates a
new process to serve the request.
Servlet Disadvantage
1. Designing in servlet is difficult and slows down the application.
2. Writing complex business logic makes the application difficult to understand.
3. You need a Java Runtime Environment on the server to run servlets. CGI is a
completely language independent protocol, so you can write CGIs in whatever
languages you have available (including Java if you want to).
Types of Servlets
There are mainly two types of servlets
1. Generic Servlet - Generic servlet is protocol independent servlet. It implements the
Servlet and ServletConfig interface. It may be directly extended by the servlet.
Writing a servlet in in GenericServlet is very easy. It has only init() and destroy()
method of ServletConfig interface in its life cycle. It also implements the log method
of ServletContext interface. They extend javax.servlet.GenericServlet.
2. Http Servlet - HttpServlet is HTTP (Hyper Text Transfer Protocol ) specific servlet. It
provides an abstract class HttpServlet for the developers for extend to create
their own HTTP specific servlets. They extend javax.servlet.HttpServlet. The sub
class of HttpServlet must overwrite at least one method given below-
a. doGet()
b. doPost()
c. doTrace()
d. doDelete()
e. init()
f. destroy()
g. getServiceInfo()
Servlet Terminology
There are some key points that must be known by the servlet programmer like server,
container, get request, post request etc. Let's first discuss these points before starting the
servlet technology.
The basic terminology used in servlet are given below:
1. HTTP
2. HTTP Request Types
3. Difference between Get and Post method
4. Container
5. Server and Difference between web server and application server
6. Content Type
7. Introduction of XML
8. Deployment
HTTP (Hyper Text Transfer Protocol)
1. Http is the protocol that allows web servers and browsers to exchange data over the
web.
2. It is a request response protocol.
Container
It provides runtime environment for JavaEE (j2ee) applications.It performs many operations
that are given below:
1. Life Cycle Management
2. Multithreaded support
3. Object Pooling
4. Security etc.
5. Server
It is a running program or software that provides services.There are two types of servers:
1. Web Server
2. Application Server
Web Server
Web server contains only web or servlet container. It can be used for servlet, jsp, struts, jsf
etc. It can't be used for EJB.
Example of Web Servers are: Apache Tomcat and Resin.
Application Server
Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf,
ejb etc.
Example of Application Servers are:
1. JBoss Open-source server from JBoss community.
2. Glassfish provided by Sun Microsystem. Now acquired by Oracle.
3. Weblogic provided by Oracle. It more secured.
4. Websphere provided by IBM.
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:
1. text/html
2. text/plain
3. application/msword
4. application/vnd.ms-excel
5. application/jar
6. application/pdf
7. application/octet-stream
8. application/x-zip
9. images/jpeg
10. video/quicktime etc.
Servlet API
1. The javax.servlet and javax.servlet.http packages represent interfaces and classes for
servlet api.
2. 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.
3. The javax.servlet.http package contains interfaces and classes that are responsible
for http requests only.
13. ServletContextListener
14. ServletContextAttributeListener
15. Classes in javax.servlet package
There are many classes in javax.servlet package. They are as follows:
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}
GenericServlet class
1. GenericServlet class implements Servlet, ServletConfig andSerializable interfaces. It
provides the implementaion of all the methods of these interfaces except the
service method.
2. GenericServlet class can handle any type of request so it is protocol-independent.
3. You may create a generic servlet by inheriting the GenericServlet class and providing
the implementation of the service method.
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.
Methods of HttpServlet class
There are many methods in HttpServlet class. They are as follows:
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.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletLifeCycle extends HttpServlet
{
public ServletLifeCycle()
{
System.out.println("Am from default constructor");
}
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("I am from doGet method");
pw.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>second</servlet-name>
<servlet-class>java4s.ServletLifeCycle</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>second</servlet-name>
<url-pattern>/lifecycle1</url-pattern>
</servlet-mapping>
</web-app>
Create the above 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 classesfolder.
The web.xml (deployement descriptor) file is kept under WEB-INF folder.
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
But mostly a servlet is created by extending HttpServlet abstract class. As discussed
earlier HttpServlet gives the definition of service() method of the Servlet interface. The
servlet class that we will create should not override service() method. Our servlet class will
override only doGet() or doPost() method.
When a request comes in for the servlet, the Web Container calls the
servlet's service() method and depending on the type of request the service() method calls
either the doGet() or doPost() method.
NOTE: By default a request is Get request.
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");
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 16
www.vertexitservices.com
Advanced Java
Compiling a Servlet
To compile a Servlet a JAR file is required. Different servers require different JAR files. In
Apache Tomcat server servlet-api.jar file is required to compile a servlet class.
Steps to compile a Servlet
Set the Class Path.
NOTE: After compiling your Servlet class you will have to paste the class file into WEB-
INF/classes/directory.
Click on New button, and enter JAVA_HOME inside Variable name text field and path of JDK
inside Variable value text field. Click OK to save.
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client
requests. A cookie has a name, a single value, and optional attributes such as a comment,
path and domain qualifiers, a maximum age, and a version number.
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It
is removed only if user logout or signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won't work.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of
useful methods for cookies.
Constructor of Cookie class
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String constructs a cookie with a specified name and
value) value.
Useful Methods of Cookie class
There are given some commonly used methods of the Cookie class.
Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
public String getName() Returns the name of the cookie. The name cannot
be changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String changes the name of the cookie.
name)
public void setValue(String changes the value of the cookie.
value)
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.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
//creating submit button
out.print("<form action='servlet2'>");
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.xml
<web-app>
<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>
</body>
</html>
File: link.html
<a href="login.html">Login</a> |
<a href="LogoutServlet">Logout</a> |
<a href="ProfileServlet">Profile</a>
<hr>
File: login.html
<form action="LoginServlet" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>
File: LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 25
www.vertexitservices.com
Advanced Java
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
String name=request.getParameter("name");
String password=request.getParameter("password");
if(password.equals("admin123")){
out.print("You are successfully logged in!");
out.print("<br>Welcome, "+name);
Cookie ck=new Cookie("name",name);
response.addCookie(ck);
}else{
out.print("sorry, username or password error!");
request.getRequestDispatcher("login.html").include(request, response);
}
out.close();
}
File: LogoutServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
Cookie ck=new Cookie("name","");
ck.setMaxAge(0);
response.addCookie(ck);
out.print("you are successfully logged out!");
}
}
File: ProfileServlet.java
import java.io.IOException;
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 26
www.vertexitservices.com
Advanced Java
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ProfileServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
Cookie ck[]=request.getCookies();
if(ck!=null){
String name=ck[0].getValue();
if(!name.equals("")||name!=null){
out.print("<b>Welcome to Profile</b>");
out.print("<br>Welcome, "+name);
}
}else{
out.print("Please login first");
request.getRequestDispatcher("login.html").include(request, response);
}
out.close();
}
}
File: web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/
ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.javatpoint.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>ProfileServlet</display-name>
<servlet-name>ProfileServlet</servlet-name>
<servlet-class>com.javatpoint.ProfileServlet</servlet-class>
</servlet>
<servlet-mapping>
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 27
www.vertexitservices.com
Advanced Java
<servlet-name>ProfileServlet</servlet-name>
<url-pattern>/ProfileServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>LogoutServlet</display-name>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.javatpoint.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
</web-app>
If again you click on the profile link, you need to login first.
2) Hidden Form Field
In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of
an user.
In such case, we store the information in the hidden field and get it from another servlet.
This approach is better if we have to submit form in all the pages and we don't want to
depend on the browser.
Let's see the code to store value in hidden field.
<input type="hidden" name="uname" value="Vimal Jaiswal">
Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
}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 doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 29
www.vertexitservices.com
Advanced Java
<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>
3)URL Rewriting
In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next
resource. We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??
A name and a value is separated using an equal = sign, a parameter name/value pair is
separated from another parameter using the ampersand(&). When the user clicks the
hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we
can use getParameter() method to obtain a parameter value.
}catch(Exception e){System.out.println(e);}
}
}
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 31
www.vertexitservices.com
Advanced Java
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//getting value from the query string
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<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>
4) HttpSession interface
In such case, container creates a session id for each user.The container uses this id to
identify the particular user.An object of HttpSession can be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
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 doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
web.xml
<web-app>
<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>
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 34
www.vertexitservices.com
Advanced Java
</web-app>
mysql>
Accessing a Database:
Here is an example which shows how to access TEST database using Servlet.
// Loading required libraries
import java.io.*;
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 35
www.vertexitservices.com
Advanced Java
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
// Database credentials
static final String USER = "root";
static final String PASS = "password";
// Open a connection
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
//Display values
out.println("ID: " + id + "<br>");
out.println(", Age: " + age + "<br>");
out.println(", First: " + first + "<br>");
out.println(", Last: " + last + "<br>");
}
out.println("</body></html>");
// Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
} //end try
}
}
Now let us compile above servlet and create following entries in web.xml
....
<servlet>
<servlet-name>DatabaseAccess</servlet-name>
<servlet-class>DatabaseAccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DatabaseAccess</servlet-name>
<url-pattern>/DatabaseAccess</url-pattern>
</servlet-mapping>
....
Now call this servlet using URL http://localhost:8080/DatabaseAccess which would display
following response:
Database Result
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JDBCServlet extends HttpServlet {
public void doGet(HttpServletRequest inRequest,
HttpServletResponse outResponse) throws ServletException,
IOException {
PrintWriter out = null;
Connection connection = null;
Statement statement;
ResultSet rs;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager
.getConnection("jdbc:mysql://localhost/products");
statement = connection.createStatement();
outResponse.setContentType("test/html");
out = outResponse.getWriter();
rs = statement.executeQuery("SELECT ID, title, price FROM product");
out.println("<HTML><HEAD><TITLE>Products</TITLE></HEAD>");
out.println("<BODY>");
out.println("<UL>");
while (rs.next()) {
out.println("<LI>" + rs.getString("ID") + " "
+ rs.getString("title") + " " + rs.getString("price"));
Contact: enquiry@vertexitservices.com Call:9763 9763 33 | 38
www.vertexitservices.com
Advanced Java
}
out.println("</UL>");
out.println("</BODY></HTML>");
} catch (ClassNotFoundException e) {
out.println("Driver Error");
} catch (SQLException e) {
out.println("SQLException: " + e.getMessage());
}
}