Sie sind auf Seite 1von 80

Writing Hello World

As we know that the our servlet extends the HttpServlet and overrides the doGet() method
which it inherits from the HttpServlet class. The server invokes doGet() method whenever web
server recieves the GET request from the servlet. The doGet() method takes two arguments
first is HttpServletRequest object and the second one is HttpServletResponse object and this
method throws the ServletException.

Whenever the user sends the request to the server then server generates two obects, first is
HttpServletRequest object and the second one is HttpServletResponse object.
HttpServletRequest object represents the client's request and the HttpServletResponse
represents the servlet's response.

Inside the doGet(() method our servlet has first used the setContentType() method of the
response object which sets the content type of the response to text/html. It is the standard
MIME content type for the Html pages. After that it has used the method getWriter() of the
response object to retrieve a PrintWriter object. To display the output on the browser we use
the println() method of the PrintWriter class.

The code the program is given below:

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

public class HelloWorld extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head><title>Hello World</title></title>");
pw.println("<body>");
pw.println("<h1>Hello World</h1>");
pw.println("</body></html>");
}
}
web.xml file for this program:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:


Displaying Date in Servlet

In this example we are going to show how we can display a current date and time on our
browser. It is very easy to display it on our browser by using the Date class of the java.util
package.

The code the program is given below:

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

public class DisplayingDate extends HttpServlet{

public void doGet(HttpServletRequest request, HttpServletRes


ponse
response) throws ServletException, IOException{
PrintWriter pw = response.getWriter();
Date today = new Date();
pw.println("<html>"+"<body><h1>Today Date is</h1>");
pw.println("<b>"+ today+"</b></body>"+ "</html>");
}
}
XML File for this program
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//E
N"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>DateDisplay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/DateDisplay</url-pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:


Simple Counter In Servlet

In this example we are going to know how we can make a program on counter which will keep
track how many times the servlet has been accessed.

To make this program firstly we have to make one class SimpleCounterInServlet. The name
of the class should follow the naming convention. Remember to keep the name of the class in
such a way that it becomes easy to understand what the program is going to do just by seeing
the class name. After making a class define one variable counter which will keep record for
how many times the servlet has been accessed. Now use method either doGet() or doPost()
to write a logic of the program. Our program logic is simple. We have to just increment the
value of the counter by 1. To display the output use the method getWriter() method of the
response object which will in turn return the object of the PrintWriter class. Now display the
value of the counter.

The code of the program is given below:

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

public class SimpleCounter extends HttpServlet{


int counter = 0;
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
counter++;
pw.println("At present the value of the counter is " + counter);
}
}

The output of the program is given below:


A Holistic counter in Servlet

In this program we are going to make a such a servlet which will count the number it has been
accessed and the number of threads created by the server.

In this example firstly we are going to create one class named as HolisticCounterInServlet. Now
declare a variable counter of int with initial value 0, the value of this counter will be different
for each servlet and create a Hashtable object. This object will be shared by all the threads in
the container. Inside the doGet() method use the method getWriter() method of the response
object which will return the PrintWriter object.

The code of the program is given below:

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

public class HolisticCounter extends HttpServlet{


int counter = 0; //separate For Each Servlet
static Hashtable hashTable = new Hashtable(); //Shared by all the th
reads

public void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
counter++;
pw.println("This servlet has been accessed" + counter + "times<br>
");
hashTable.put(this,this);
pw.println("There are currently" + hashTable.size() + "threads<br>"
);
}
}

The output of the program is given below:


Counter in Init() Method

In this program we are going to make a such a servlet which will count and displays the
number of times it has been accessed and by reading the init parameter to know from where
the counting will begin.

In this program we are going to make use of the init method of the Servlet interface which
takes one argument of ServletConfig. Firstly declare a variable counter which will have the
initial value of the counter. The init() method accepts an object which implements
ServletConfig interface. It uses the method getInitParameter() method of the ServletConfig
interface to the value of the init parameter initial which we have defined in the deployment
descriptor file. You need to parse the String value which you will get from the
getInitParameter() method to a Integer.

The code of the program is given below:

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

public class CounterInInit extends HttpServlet {


int counter;
public void init(ServletConfig config) throws ServletException{
super.init(config);
String initValue = config.getInitParameter("initial");
try{
counter = Integer.parseInt(initValue);
}
catch(NumberFormatException e){
counter = 0;
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)

throws ServletException, IOException {response.setContentType("text/ht


ml");
PrintWriter pw = response.getWriter();
counter++;
pw.println("Since loading this servlet has been accessed" + counter + "ti
mes");
}
}
web.xml file for this program:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>CounterInInit</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/CounterInInit</url-pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:

Snooping the server

In this program we are going to tell you how can a use servlet to display information about its
server.

Firstly we will create a class in which there will be doGet() method which takes two objects as
arguments, first is request object and the second one is of response.

To display the name of the server you are using use the method getServerName() of the
ServletRequest interface. To display the server port number use the method
getServerPort(). You can also use other methods of the ServletRequest interface like
getProtocol() to display the protocol you are using and many more methods depending on
your needs.

The code of the program is given below:

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

public class SnoopingServerServlet extends HttpServlet{


protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
PrintWriter pw = response.getWriter();
pw.println("The server name is " + request.getServerName() + "<br>");
pw.println("The server port number is " + request.getServerPort()+ "<br
>");
pw.println("The protocol is " + request.getProtocol()+ "<br>");
pw.println("The scheme used is " + request.getScheme());
}
}

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>SnoopingServerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/SnoopingServerServlet</url-pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:

Snooping Headers

In this program we are going to going to make a servlet which will retrieve all the Http request
header.

To make a program over this firstly we need to make one class named
GettingSnoopingHeader. In HttpRequest there are too many headers. To retrieve all the
headers firstly we need to call the getWriter() which returns PrintWriter object and helps us
to display all the headers. To get a header names call the method getHeaderNames() of the
request object which will return the Enumeration of the headers. Now to retrieve all the
headers from the Enumeration use the method hasMoreElements(). This method checks
whether there are more headers or not. To display the output on your browser use the
PrintWriter object.

The code of the program is given below:

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

public class HeaderSnoopServlet extends HttpServlet{


protected void doGet(HttpServletRequest request, HttpServletResponse resp
onse)
throws ServletException, IOException {
PrintWriter pw = response.getWriter();
pw.println("Request Headers are");
Enumeration enumeration = request.getHeaderNames();
while(enumeration.hasMoreElements()){
String headerName = (String)enumeration.nextElement();
Enumeration headerValues = request.getHeaders(headerName);
if (headerValues != null){
while (headerValues.hasMoreElements()){
String values = (String) headerValues.nextElement();
pw.println(headerName + ": " + values);
}
}
}
}
}
web.xml file for this program:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HeaderSnoopServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HeaderSnoopServlet</url-pattern>
</servlet-mapping>
</web-app>
The output of the program is given below:

Dice Roller

We are going to make one program on the dice roller in which the number in the dice will be
selected randomly.

To make a program over this firstly we need to make a class DiceRoller in which we will have
a doGet() method in which we will have our application logic. To make the dice working
randomly use the random() method of the class java.lang.Math. To print the number on the
browser call the method getWriter() of the response object which will return the PrintWriter
object. Now by the object of the PrintWriter class print the values of the dice on the browser.

The code of the program is given below:

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

public class DiceRollerServlet extends HttpServlet{


protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException{
PrintWriter pw = response.getWriter();
String dice1 = Integer.toString((int)(Math.random()*6)+1);
String dice2 = Integer.toString((int)(Math.random()*6)+1);
pw.println("<html><body>");
pw.println("dice roller<br>");
pw.println("dice1 value is " + dice1 + " and <br>dice2 value is " +dice2
);
}
}

XML File for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>DiceRollerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/DiceRollerServlet</url-pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:

Getting Init Parameter Names

In this example we are going to retreive the init paramater values which we have given in the
web.xml file.

Whenever the container makes a servlet it always reads it deployment descriptor file i.e.
web.xml. Container creates name/value pairs for the ServletConfig object. Once the
parameters are in ServletConfig they will never be read again by the Container.

The main job of the ServletConfig object is to give the init parameters.

To retrieve the init parameters in the program firstly we have made one class named
GettingInitParameterNames. The container calls the servlet's service() method then
depending on the type of request, the service method calls either the doGet() or the doPost().
By default it will be doGet() method. Now inside the doGet() method use getWriter() method
of the response object which will return a object of the PrintWriter class which helps us to
print the content on the browser.

To retrieve all the values of the init parameter use method getInitParameterNames() which
will return the Enumeration of the init parameters.

The code of the program is given below:

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

public class InitServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter pw = response.getWriter();
pw.print("Init Parameters are : ");
Enumeration enumeration = getServletConfig().getInitParameterNames();
while(enumeration.hasMoreElements()){
pw.print(enumeration.nextElement() + " ");
}
pw.println("\nThe email address is " + getServletConfig().getInitParameter("Adm
inEmail"));
pw.println("The address is " + getServletConfig().getInitParameter("Address"));
pw.println("The phone no is " + getServletConfig().getInitParameter("PhoneNo")
);
}
}
web.xml file of this program:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<init-param>
<param-name>AdminEmail</param-name>
<param-value>zulfiqar_mca@yahoo.co.in</param-value>
</init-param>
<init-param>
<param-name>Address</param-name>
<param-value>Okhla</param-value>
</init-param>
<init-param>
<param-name>PhoneNo</param-name>
<param-value>9911217074</param-value>
</init-param>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>InitServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/InitServlet</url-pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:

Passing Parameter Using Html Form

This is a very simple example in which we are going to display the name on the browser which
we have entered from the Html page.

To get the desired result firstly we have to make one html form which will have only one field
named as name in which we will enter the name. And we will also have one submit button, on
pressing the submit button the request will go to the server and the result will be displayed to
us.
In the servlet which will work as a controller here picks the value from the html page by using
the method getParameter(). The output will be displayed to you by the object of the
PrintWriter class.

The code of the program is given below:

<html>

<head>
<title>New Page 1</title>
</head>

<body>

<h2>Login</h2>
<p>Please enter your username and password</p>
<form method="GET" action="/htmlform/LoginServlet">
<p> Username <input type="text" name="username" size="
20"></p>
<p> Password <input type="text" name="password" size="2
0"></p>
<p><input type="submit" value="Submit" name="B1"></p>
</form>
<p>&nbsp;</p>

</body>

</html>

LoginServlet.java

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

public class LoginServlet extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("username");
String pass = request.getParameter("password");
out.println("<html>");
out.println("<body>");
out.println("Thanks Mr." + " " + name + " " + "for visiting roseindia
<br>" );
out.println("Now you can see your password : " + " " + pass + "<br
>");
out.println("</body></html>");
}
}

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:

Multiple values for a single parameter

In our program it may be that we may have multiples values for a single parameter like in
checkboxes. We are going to make one program over it.
To make such a servlet which we have made one html form from where the values will be
passed to the controller. In this program we have used the checkbox which will have the same
name but with different values. We have one more button submit, on pressing this button the
request will be forwarded.

Now in the servlet that is working like a controller will retrieve the values we have entered in
the html form by the method getParameterValues() which returns the array of String. At
last to retrieve all the values from the array use the for loop. The output will be displayed to
you by the PrintWriter object.
The code of the program is given below:

Index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<title>Insert title here</title>
</head>
<body>
<form method = "post" action = "/GetParameterServlet/GetParameterValues">
<p>Which of the whisky you like most</p>
<input type = "checkbox" name ="whisky" value = "RoyalChallenge">RoyalCha
llenge.<br>
<input type = "checkbox" name ="whisky" value = "RoyalStag">RoyalStag.<br
>
<input type = "checkbox" name ="whisky" value = "Bagpiper">Bagpiper.<br>
<input type ="submit" name= "submit">
</form>
</body>
</html>

GetParameterValues.java

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

public class GetParameterValues extends HttpServlet{


protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String[] whisky = request.getParameterValues("whisky");
for(int i=0; i<whisky.length; i++){
pw.println("<br>whisky : " + whisky[i]);
}
}
}

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>GetParameterValues</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/GetParameterValues</url-pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:


Here is the result of the above selection:

Time Updater in Servlet

In this program we are going to make one program on servlet which will keep on updating the
time in every second and the result will be displayed to you.

To make this servlet firstly we need to make a class named TimeUpdater. The name of the
class should be such that it becomes easy to understand what the program is going to do. Call
the method getWriter() method of the response object which will return a PrintWriter
object. Use the method getHeader() of the response object to add a new header. We can also
use setHeader() in place of getHeader(). The setHeader() method overrides the previous set
header. Now by using the PrintWriter object display the result on the browser.

The code of the program is given below:

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

public class TimeUpdater extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
PrintWriter pw = response.getWriter();

response.addHeader("Refresh", "1");
pw.println(new Date().toString());
}
}

The output of the program is given below:

Send Redirect in Servlet

When we want that someone else should handle the response of our servlet, then there we
should use sendRedirect() method.

In send Redirect whenever the client makes any request it goes to the container, there the
container decides whether the concerned servlet can handle the request or not. If not then
the servlet decides that the request can be handle by other servlet or jsp. Then the servlet
calls the sendRedirect() method of the response object and sends back the response to the
browser along with the status code. Then the browser sees the status code and look for that
servlet which can now handle the request. Again the browser makes a new request, but with
the name of that servlet which can now handle the request and the result will be displayed to
you by the browser. In all this process the client is unaware of the processing.

In this example we are going to make one html in which we will submit the user name and his
password. The controller will check if the password entered by the user is correct or not. If the
password entered by the user is correct then the servlet will redirect the request to the other
servlet which will handle the request. If the password entered by the user is wrong then the
request will be forwarded to the html form.

The code of the example is given below:

html file for this program:

<html>

<head>
<title>New Page 1</title>
</head>

<body>

<form method="POST" action="/SendRedirect/SendRedirectServlet">


<p>Enter your name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="text" name="username" size="20"></p>
<p>Enter your password&nbsp; <input type="text" name="password" size="2
0"></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nb
sp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n
bsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="submit" value="Submit" name="B1"></p>
</form>

</body>
</html>

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

public class SendRedirectServlet extends HttpServlet{


protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String name = request.getParameter("username");
String password = request.getParameter("password");
if(name.equals("James")&& password.equals("abc")){
response.sendRedirect("/SendRedirect/ValidUserServlet");
}
else{
pw.println("u r not a valid user");
}
}
}

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

public class ValidUserServlet extends HttpServlet{


protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
PrintWriter pw = response.getWriter();
pw.println("Welcome to roseindia.net " + " ");
pw.println("how are you");
}
}

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>SendRedirectServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/SendRedirectServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>ValidUserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/ValidUserServlet</url-pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:


Session Tracking

As we know that the Http is a stateless protocol, means that it can't persist the information. It
always treats each request as a new request. In Http client makes a connection to the server,
sends the request., gets the response, and closes the connection.

In session management client first make a request for any servlet or any page, the container
receives the request and generate a unique session ID and gives it back to the client along
with the response. This ID gets stores on the client machine. Thereafter when the client
request again sends a request to the server then it also sends the session Id with the request.
There the container sees the Id and sends back the request.

Session Tracking can be done in three ways:

1. Hidden Form Fields: This is one of the way to support the session tracking. As we
know by the name, that in this fields are added to an HTML form which are not
displayed in the client's request. The hidden form field are sent back to the server
when the form is submitted. In hidden form fields the html entry will be like this :
<input type ="hidden" name = "name" value="">. This means that when you submit
the form, the specified name and value will be get included in get or post method. In
this session ID information would be embedded within the form as a hidden field and
submitted with the Http POST command.
2. URL Rewriting: This is another way to support the session tracking. URLRewriting
can be used in place where we don't want to use cookies. It is used to maintain the
session. Whenever the browser sends a request then it is always interpreted as a new
request because http protocol is a stateless protocol as it is not persistent. Whenever
we want that out request object to stay alive till we decide to end the request object
then, there we use the concept of session tracking. In session tracking firstly a session
object is created when the first request goes to the server. Then server creates a token
which will be used to maintain the session. The token is transmitted to the client by the
response object and gets stored on the client machine. By default the server creates a
cookie and the cookie get stored on the client machine.
3. Cookies: When cookie based session management is used, a token is generated which
contains user's information, is sent to the browser by the server. The cookie is sent
back to the server when the user sends a new request. By this cookie, the server is
able to identify the user. In this way the session is maintained. Cookie is nothing but a
name- value pair, which is stored on the client machine. By default the cookie is
implemented in most of the browsers. If we want then we can also disable the cookie.
For security reasons, cookie based session management uses two types of cookies.

To Determine whether the Session is New or Old

In this program we are going to make one servlet on session in which we will check whether
the session is new or old.
To make this program firstly we need to make one class named CheckingTheSession. Inside
the doGet() method, which takes two objects one of request and second of response. Inside
this method call the method getWriter() of the response object. Use getSession() of the
request object, which returns the HttpSession object. Now by using the HttpSession we can
find out whether the session is new or old.

The code of the program is given below:

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

public class CheckingTheSession extends HttpServlet{


protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("Checking whether the session is new or old<br>");
HttpSession session = request.getSession();
if(session.isNew()){
pw.println("You have created a new session");
}
else{
pw.println("Session already exists");
}
}
}

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>CheckingTheSession</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/CheckingTheSession</url-pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:

Pre- Existing Session


In this example we are going to find out whether the session is pre-existing or not.

Consider a situation where servlet want to use only a existing session. It is not always a good
idea to create a new session. To perform this work we have one overloaded method
getSession(boolean) of the request object. If we don't want to create a new session then we
should use getSession(false).

In the example below we have used the method getSession(false) which will test whether
the session is null or not. If there will be no session then the new session will be created by the
method getSession().

The code of the program is given below:

PreExistingSessionServlet.java

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

public class PreExistingSessionServlet extends HttpServlet{


protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("Testing The Session : ");
HttpSession session = request.getSession(false);
if(session==null){
pw.println("There is no session");
pw.println("Can we create a session for you. Creating.........");
session = request.getSession();
}
else{
pw.println("Session already exists");
}
}
}

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>PreExistingSessionServlet</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/PreExistingSessionServlet</url-pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:


Get Session Id

In this example we are going to make a program in which we will find the session id which was
generated by the container.

HttpSession session = request.getSession(); Inside the service method we ask for the
session and every thing gets automatically, like the creation of the HttpSession object. There is
no need to generate the unique session id. There is no need to make a new Cookie object.
Everything happens automatically behind the scenes.

As soon as call the method getSession() of the request object a new object of the session
gets created by the container and a unique session id generated to maintain the session. This
session id is transmitted back to the response object so that whenever the client makes any
request then it should also attach the session id with the requsest object so that the container
can identify the session.

The code of the program is given below:

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

public class SessionIdServlet extends HttpServlet{


protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
HttpSession session = request.getSession();
String id = session.getId();
pw.println("Session Id is : " + id);
}
}

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>SessionIdServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/SessionIdServlet</url-pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:

sendRedirect

In send Redirect whenever the client makes any request it goes to the container, there the
container decides whether the concerned servlet can handle the request or not. If not then
the servlet decides that the request can be handle by other servlet or jsp. Then the servlet
calls the sendRedirect() method of the response object and sends back the response to the
browser along with the status code. Then the browser sees the status code and look for that
servlet which can now handle the request. Again the browser makes a new request, but with
the name of that servlet which can now handle the request and the result will be displayed to
you by the browser. The URL will have the address of the new servlet. In all this process the
client is unaware of the processing.

Servlet Redirect forces the browser to do work.

Send Redirect in Servlet

When we want that someone else should handle the response of our servlet, then there we
should use sendRedirect() method.

In send Redirect whenever the client makes any request it goes to the container, there the
container decides whether the concerned servlet can handle the request or not. If not then
the servlet decides that the request can be handle by other servlet or jsp. Then the servlet
calls the sendRedirect() method of the response object and sends back the response to the
browser along with the status code. Then the browser sees the status code and look for that
servlet which can now handle the request. Again the browser makes a new request, but with
the name of that servlet which can now handle the request and the result will be displayed to
you by the browser. In all this process the client is unaware of the processing.

The output of the program is given below:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Redirecting the page</title>
</head>
<body>
<form action = "/ServletProject/SendRedirect" method =
"post">
<tr>
<td>Enter your name :</td>
<td><input type = "text" name =
"username"></td>
</tr><br>
<tr>
<td>Enter your password :</td>
<td><input type = "password" name =
"password"></td>
</tr><br>
<tr>
<td><input type = "submit" name =
"submit"></td>
</tr>
</form>
</body>
</html>

import java.io.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendRedirect extends javax.servlet.http.HttpServlet implements


javax.servlet.Servlet {
public SendRedirect() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String name = request.getParameter("username");
String password = request.getParameter("password");
if(name.equals("James")&& password.equals("abc"))
{
response.sendRedirect("/ServletProject/ValidUser");
}
else
{
pw.println("u r not a valid user");
}
}
}

import java.io.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class for Servlet: ValidUser
*
*/
public class ValidUser extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet
{
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public ValidUser() {
super();
}

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter pw = response.getWriter();
pw.println("Welcome to roseindia.net<br>");
pw.println("how are you");
}
}

The code of the program is given below:

Random Redirector
In this program we are going to make such a servlet which will be responsible to select a site
randomly from the list of sites you have entered. Note that the selection of the site will be
randomly.

To make such a servlet firstly make a class named SiteSelectionServlet. Use the Vector class
where you can store the sites which you want to select randomly and the other class Random
which will helps you to select the site randomly.

The code of the program is given below:

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

public class SiteSelectionInServlet extends HttpServlet {

Vector sites = new Vector();


Random random = new Random();

public void init() throws ServletException {


sites.addElement("http://www.roseindia.net");
sites.addElement("http://www.java.sun.com");
sites.addElement("http://www.rediffmail.com");
sites.addElement("http://www.yahoo.com");
sites.addElement("http://www.indiatimes.com");
}

public void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

int siteIndex = Math.abs(random.nextInt()) % sites.size();


String site = (String)sites.elementAt(siteIndex);

response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
}
}

The output of the program is given below:


Note: The selection will be random.

Servlet Context

ServletContext is a interface which helps us to communicate with the servlet container.


There is only one ServletContext for the entire web application and the components of the web
application can share it. The information in the ServletContext will be common to all the
components. Remember that each servlet will have its own ServletConfig. The ServetContext
is created by the container when the web application is deployed and after that only the
context is available to each servlet in the web application.

Web application initialization:

1. First of all the web container reads the deployment descriptor file and then creates a
name/value pair for each <context-param> tag.
2. After creating the name/value pair it creates a new instance of ServletContext.
3. Its the responsibility of the Container to give the reference of the ServletContext to the
context init parameters.
4. The servlet and jsp which are part of the same web application can have the access of
the ServletContext.

The Context init parameters are available to the entire web application not just to the single
servlet like servlet init parameters.

How can we do the mapping of the Context init parameters in web.xml

<servlet>
<servlet-name>Mapping</servlet-name>
<servlet-class>ContextMapping</servlet-class>
</servlet>

<context-param>
<param-name>Email</param-name>
<param-value>admin@roseindia.net</param-value>
</context-param>

In the servlet code we will write this as

ServletContext context = getServletContext();


pw.println(context.getInitParameter("Email");

Thanks Jyoti, We have corrected the typo error.

ServletContextListener

ServletContextListener is a interface which contains two methods:

1. public void contextInitialized(ServletContextEvent event)


2. public void contextDestroyed(ServletContextEvent event)

When we implement any interface then we have to implement its all methods. This listener will
help a application to start and shutdown the events.

How the ServletContextListener is useful:

1. ServletContextListener is notified when the context is initialized.

a). ServletContextListener gets the context init parameters from the ServletContext.

b). It stores the database connection as an attribute, so that the other components in the web
application can access it.

2. It will be notified when the context is destroyed. It closes the database connection.

ServletContextListener example

Before going into the details of ServletContextListener we should understand what is


ServletContext. ServletContext is a interface which helps us to communicate with the servlet
container. There is only one ServletContext for the entire web application and the components
of the web application can share it. The information in the ServletContext will be common to all
the components. Remember that each servlet will have its own ServletConfig. The
ServetContext is created by the container when the web application is deployed and after that
only the context is available to each servlet in the web application.

ServletContextListener is a interface which contains two methods:

1. public void contextInitialized(ServletContextEvent event)


2. public void contextDestroyed(ServletContextEvent event)

When we implement any interface then we have to implement its all methods. This listener will
help a application to start and shutdown the events.

How the ServletContextListener is useful:


1. ServletContextListener is notified when the context is initialized.

a). ServletContextListener gets the context init parameters from the ServletContext.

b). It stores the database connection as an attribute, so that the other components in the web
application can access it.

2. It will be notified when the context is destroyed. It closes the database connection.

The code of the program is given below:

import javax.servlet.*;
import javax.servlet.http.*;

public class MyServletContextListener implements


ServletContextListener{
public void contextInitialized(ServletContextEvent event)
{
ServletContext sc = event.getServletContext();
String whatType = sc.getInitParameter("typeSelected");
Furniture f = new Furniture(whatType);
sc.setAttribute("furniture", f);
}
public void contextDestroyed(ServletContextEvent event)
{

}
}

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

public class ListenerTester extends


javax.servlet.http.HttpServlet
implements javax.servlet.Servlet {
public ListenerTester() {
super();
}

public void doGet(HttpServletRequest request, }


HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("context attributes set by the listener <br>");
Furniture f =
(Furniture)getServletContext().getAttribute("furniture");
pw.println("The furniture you have selected is :" +
f.getTypeSelected());
}

public void doPost(HttpServletRequest request,


HttpServletResponse response) throws ServletException,
IOException {
// TODO Auto-generated method stub
}
}
The output of the program is given below:

ServletContextAttributeListener

As we know that the javax.servlet.ServletContext interface used to represents a Servlet's


view of the web application it belongs to. All the servlets in an application can access the
SevletContext. It means that we keep such information in the servlet context which are
common to all the servlets. The elements of the ServletContext are stored in web.xml file.
Whenever the container gets start it reads the web.xml file. Occurrence of <context-
param> tag should appear before the Servlet tags.

ServletContext is a interface which helps us to communicate with the servlet container.


There is only one ServletContext for the entire web application and the components of the
web application can share it. The information in the ServletContext will be common to all the
components. Remember that each servlet will have its own ServletConfig. The ServetContext
is created by the container when the web application is deployed and after that only the
context is available to each servlet in the web application.

The listener ServletContextAttributeListener is an interface and extends the


java.util.EventListener class. This listener come into existence when this interface receives
notifications of changes to the attribute list on the servlet context of a web application.
Remember one thing before gets notified by the container, you should make sure that the
implementation class is configured in deployment descriptor for the web application. This
listener is used when we want to know when a attribute has been added in a context, when a
attribute has been removed and when it is replaced by another attribute. We can also say that
this attribute is used when the developer is interested to be notified when the context
attribute changes. Now you may be wondering what is an attribute. An attribute is an object
set or you can simply say that it is name/value pair where the name refers to a String and a
value refers to the Object.

javax.servlet.ServletContextAttributeListener interface has following methods:

1. attributeAdded(ServletContextAttributeEvent event): It notifies whenever a


new attribute is added to the servlet context.
2. attributeRemoved(ServletContextAttributeEvent event): It notifies whenever
the attribute is removed from the servlet context.
3. attributeReplaced(ServletContextAttributeEvent event): It notifies whenever
the attribute gets replaced on the servlet context.

In the above methods you can see that we have used ServletContextAttributeEvent class
as a parameter to the above methods. This class is a event class which is used for notifications
when the changes are made to the attributes of ServletContext in an application.

The class ServletContextAttributeEvent has two methods:

1. getName() : This method returns the name of the attribute that has been changed on
the ServletContext.
2. getValue(): This method will return the value of the attribute that has been added,
removed or replaced by other attribute.

HttpSessionListener
Before going into the details of the SessionListener we should firstly know about the
sessions. As we know that Http protocol is a "stateless" protocol. The term stateless means
that it can't persist the information. It can't remember the previous transactions. Whenever a
client makes a request for any resources to the server, the server receives the request and
processes the request and sends back the response. After sending the response the server
closes the connection and forgets about the previous requests. Whenever a client sends any
request to the server, the server treats each request as a new request. To remove this we have
been provided the facility of the session. In session tracking whenever a client sends a request
to the server then server creates a unique id for that request and sends back the unique id to
the client along with the response object, now whenever a client sends a request to the server
it also sends a unique id with it so that the server can know from where the request is coming.

Listeners listen the events. Whenever any event occurs it is listened by the listener. The
listener will be controller by the web servers.

HttpSessionListener is an interface which extends java.util.EventListener class. The main


purpose of this listener is to notify whenever there is a change in the list of active sessions in a
web application

This interface has two methods:

1. sessionCreated(HttpSessionEvent event): It will notify when the session is


created.
2. sessionDestroyed(HttpSessionEvent event): It will notify when the session gets
invalidated.

In the above methods we can see that we have used HttpSessionEvent as the parameter of
both the methods. This class has only one method getSession() which returns the current
session.

The code of the program is given below:

Make the entry of this file in the deployment descriptor file that is web.xml

import javax.servlet.*;
import javax.servlet.http.*;

public class MySessionListener


implements HttpSessionListener {
public MySessionListener() {
}
public void sessionCreated(HttpSessionEvent sessionEvent)
{
// Get the session
HttpSession session = sessionEvent.getSession();
try {
System.out.println("Session created: "+session);
session.setAttribute("foo","bar");
} catch (Exception e) {
System.out.println("Error in setting session attribute: "
}+ e.getMessage());
}
}
public void sessionDestroyed(HttpSessionEvent
sessionEvent) {
// Get the session that was invalidated
HttpSession session = sessionEvent.getSession();
// Log a message
System.out.println("Session invalidated: "+session);
System.out.println("The name is: " +
session.getAttribute("foo"));
}
}
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class ServletSessionListener extends HttpServlet{


public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
HttpSession session= request.getSession();
String str = (String)session.getAttribute("foo");
pw.println("The name is " + str);
}
}

The output of the program is given below:

HttpSessionListener example

Before going into the details of the SessionListener we should firstly know about the
sessions. As we know that Http protocol is a "stateless" protocol. The term stateless means
that it can't persist the information. It can't remember the previous transactions. Whenever a
client makes a request for any resources to the server, the server receives the request and
processes the request and sends back the response. After sending the response the server
closes the connection and forgets about the previous requests. Whenever a client sends any
request to the server, the server treats each request as a new request. To remove this we have
been provided the facility of the session. In session tracking whenever a client sends a request
to the server then server creates a unique id for that request and sends back the unique id to
the client along with the response object, now whenever a client sends a request to the server
it also sends a unique id with it so that the server can know from where the request is coming.

Listeners listen the events. Whenever any event occurs it is listened by the listener. The
listener will be controller by the web servers.

HttpSessionListener is an interface which extends java.util.EventListener class. The main


purpose of this listener is to notify whenever there is a change in the list of active sessions in a
web application

This interface has two methods:

1. sessionCreated(HttpSessionEvent event): It will notify when the session is


created.
2. sessionDestroyed(HttpSessionEvent event): It will notify when the session gets
invalidated.
In the above methods we can see that we have used HttpSessionEvent as the parameter of
both the methods. This class has only one method getSession() which returns the current
session.

The code of the program is given below:

Make the entry of this file in the deployment descriptor file that is web.xml

import javax.servlet.*;
import javax.servlet.http.*;

public class ListenerSession


implements HttpSessionListener {
public ListenerSession() {
}
public void sessionCreated(HttpSessionEvent sessionEvent) {
// Get the session that was created
HttpSession session = sessionEvent.getSession();
// Store something in the session, and log a message
try {
System.out.println("Session created: "+session);
session.setAttribute("dog", "labrador");
session.setAttribute("name", "Diana");
} catch (Exception e) {
System.out.println("Error in setting session attribute: " +
e.getMessage());
}
}
public void sessionDestroyed(HttpSessionEvent sessionEvent) {
// Get the session that was invalidated
HttpSession session = sessionEvent.getSession();
// Log a message
System.out.println("Session invalidated: "+session);
System.out.println("The breed of the dog is: " +
session.getAttribute("dog"));
System.out.println("The name of the dog is : " +
session.getAttribute("name"));
}
}

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

public class ServletListenerSession extends HttpServlet{


public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
HttpSession session= request.getSession();
String str = (String)session.getAttribute("dog");
String dogName = (String)session.getAttribute("name");
pw.println("The breed of the dog is " + str);
pw.println("The name of the dog is " + dogName);
}
}

The output of the example is given below:


HttpSessionAttributeListener

As we know that the Session is used to maintain the session between request. Session object is
responsible to hold the conversational state across multiple requests.

The listener HttpSessionAttributeListener is an interface and extends the


java.util.EventListener class. This listener will be called by the container whenever there
there will be change to the attribute list on the servlet session of a web application. This
listener is used when we want to know when a attribute has been added in a session, when a
attribute has been removed and when it is replaced by another attribute. We can also say that
this attribute is used when the developer is interested to be notified when the session
attribute changes. Now you may be wondering what is an attribute. An attribute is an object
set or you can simply say that it is name/value pair where the name refers to a String and a
value refers to the Object.

javax.servlet.http.HttpSessionAttributeListener interface has following methods:

1. attributeAdded(HttpSessionBindingEvent event): It notifies whenever a new


attribute is added to the servlet session.
2. attributeRemoved(HttpSessionBindingEvent event): It notifies whenever the
attribute is removed from the servlet session.
3. attributeReplaced(HttpSessionBindingEvent event): It notifies whenever the
attribute gets replaced on the servlet session.

In the above methods you can see that we have used HttpSessionBindingEvent class as a
parameter to the above methods. This class is a event class which is used for notifications
when the changes are made to the attributes of in a session.

The class HttpSessionBindingEvent has two methods:

1. getName() : This method returns the name of the attribute that has been change in
the session.
2. getValue(): This method will return the value of the attribute that has been added,
removed or replaced by other attribute.
3. getSession(): This method will return the session that has been changed.

HttpSessionAttributeListener Example

As we know that the Session is used to maintain the session between request. Session object is
responsible to hold the conversational state across multiple requests.

The listener HttpSessionAttributeListener is an interface and extends the


java.util.EventListener class. This listener will be called by the container whenever there
there will be change to the attribute list on the servlet session of a web application. This
listener is used when we want to know when a attribute has been added in a session, when a
attribute has been removed and when it is replaced by another attribute. We can also say that
this attribute is used when the developer is interested to be notified when the session
attribute changes. Now you may be wondering what is an attribute. An attribute is an object
set or you can simply say that it is name/value pair where the name refers to a String and a
value refers to the Object.

javax.servlet.http.HttpSessionAttributeListener interface has following methods:

1. attributeAdded(HttpSessionBindingEvent event): It notifies whenever a new


attribute is added to the servlet session.
2. attributeRemoved(HttpSessionBindingEvent event): It notifies whenever the
attribute is removed from the servlet session.
3. attributeReplaced(HttpSessionBindingEvent event): It notifies whenever the
attribute gets replaced on the servlet session.

In the above methods you can see that we have used HttpSessionBindingEvent class as a
parameter to the above methods. This class is a event class which is used for notifications
when the changes are made to the attributes of in a session.

The class HttpSessionBindingEvent has two methods:

1. getName() : This method returns the name of the attribute that has been change in
the session.
2. getValue(): This method will return the value of the attribute that has been added,
removed or replaced by other attribute.
3. getSession(): This method will return the session that has been changed.

The code of the program is given below:

import javax.servlet.*;
import javax.servlet.http.*;

public class SessionAttributeListenerExample


implements HttpSessionAttributeListener {
public void attributeAdded(HttpSessionBindingEvent
sessionBindingEvent) {
// Get the session
HttpSession session =
sessionBindingEvent.getSession();
// Log some information
System.out.println("[SessionAttr] "+new
java.util.Date()+
" Attribute added, session "+session+": "
+sessionBindingEvent.getName()+"="+
sessionBindingEvent.getValue());
}
public void
attributeRemoved(HttpSessionBindingEvent
sessionBindingEvent) {
// Get the session
HttpSession session =
sessionBindingEvent.getSession();
System.out.println(new java.util.Date()+" Attribute
removed,
session "+session+":
"+sessionBindingEvent.getName());
}
public void attributeReplaced(HttpSessionBindingEvent
sessionBindingEvent) {
// Get the session
HttpSession session =
sessionBindingEvent.getSession();
// Log some information
System.out.println(new java.util.Date()+" Attribute
replaced, session "+session+": "+sessionBindingEvent
.getName()+"="+sessionBindingEvent.getValue());
}
}

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

public class AttributeSessionForSession extends HttpServlet{


public void doGet(HttpServletRequest request,
HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
HttpSession session = request.getSession();
session.setAttribute("dog", "Labrador");
session.setAttribute("name", "moti");
session.setAttribute("age","5");
String str1 = (String)session.getAttribute("dog");
pw.println("The breed of the dog is " + str1);
String str2 = (String)session.getAttribute("age");
pw.println("The age of the dog is " + str2);
session.removeAttribute("name");
}
}

The output of the program is given below:

The output on the server will look like this:

httpsessionbindinglistener

Before going into the details of the HttpSessionBindingListener we should firstly know
about the sessions. As we know that Http protocol is a "stateless" protocol. The term stateless
means that it can't persist the information. It can't remember the previous transactions.
Whenever a client makes a request for any resources to the server, the server receives the
request and processes the request and sends back the response. After sending the response
the server closes the connection and forgets about the previous requests. Whenever a client
sends any request to the server, the server treats each request as a new request. To remove
this we have been provided the facility of the session. In session tracking whenever a client
sends a request to the server then server creates a unique id for that request and sends back
the unique id to the client along with the response object, now whenever a client sends a
request to the server it also sends a unique id with it so that the server can know from where
the request is coming.

HttpSessionBindingListener is a interface which extends java.util.EventListener


interface. The purpose of the this interface is to notify an object when it is bound to or
unbound from a session.

This interface has two methods:

1. valueBound(HttpSessionBindingEvent event): It notifies the object that is being


bound to a session and is responsible for identifying the session.
2. valueUnBound(HttpSessionBindingEvent event): It notifies the object that is
being unbound from a session and is responsible for identifying the session.

In the above method we can see that we have used the class HttpSessionBindingEvent as a
argument to the methods. The object is notified by an HttpSessionBindingEvent object

This class has two methods:

1. getName(): It returns the name with which the object is bound or unbound from the
session.
2. getSession(): This method returns the session to or from which the object is bound or
unbound.

httpsessionbindinglistener example

Before going into the details of the HttpSessionBindingListener we should firstly know
about the sessions. As we know that Http protocol is a "stateless" protocol. The term stateless
means that it can't persist the information. It can't remember the previous transactions.
Whenever a client makes a request for any resources to the server, the server receives the
request and processes the request and sends back the response. After sending the response
the server closes the connection and forgets about the previous requests. Whenever a client
sends any request to the server, the server treats each request as a new request. To remove
this we have been provided the facility of the session. In session tracking whenever a client
sends a request to the server then server creates a unique id for that request and sends back
the unique id to the client along with the response object, now whenever a client sends a
request to the server it also sends a unique id with it so that the server can know from where
the request is coming.

HttpSessionBindingListener is a interface which extends java.util.EventListener


interface. The purpose of the this interface is to notify an object when it is bound to or
unbound from a session.

This interface has two methods:

1. valueBound(HttpSessionBindingEvent event): It notifies the object that is being


bound to a session and is responsible for identifying the session.
2. valueUnBound(HttpSessionBindingEvent event): It notifies the object that is
being unbound from a session and is responsible for identifying the session.

In the above method we can see that we have used the class HttpSessionBindingEvent as a
argument to the methods. The object is notified by an HttpSessionBindingEvent object

This class has two methods:


1. getName(): It returns the name with which the object is bound or unbound from the
session.
2. getSession(): This method returns the session to or from which the object is bound or
unbound.

The code of the program is given below:

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

public class SessionBindingListenerExample extends


HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// Get the current session object, create one if necessary
HttpSession session = req.getSession();
// Add a UserName
session.setAttribute("name",
new UserName(getServletContext()));
out.println("This is the example of
HttpSessionBindingListener");
}
}

import javax.servlet.*;
import javax.servlet.http.*;

public class UserName implements


HttpSessionBindingListener {
ServletContext context;
public UserName(ServletContext context){
this.context = context;
}
public void valueBound(HttpSessionBindingEvent event)
{
context.log("The value bound is " + event.getName());
}
public void valueUnbound(HttpSessionBindingEvent
event) {
context.log("The value unbound is " + event.getName());
}
}

The output of the program is given below:

ServletRequestAttributeListener
This listener is used when we want to know when a attribute has been added in a request,
when a attribute has been removed and when it is replaced by another attribute. We can also
say that this attribute is used when the developer is interested to be notified when the request
attribute changes. Now you may be wondering what is an attribute. An attribute is an object
set or you can simply say that it is name/value pair where the name refers to a String and a
value refers to the Object.

javax.servlet.ServletRequestAttributeListener interface has following methods:

1. attributeAdded(ServletRequestAttributeEvent event): It notifies whenever a


new attribute is added to the servlet request.
2. attributeRemoved(ServletRequestAttributeEvent event): It notifies whenever
the attribute is removed from the servlet request.
3. attributeReplaced(ServletRequestAttributeEvent event): It notifies whenever
the attribute gets replaced on the servlet request.

In the above methods you can see that we have used ServletRequestAttributeEvent class
as a parameter to the above methods. This class is a event class which is used for notifications
when the changes are made to the attributes of ServletRequest in an application.

The class ServletRequestAttributeEvent has two methods:

1. getName() : This method returns the name of the attribute that has been changed on
the ServletRequest.
2. getValue(): This method will return the value of the attribute that has been added,
removed or replaced by other attribute.

Inserting Image in a database Table

Consider a case where we want that along with the name of the person and its information, his
image should also come with all these things. After going through this tutorial you can better
understand the concept of inserting a image in the database table, so go through this example
properly.

To get the program working we need to use a doGet() method to write our business logic as it
is server side programming so all the processing will be done by the container. First of all
make a class named JdbcInsertImage, the name of the class should be such that the person
can understand what the program is going to do. This class must extend the HttpServlet class
which is an abstract method. Now inside the doGet() method call the method getWriter() of
the class PrintWriter. To insert a image from our java program we need to make a connection
between our java class and the MySql database which we are using. After the connection
establishment we will pass a insertion query for the image in the prepareStatement()
method of the Connection object which returns the PreparedStatement object. Note that the
data type for the image we have used is mediumblob. It is case sensitive.

As we have to insert an image file in our database so there is a need to use a File class of the
java.io package. In the constructor of the File class pass the path of the file. To read the
image file we will use FileInputStream class. To set the image in the database use the
method setBinaryStream() of the PreparedStatement interface. If the image will be inserted
in the database you will get the message "image has been inserted" otherwise "image is not
inserted".

The code of the program is given below:

import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class JdbcInsertImage extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
PrintWriter pw = response.getWriter();
String connectionURL =
"jdbc:mysql://localhost:3306/roseindia";
java.sql.Connection connection=null;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL,
"root", "root");
PreparedStatement pst = connection.prepareStatement
("insert into image values(?,?)");
File file = new File("C:/apache-tomcat-5.5.20/webapps
/mywork/grad_sm.gif");
FileInputStream fis = new FileInputStream(file);
pst.setBinaryStream(1,fis,fis.available());
pst.setString(2, "Tim");
int i = pst.executeUpdate();
if(i!=0)
{
pw.println("image has been inserted");
}
else
{
pw.println("image is not inserted");
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}

The output of the program is given below:

say hello in spanish


In this program we are going to display "hello" in spanish along with the date.

To make this program we need to make a class SayHelloToSpain. To main logic of the
program will be written inside the doGet() method of the servlet. To print "hello" in servlet
setHeader() method of the response object should be "es". Here "es" means the content
language is spanish.

The code of the program is given below:

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

public class SayHelloToSpain extends HttpServlet {


public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
res.setHeader("Content-Language", "es");
Locale locale = new Locale("es", "");
DateFormat df = DateFormat.getDateTimeInstance
(DateFormat.LONG,DateFormat.LONG,locale);
df.setTimeZone(TimeZone.getDefault());
out.println("Hello spain will be written in this way");
out.println("En Español:");
out.println("\u00a1Hola Mundo!");
out.println(df.format(new Date()));
}
}

The output of the program is given below:

Accessing Date In Servlet

In this example, we are going to show how we can display a creation date of the session and
last accessed date or time and id on our browser. It is very easy to display it on our browser by
using the Date class of the java.util package.

As we know that the our servlet extends the HttpServlet and overrides the doGet() method
which it inherits from the HttpServlet class. The server invokes doGet() method whenever
web server receives the GET request from the servlet. The doGet() method takes two
arguments first is HttpServletRequest object and the second one is HttpServletResponse object
and this method throws the ServletException.

getSession(): getSession() is a method. This is the method that uses HttpServletRequest


object. When you call the method with its argument as true, the servlet reference
implementation creates a session if necessary. To properly maintain the session, you must call
getSession() before any output to response.

getCreationTime(): getCreationTime() is a method. This is the method that returns the time
when this session was created a long integer time.

getLastAccessedTime(): getLastAccessedTime() is a method. This is the method that returns


the last time the client sends request with this session.

getId(): This is the method that returns a string containing the unique identifier assigned to
this session.

Here is the code of this program:

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

public class AccessedDateServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
PrintWriter pw = response.getWriter();
HttpSession session = request.getSession(true);
Date create = new Date(session.getCreationTime());
Date accessed = new Date(session.getLastAccessedTime());
pw.println("ID " + session.getId());
pw.println("Create: " + create);
pw.println("Last Accessed: " + accessed);
String dataName = request.getParameter("dataName");
if (dataName != null && dataName.length() > 0) {
String dataValue = request.getParameter("dataValue");
session.putValue(dataName, dataValue);
}
String[] valueNames = session.getValueNames();
if (valueNames != null && valueNames.length > 0) {
for (int i = 0; i < valueNames.length; i++) {
String str = valueNames[i];
String str1 = session.getValue(str).toString();
pw.println(str + " = " + str1);
}
}
}
}

Download of this program:

XML file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>amar</servlet-name>
<servlet-class>AccessedDateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>amar</servlet-name>
<url-pattern>/AccessedDateServlet</url-pattern>
</servlet-mapping>
</web-app>

Output of this program is given below.

Post Message In servlet

In this example, we are going to implement posting massage to servlet. In the following
program, you will learn how to post massage.

Code Description:

The following program uses getOutputStream() method. This is the method that defines an
object to assist a servlet in sending a response to the client . The servlet container creates a
ServletResponse object and passes it as an argument to the servlet's service method.
ServletOutputStream is a constructor. This constructor provides an output stream for sending
data to the client. A ServletOutputStream object is created using response.getOutputStream()
method. The servlet extends the HttpServlet and overrides the doGet() method which is
inherited from HttpServlet class. The server invokes doGet() method whenever web server
receives the GET request from the servlet.

In this example we are going to make one html in which we post the massage given by user.
The controller will check if the username , password and comment entered by the user is blank
then servlet will display massage null, if the username, password and comment entered by the
user are not blank then servlet will display the massage entered by the user.

Html file for this program:

<html>
<head>
<title>post servlet</title>
</head>
<body>
<h2>Post Massage</h2>
<form Action="/amar/PostServlet" Method="GET">
<p> Username: <input type="text" name="username" size="20"></p>
<p> Password: <input type="password" name="password" size="20"></p>
<p> Comment: <textarea ROWS=2 COLS=50 height="100" NAME="comment"></textarea
></p><BR>
<input type="submit" VALUE="submit">
<input type="reset" value="reset">
</form>
</body>
</html>

Here is the code of this program:

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

public class PostServlet extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType("text/html");{
ServletOutputStream out = response.getOutputStream();
try {
out.println("<html><head><title>" + "</title></head>");
out.println("<body><h1>" + "</h1>");
String name = request.getParameter("username" );
String password = request.getParameter("password" );
String comment = request.getParameter( "comment" );
out.println("Name:" + name + "<BR>");
out.println("Password:" + password + "<BR>");
out.println("Comment: " + comment + "<BR>");
}
catch(Throwable t ) {
out.println("<P><pre>");
t.printStackTrace( new PrintStream(out) );
out.println ("</pre><P>");
}
out.println ("</body></html>");
}
}
}

Download of this program:

xml file of this program.

<?xml version="1.0" encoding="ISO-8859-1"?>


<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->
<web-app>
<servlet>
<servlet-name>amar</servlet-name>
<servlet-class>PostServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>amar</servlet-name>
<url-pattern>/PostServlet</url-pattern>
</servlet-mapping>
</web-app>

Output of this program.


Show Parameter In Servlet

In this section, you will learn how to send and put all parameter names into the table. The
following program uses two methods, which is described below.

Code Description:

Here, in this example, you will also see the use of getParameterNames() method and
getParameterValues() method. The logic of the program will be written inside the doGet()
method which takes two arguments, first is HttpServletRequest interface and the second
one is the HttpServletResponse interface and this method can throw ServletException.
First, it looks up all the parameter names via the getParameterNames() method of
HttpServletRequest. This returns an Enumeration. Next, it loops down the Enumeration in the
standard manner, using hasMoreElements() method to determine when to stop and using
nextElement to get each entry. Since nextElement returns an Object, it casts the result to a
String and passes that to getParameterValues, yielding an array of Strings. If that array is one
entry long and contains only an empty string, then the parameter had no values, and the
servlet generates an italicized "No Value" entry. The array takes more then one entry long,
then the parameter had multiple values and they are displayed in a table list. Otherwise the
one main value is just placed into the table.

getParameterNames(): getParameterNames() is a method. This is the method that returns


the parameter names for the request as an enumeration of string .

getParameterValues: getParameterValues() is a method. This is the method that returns the


values of the specified parameter for the request as an array of strings or null if the named
parameter does not exit.

Html file for this program:

<html>
<head>
<title>Form Post</title>
</head>

<body bgcolor="#FFFFFF">
<h1 align="center">A Sample FORM using POST</h1>

<form action="/amar/ShowParameterServlet" method="GET">


Item Number:
<input type="text" name="ItemNum"><br>
Quantity:
<input type="text" name="Quantity"><br>
<hr>
First Name:
<input type="text" name="FirstName"><br>

Last Name:
<input type="text" name="LastName"><br>
Address:
<textarea NAME="address" ROWS=3 COLS=40></textarea><br>
Credit Card:<br>
<input type="RADIO" name="CardType" value="Visa">Visa<br>

<input type="RADIO" name="CardType" value="Master Card">Master Ca


rd<br>

<input type="RADIO" name="CardType" value="India Express">India Ex


press<br>

Enter the Credit Card Number:


<input type="password" name="CardNum"><br>
Reenter the Credit Card Number:
<input type="password" name="CardNum"><BR><BR>
<center>
<input type="submit" VALUE="Submit ">
<input type ="reset" value= "Reset">
</center>
</form>
</body>
</html>

Here is the code of this program:


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

public class ShowParameterServlet extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String title ="Reading all request parameter";
pw.println("<html><head><title>" +
"<body bgcolor=\"#FFFFFF\">\n" +
"<H1 align=center>" + title + "</H1>\n" +
"<table border=1 align=center>\n" +
"<TR bgcolor=\"#8AEAF4\">\n" +
"<td>Parameter Name</td><td>Parameter Value(s)</td>\n
");
Enumeration Names = request.getParameterNames();
while(Names.hasMoreElements()) {
String str = (String)Names.nextElement();
pw.println("<tr><td>" + str + "</td><td>");
String[] Values = request.getParameterValues(str);
if (Values.length == 1) {
String paramValue = Values[0];
if (paramValue.length() == 0)
pw.print("<I>No Value</I>");
else
pw.print(paramValue);
}
else {
pw.println("<UL>");
for(int i=0; i<Values.length; i++) {
pw.println("<LI>" + Values[i]);
}
pw.println("</UL>");
}
}
pw.println("</td></tr></table>\n</body></html>");
}
}

Download of this program:

xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>amar</servlet-name>
<servlet-class>ShowParameterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>amar</servlet-name>
<url-pattern>/ShowParameterServlet</url-pattern>
</servlet-mapping>
</web-app>

Output of this program.


Inserting Data In Database table using Statement

In this program we are going to insert the data in the database from our java program in the
table stored in the database.

To accomplish our goal we first have to make a class named as ServletInsertingData, which
must extends the abstract HttpServlet class, the name of the class should be such that other
person can understand what this program is going to perform. The logic of the program will be
written inside the doGet() method that takes two arguments, first is HttpServletRequest
interface and the second one is the HttpServletResponse interface and this method can
throw ServletException.

Inside this method call the getWriter() method of the PrintWriter class. We can insert the
data in the database only and only if there is a connectivity between our database and the java
program. To establish the connection between our database and the java program we first
need to call the method forName(), which is static in nature of the class Class. It takes one
argument which tells about the database driver we are going to use. Now use the static
method getConnection() of the DriverManager class. This method takes three arguments
and returns the Connection object. SQL statements are executed and results are returned
within the context of a connection. Now your connection has been established. Now use the
method createStatement() of the Connection object which will return the Statement object.
This object is used for executing a static SQL statement and obtaining the results produced by
it. We have to insert a values into the table so we need to write a query for inserting the values
into the table. This query we will write inside the executeUpdate() method of the Statement
object. This method returns int value.
If the record will get inserted in the table then output will show "record has been inserted"
otherwise "sorry! Failure".

The code of the program is given below:

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

public class DataInsertion extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse respons
e)throws
ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String url = "jdbc:mysql://localhost/zulfiqar?user=root&password=admin";
Connection conn;
ResultSet rs;
try{
Class.forName("org.gjt.mm.mysql.Driver");
conn = DriverManager.getConnection(url);
Statement statement = conn.createStatement();
String query = "insert into emp_sal values('zulfiqar', 15000)";
int i = statement.executeUpdate(query);
if(i!=0){
out.println("The record has been inserted");
}
else{
out.println("Sorry! Failure");
}
rs = statement.executeQuery("select * from emp_sal");
while(rs.next()){
out.println("<p><table>" + rs.getString(1) + " " + rs.getInt(2) + "</p><
/table>");
}
rs.close();
statement.close();
}
catch (Exception e){
System.out.println(e);
}
}
}

XML File for this program

<?xml version="1.0" encoding="ISO-8859-1"?>


<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>DataInsertion</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/DataInsertion</url-pattern>
</servlet-mapping>
</web-app>

Table in the database before Insertion:


mysql> select * from
emp_sal;
Empty set (0.02 sec)

The output of the program is given below:

Table in the database after Insertion:

mysql> select * from


emp_sal;
+----------+--------+
| EmpName | salary |
+----------+--------+
| zulfiqar | 15000 |
+----------+--------+
1 row in set (0.02 sec)

Retrieving Data from the table using Statement

In this program we are going to fetch the data from the database in the table from our java
program.

To accomplish our goal we first have to make a class named as ServletFetchingData which
must extends the abstract HttpServlet class, the name of the class should be such that the
other person can understand what this program is going to perform. The logic of the program
will be written inside the doGet() method which takes two arguments, first is
HttpServletRequest interface and the second one is the HttpServletResponse interface
and this method can throw ServletException.

Inside this method call the getWriter() method of the PrintWriter class. We can retrieve the
data from the database only and only if there is a connectivity between our database and the
java program. To establish the connection between our database and the java program we
firstly need to call the method forName() which is static in nature of the class ClassLoader. It
takes one argument which tells about the database driver we are going to use. Now use the
static method getConnection() of the DriverManager class. This method takes three
arguments and returns the Connection object. SQL statements are executed and results are
returned within the context of a connection. Now your connection has been established. Now
use the method createStatement() of the Connection object which will return the Statement
object. This object is used for executing a static SQL statement and obtaining the results
produced by it. As we need to retrieve the data from the table so we need to write a query to
select all the records from the table. This query will be passed in the executeQuery() method
of Statement object, which returns the ResultSet object. Now the data will be retrieved by
using the getString() method of the ResultSet object.

The code of the program is given below:

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

public class ServletFetchingDataFromDatabase1 extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse respons
e) throws
ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection=null;
try{
Class.forName("org.gjt.mm.mysql.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "admin"
);
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("Select * from emp_sal");
while(rs.next()){
pw.println("EmpName" + " " + "EmpSalary" + "<br>");
pw.println(rs.getString(1) + " " + rs.getString(2) + "<br>");
}
}
catch (Exception e){
pw.println(e);
}
}
}

XML File for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3
//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-
class>ServletFetchingDataFromDatabase</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/ServletFetchingDataFromDatabase</url-
pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:


Table in the database:

mysql> select * from


emp_sal;
+----------+--------+
| EmpName | salary |
+----------+--------+
| zulfiqar | 15000 |
| vinod | 12000 |
+----------+--------+
2 rows in set (0.00 sec)

Inserting data from the HTML page to the database

In this program we are going to make program in which we are going to insert the values in the
database table from the html form.

To make our program working we need to make one html form in which we will have two fields,
one is for the name and the other one is for entering the password. At last we will have the
submit form, clicking on which the values will be passed to the server.

The values which we have entered in the Html form will be retrieved by the server side
program which we are going to write. To accomplish our goal we first have to make a class
named as ServletInsertingDataUsingHtml which must extends the abstract HttpServlet
class, the name of the class should be such that the other person can understand what this
program is going to perform. The logic of the program will be written inside the doGet()
method which takes two arguments, first is HttpServletRequest interface and the second
one is the HttpServletResponse interface and this method can throw ServletException.

Inside this method call the getWriter() method of the PrintWriter class. We can insert the
data in the database only and only if there is a connectivity between our database and the java
program. To establish the connection between our database and the java program we firstly
need to call the method forName() which is static in nature of the class Class. It takes one
argument which tells about the database driver we are going to use. Now use the static
method getConnection() of the DriverManager class. This method takes three arguments
and returns the Connection object. SQL statements are executed and results are returned
within the context of a connection. Now your connection has been established. Now use the
method prepareStatement() of the Connection object which will return the
PreparedStatement object and takes one a query which we want to fire as its input. The values
which we have got from the html will be set in the database by using the setString() method
of the PreparedStatement object.

If the record will get inserted in the table then output will show "record has been inserted"
otherwise "sorry! Failure".
The code of the program is given below:

<html>

<head>
<title>New Page 1</title>
</head>

<body>

<form method="POST" action="/InDataByHtml/ServletInsertingDataUsingHtml">


<!--webbot bot="SaveResults" U-File="fpweb:///_private/form_results.txt"
S-Format="TEXT/CSV" S-Label-Fields="TRUE" -->
<p>Enter Name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text"
name="username" size="20"></p>
<p>Enter Password: <input type="text" name="password" size="20"></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&
nbsp;&nbsp;
<input type="submit" value="Submit" name="B1"></p>
</form>

</body>

</html>

ServletInsertingDataUsingHtml.java

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

public class ServletInsertingDataUsingHtml extends HttpServlet{


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection;
try{
String username = request.getParameter("username");
String password = request.getParameter("password");
pw.println(username);
pw.println(password);
Class.forName("org.gjt.mm.mysql.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "admin");
PreparedStatement pst = connection.prepareStatement("insert into emp_info v
alues(?,?)");
pst.setString(1,username);
pst.setString(2,password);
int i = pst.executeUpdate();
if(i!=0){
pw.println("<br>Record has been inserted");
}
else{
pw.println("failed to insert the data");
}
}
catch (Exception e){
pw.println(e);
}
}
}
web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>ServletInsertingDataUsingHtml</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/ServletInsertingDataUsingHtml</url-
pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:

This is the output of the above input.

Retrieving Data from the table using PreparedStatement

In this program we are going to fetch the data from the database in the table from our java
program using PreparedStatement.

To accomplish our goal we first have to make a class named as


ServletFetchingDataFromDatabase which must extends the abstract HttpServlet class,
the name of the class should be such that the other person can understand what this program
is going to perform. The logic of the program will be written inside the doGet() method which
takes two arguments, first is HttpServletRequest interface and the second one is the
HttpServletResponse interface and this method can throw ServletException.

Inside this method call the getWriter() method of the PrintWriter class. We can retrieve the
data from the database only and only if there is a connectivity between our database and the
java program. To establish the connection between our database and the java program we
firstly need to call the method forName() which is static in nature of the class ClassLoader. It
takes one argument which tells about the database driver we are going to use. Now use the
static method getConnection() of the DriverManager class. This method takes three
arguments and returns the Connection object. SQL statements are executed and results are
returned within the context of a connection. Now your connection has been established. Now
use the method prepareStatement() of the Connection object which will return the
PreparedStatement object and takes a query as its parameter. In this query we will write the
task we want to perform. The Resultset object will be retrieved by using the executeQuery()
method of the PreparedStatement object. Now the data will be retrieved by using the
getString() method of the ResultSet object.

The code of the program is given below:

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

public class ServletFetchingDataFromDatabase extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse respons
e) throws
ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection=null;
try{
Class.forName("org.gjt.mm.mysql.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "admin"
);
PreparedStatement pst = connection.prepareStatement("Select * from emp
_sal");
ResultSet rs = pst.executeQuery();
while(rs.next()){
pw.println(rs.getString(1) +" " + rs.getString(2)+"<br>");
}
}
catch (Exception e){
pw.println(e);
}
pw.println("hello");
}
}

The output of the program is given below:


Table in the database:

mysql> select * from emp_sal;


+----------+--------+
| EmpName | salary |
+----------+--------+
| zulfiqar | 15000 |
| vinod | 12000 |
+----------+--------+
2 rows in set (0.00 sec)

Getting Columns Names using Servlets

Consider a situation where there is a need to know about the name of the columns without
touching our database. As we are the programmers so why we need to worry about the
database. We want to do the manipulation by sitting on our computer through our program
without going into the database.

In this example we are going to exactly the same as we said above. To make this possible we
need to make a class named ServletGettingColumnsNames, the name of the program
should be such that if in future there is any need to make any change in the program, you can
easily understand in which program you have to make a change. Now inside the doGet()
method use the getWriter() method of the response object and its returns the PrintWriter
object, which helps us to write on the browser. To get a column names from the database there
is a need for the connection between the database and the java program. After the
establishment of the connection with the database pass a query for retrieving all the records
from the database and this will return the PreparedStatement object. To get the column names
from the database we firstly need a reference of ResultSetMetaData object and we will get it
only when if we have the ResultSet object. To get the object of the ResultSet we will call the
method executeQuery() of the PreparedStatement interface. Now we have the object of the
ResultSet. By the help of the ResultSet we can get the object of ResultSetMetaData. We will get
it by calling the method getMetaData() of the ResultSet interface. The names of the columns
will be retrieved by the method getColumnsNames() of the ResultSetMetaData interface.
The output will be displayed to you by the PrintWriter object.

The code of the program is given below:

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

public class ServletGettingColumnsNames extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse respon
se)
throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection=null;
try{
Class.forName("org.gjt.mm.mysql.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "admin
");
PreparedStatement pst = connection.prepareStatement("select * from em
p_details");
ResultSet rs = pst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int noOfColumns = rsmd.getColumnCount();
//It shows the number of columns
pw.println("The number of columns are " + noOfColumns + "<br>");
//It shows the name of the columns
pw.println("The name of the columns are: <br>");
for(int i =1; i<=noOfColumns;i++){
String names = rsmd.getColumnName(i);
pw.println(names);
}
}
catch(Exception e){
pw.println("The exception is " + e);
}
}
}

XML File for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>ServletGettingColumnsNames</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/ServletGettingColumnsNames</url-
pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:

Table in the database:

mysql> select * from emp_details;


+--------+----------+---------+-----------+----------+-------
+---------+--------
-+
| userId | Name | surname | address1 | address2 |
town | country | zipcode
|
+--------+----------+---------+-----------+----------+-------
+---------+--------
-+
| 73979 | zulfiqar | Ahmed | Moradabad | Delhi |
Okhla | India | 110025
|
+--------+----------+---------+-----------+----------+-------
+---------+--------
-+
1 row in set (0.00 sec)
Getting Number of Columns

Consider a situation where there is a need to know about the number of columns in the table
without touching our database. As we are the programmers so why we should worry about the
database. We want to do the manipulation by sitting on our computer through our program
without going into the database.

In this example we are going to exactly the same as we said above. To make this possible we
need to make a class named ServletGettingNoOfColumns, the name of the program should
be such that if in future there is any need to make any change in the program, you can easily
understand in which program you have to make a change. As we know that in Servlet the main
logic of the program is written inside the service method and in turn the service method calls
the doGet() method. Now inside the doGet() method use the getWriter() method of the
response object and its returns the PrintWriter object, which helps us to write on the browser.
To get the number of columns from the database table there is a need for the connection
between the database and the java program. After the establishment of the connection with
the database, pass a query for retrieving all the records from the database and this will return
the PreparedStatement object. To get the number of columns from the database we firstly
need a reference of ResultSetMetaData object and we will get it only when if we have the
ResultSet object with us. To get the object of the ResultSet we will call the method
executeQuery() of the PreparedStatement interface. Now we have the object of the
ResultSet. By the help of the ResultSet we can get the object of ResultSetMetaData. We will
get it by calling the method getMetaData() of the ResultSet interface. The number of
columns in the databasd table will be retrieved by the method getColumnsCount() of the
ResultSetMetaData interface. This method will return the integer type of value. The number of
columns will be displayed on the browser by the PrintWriter object.

The code of the program is given below:

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

public class ServletGettingNoOfColumns extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse respon
se) throws
ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "admin
");
PreparedStatement pst = connection.prepareStatement("select * from em
p_details");
ResultSet rs = pst.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int noOfColumns = rsmd.getColumnCount();
//It shows the number of columns
pw.println("The number of columns are " + noOfColumns);
}
catch(Exception e){
pw.println("The exception is " + e);
}
}
}

web.xml file for this program:


<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>ServletGettingNoOfColumns</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/ServletGettingNoOfColumns</url-pattern>
</servlet-mapping>
</web-app>

Table emp_details in the database:

mysql> select * from emp_details;


+--------+----------+---------+-----------+----------+--------
+---------+-------
--+
| userId | Name | surname | address1 | address2 | town |
country | zipcod
e|
+--------+----------+---------+-----------+----------+--------
+---------+-------
--+
| 86372 | Zulfiqar | Ahmed | Moradabad | Rohini | Rohini |
Delhi | 110025
|
+--------+----------+---------+-----------+----------+--------
+---------+-------

The output of the program is given below:

Getting Number of Rows

Consider a situation where we want to know about the number of rows in the particular
database table without touching our database. As we are the programmers so why we should
worry about the database complexities. We want to find out the number of rows without going
touching our back- end.

In this example we are going to exactly the same as we said above. To make this possible we
need to make a class named ServletGettingNoOfRows, the name of the program should be
such, if in future there is any need to make any change in the program, you can easily
understand in which program you have to make a change. As we know that in Servlet the main
logic of the program is written inside the service method and in turn the service method calls
the doGet() method. Now inside the doGet() method use the getWriter() method of the
response object and its returns the PrintWriter object, which helps us to write on the browser.
To get the number of rows from the database table there is a need for the connection between
the database and the java program. After the establishment of the connection with the
database, fire a query for selecting the number of rows from the database table inside the
executeQuery() method of the PreparedStatement object and returns the ResultSet object.
Now we have the ResultSet object, by the help of this object we can get the number of rows we
have in the database table. The number of rows we have in the database table will be
displayed on the browser by the PrintWriter object.

The code of the program is given below:

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

public class ServletGettingNoOfRows extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse respons
e) throws
ServletException, IOException{
int rows=0;
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection;
try{
Class.forName("org.gjt.mm.mysql.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "admin"
);
PreparedStatement pst = connection.prepareStatement("");
ResultSet rs = pst.executeQuery("select count(*) from emp_sal");
while (rs.next()){
rows = rs.getInt(1);
}
pw.println("The number of rows are " + rows);
}
catch(Exception e){
pw.println("The exception is " + e);
}
}
}

XML File for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>ServletGettingNoOfRows</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/ServletGettingNoOfRows</url-pattern>
</servlet-mapping>
</web-app>

Table emp_sal in the database:

mysql> select * from


emp_sal;
+----------+--------+
| EmpName | salary |
+----------+--------+
| zulfiqar | 15000 |
| vinod | 12000 |
+----------+--------+
2 rows in set (0.05 sec)

The output of the program is given below:

Deleting Rows From Table

Consider a situation where we have entered some wrong data and in later situation it starts
giving problem to the organization. Rather than go through with that data its better to delete
that data. We can do it very easily through our program, what we need is a simple query.

In this example we are going to exactly the same as we said above. To make this possible we
need to make a class named ServletDeletingRowsFromTable, the name of the program
should be such, if in future there is any need to make any change in the program, you can
easily understand in which program you have to make a change. As we know that in Servlet
the main logic of the program is written inside the service method and in turn the service
method calls the doGet() method. Now inside the doGet() method use the getWriter()
method of the response object and its returns the PrintWriter object, which helps us to write
on the browser. To delete the unwanted data from our table there is a need for the connection
between the database and the java program. After the establishment of the connection with
the database, fire a query for deleting the unwanted row in the database table. This query will
be fired inside the prepareStatement() method of the Connection object and returns the
PreparedStatement object. If the rows has been deleted from the database table then print the
message "row is deleted" otherwise "no rows has been deleted".

The code of the program is given below:

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

public class ServletDeletingRowsFromTable extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse respon
se) throws
ServletException, IOException{
int rows;
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection;
try{
Class.forName("org.gjt.mm.mysql.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "admin
");
PreparedStatement pst = connection.prepareStatement
("delete from emp_sal where EmpName = 'vinod'");
int i = pst.executeUpdate();
if (i==0){
pw.println("Row has been deleted");
}
else{
pw.println("No rows has been deleted");
}
}
catch(Exception e){
pw.println("The exception is " + e);
}
}
}

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>ServletDeletingRowsFromTable</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/ServletDeletingRowsFromTable</url-
pattern>
</servlet-mapping>
</web-app>

Table in the database before deletion:

mysql> select * from


emp_sal;
+----------+--------+
| EmpName | salary |
+----------+--------+
| zulfiqar | 15000 |
| vinod | 12000 |
+----------+--------+
2 rows in set (0.00 sec)

The output of the program is given below:

Table in the database after deletion:

mysql> select * from


emp_sal;
+----------+--------+
| EmpName | salary |
+----------+--------+
| zulfiqar | 15000 |
+----------+--------+
1 row in set (0.05
sec)

Deleting All Rows From the database Table

Consider a situation where we have entered some wrong data and in later situation it starts
giving problem to an organization or may become useless after sometime . Rather than go
through with that data its better to delete that data. We can do it very easily through our
program, what we need is a simple query.

In this example we are going to exactly the same as we said above. To make this possible we
need to make a class named ServletDeletingAllRowsFromTable, the name of the program
should be such, if in future there is any need to make any change in the program, you can
easily understand in which program you have to make a change. As we know that in Servlet
the main logic of the program is written inside the service method and in turn the service
method calls the doGet() method. Now inside the doGet() method use the getWriter()
method of the response object and its returns the PrintWriter object, which helps us to write
on the browser. To delete all the rows from our database table there is a need for the
connection between the database and the java program. After the establishment of the
connection with the database, fire a query for deleting all the rows in the database table. This
query will be fired inside the prepareStatement() method of the Connection object and
returns the PreparedStatement object. If the rows has been deleted from the database table
then print the message "all rows are deleted" otherwise "no rows has been deleted".

The code of the program is given below:

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

public class ServletDeletingAllRowsFromTable extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse re
sponse)
throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection;
try{
Class.forName("org.gjt.mm.mysql.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "a
dmin");
PreparedStatement pst = connection.prepareStatement("delete from
emp_sal");
int i = pst.executeUpdate();
if (i==0){
pw.println("All rows are deleted");
}
else{
pw.println("no rows has been deleted");
}
}
catch(Exception e){
pw.println("The exception is " + e);
}
}
}

XML File for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-
class>ServletDeletingAllRowsFromTable</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/ServletDeletingAllRowsFromTable</url-
pattern>
</servlet-mapping>
</web-app>

Table in the database before deletion:

mysql> select * from


emp_sal;
+----------+--------+
| EmpName | salary |
+----------+--------+
| zulfiqar | 15000 |
| vinod | 12000 |
+----------+--------+
2 rows in set (0.00
sec)

The output of the program is given below:

Table in the database after deletion:

mysql> select * from


emp_sal;
Empty set (0.02 sec)

How to add a column in a table

Consider a situation where the requirement of the client gets changed and you have asked to
modify the structure of the table. In reality it is the work of the database administrator but as a
Java programmer you should know how you can modify the structure of the table. The problem
is that we have to add a new column to our database by using the java program. There is no
need to get panic. What we simply need is to use a query for adding a new column in the
database table.

To get the desired result firstly we need to make a connection with our database. After
connection has been established pass the query in the prepareStatement() for adding new
column in the database. This method will return the PreparedStatement object. By the
object of the PreparedStatement we will call the executeUpdate() which will tell the status
of the table.

The code of the example is given below:

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

public class ServletAddingNewColumn extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse respons
e) throws
ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection;
try{
Class.forName("org.gjt.mm.mysql.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "admin"
);
PreparedStatement pst = connection.prepareStatement
("alter table emp_details add column sal int(5)");
int i = pst.executeUpdate();
if (i==1){
pw.println("Column has been added");
}
else{
pw.println("No column has been added");
}
}
catch(Exception e){
pw.println("The exception is " + e);
}
}
}

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>ServletAddingNewColumn</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/ServletAddingNewColumn</url-pattern>
</servlet-mapping>
</web-app>
The output of the program is given below:

How to delete a table in mysql

Consider a situation where we need to delete a table from a database.

To delete a table from the database firstly we need to make a connection with the database.
When the connection has been established pass a query for deleting a table inside the
prepareStatement() method and it will return the PreparedStatement object. Now call the
method executeUpdate() of the PreparedStatement interface which will helps us to know
the status of the program.

The code of the program is given below:

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

public class ServletDeletingTable extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse respon
se) throws
ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection;
try{
Class.forName("org.gjt.mm.mysql.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "admin
");
PreparedStatement pst = connection.prepareStatement("drop table emp_s
al");
int i = pst.executeUpdate();
if (i==0){
pw.println("Table has been deleted");
}
else{
pw.println("Table has not been deleted");
}
}
catch(Exception e){
pw.println("The exception is " + e);
}
}
}

XML File for this program:


<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>ServletDeletingTable</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/ServletDeletingTable</url-pattern>
</servlet-mapping>
</web-app>

Table in the database before deletion:

mysql> select * from emp_sa


+----------+--------+
| EmpName | salary |
+----------+--------+
| zulfiqar | 15000 |
| vinod | 12000 |
+----------+--------+
2 rows in set (0.00 sec)

The output of the program is given below:

Table in the database after deletion:

mysql> select * from emp_sal;


ERROR 1146 (42S02): Table
'zulfiqar.emp_sal' doesn't exist

Changing column name

We make a table for storing some type of data. Table keeps the data in the form of rows and
columns. Column indicates the field while row indicate the data of the field. Now consider a
scenario where we have a table and it consists some data and a situation arises where there is
a need to change the name of the column. As this is not the work of the programmer to
change the name of the field, but as a programmer we should be aware how we can change
the name of the column.

The name of the column of the column will be changed by using the simple query. But before
going into it we should see what are the initial steps to get the desired results. First of all make
a database connection with your program. When the connection has been established pass a
query for changing the column name in the preparedStatement(). This will return the
PreparedStatement object.

The code of the program is given below:


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

public class ServletChangingColumnName extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection;
try{
Class.forName("org.gjt.mm.mysql.Driver");
connection = DriverManager.getConnection(connectionURL, "root","admin");
PreparedStatement pst = connection.prepareStatement("alter table emp_details

change firstname Name varchar(10)");


int i = pst.executeUpdate();
pw.println("The name of the column has been changed");
}
catch(Exception e){
pw.println("The exception is " + e);
}
}
}

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>ServletChangingColumnName</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/ServletChangingColumnName</url-
pattern>
</servlet-mapping>
</web-app>

The table in the database before changing of column name:

mysql> select * from emp_details;


+--------+----------+---------+-----------+----------+-------
+-----------
| userId | Name | surname | address1 | address2 |
town | country | zipcode
+--------+----------+---------+-----------+----------+-------
+-----------
| 73979 | zulfiqar | Ahmed | Moradabad | Delhi |
Okhla | India | 110025
+--------+----------+---------+-----------+----------+-------
+-----------
1 row in set (0.00 sec)

The output of the program is given below:


The table in the database after changing the column name:

mysql> select * from emp_details;


+--------+-----------+---------+-----------
+----------+-------+-----------
| userId | firstname | surname | address1 |
address2 | town | country | zipcode
+--------+-----------+---------+-----------
+----------+-------+-----------
| 73979 | zulfiqar | Ahmed | Moradabad |
Delhi | Okhla | India | 110025
+--------+-----------+---------+-----------
+----------+-------+-----------
1 row in set (0.03 sec)

insert into statement in sql using servlets

In this tutorial we are going to learn how we can insert a value from a html form in the table
stored in the database.

For inserting the values in the database table it is required to have a table in which we are
going to insert the values. Now make one jsp page or html page where we will insert the
values. In this program we have made one simple enquiry form which will get stored in the
database table and when the data gets entered into the database then you will get a message.
Make one submit button for inserting the values into the database. Firstly this values will go to
the controller and retrieved the variables enter in the form by the method getParameter()
method of the request object. Pass a query to insert the values retrieved from the html form.
To set the values into the database use setString() method. To retrieve the values from the
database use getString() method of the PreparedStatement object.

The code of the program is given below:

<html>

<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>New Page 1</title>
</head>

<body>

<form method="POST" action="/sqlStatServlet/ServletUserEnquiryForm">


<!--webbot bot="SaveResults" U-File="fpweb:///_private/form_results.txt"
S-Format="TEXT/CSV" S-Label-Fields="TRUE" -->
<p>User Id:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="text" name="userId" size="20"></p>
<p>First Name:&nbsp;&nbsp; <input type="text" name="firstname" size="20"></p>
<p>Surname: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="surname" size
="20"></p>
<p>Address1:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="address1" size
="20"></p>
<p>Address2:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="address2" size
="20"></p>
<p>Town:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <inp
ut type="text"
name="town" size="20"></p>
<p>City:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;
<input type="text" name="country" size="20"></p>
<p>Zip code:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="zi
pcode" size="20"></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nb
sp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="submit" value="Submit" name="B1"></p>
</form>

</body>

</html>

ServletUserEnquiryForm.java

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

public class ServletUserEnquiryForm extends HttpServlet{


public void init(ServletConfig config) throws ServletException{
super.init(config);
}
/**Process the HTTP Get request*/
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection=null;
ResultSet rs;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
//get the variables entered in the form
String uId = req.getParameter("userId");
String fname = req.getParameter("firstname");
String sname = req.getParameter("surname");
String address1 = req.getParameter("address1");
String address2 = req.getParameter("address2");
String town = req.getParameter("town");
String county = req.getParameter("country");
String zipcode = req.getParameter("zipcode");
try {
// Load the database driver
Class.forName("org.gjt.mm.mysql.Driver");
// Get a Connection to the database
connection = DriverManager.getConnection(connectionURL, "root",
"admin");
//Add the data into the database
String sql = "insert into emp_details values (?,?,?,?,?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setString(1, uId);
pst.setString(2, fname);
pst.setString(3, sname);
pst.setString(4, address1);
pst.setString(5, address2);
pst.setString(6, town);
pst.setString(7, county);
pst.setString(8, zipcode);
int numRowsChanged = pst.executeUpdate();
// show that the new account has been created
out.println(" Hello : ");
out.println(" '"+fname+"'");
pst.close();
}
catch(ClassNotFoundException e){
out.println("Couldn't load database driver: " + e.getMessage());
}
catch(SQLException e){
out.println("SQLException caught: " + e.getMessage());
}
catch (Exception e){
out.println(e);
}
finally {
// Always close the database connection.
try {
if (connection != null) connection.close();
}
catch (SQLException ignored){
out.println(ignored);
}
}
}
}

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>ServletUserEnquiryForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/ServletUserEnquiryForm</url-pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:

Login.html form for the data input:


The output of the input data:

join tables mysql

In this program we are going to join the two table by using the servlets and the result will be
displayed in the browser.

To join the tables firstly it is important to make a connection between the java class and the
database. In our program we are using the MySql database. To join the table it is important to
have those tables in our database. First of all make a class named ServletJoiningTables. The
name of the class should be such that it becomes clear that what the program is going to do.
The logic of the program will be written inside the doGet() method which takes two arguments
HttpServletRequest and HttpServletResponse. call the method getWriter() of the
PrintWriter class, which is responsible for writing the contents on the browser. Our priority is
to join the two tables so pass a query in prepareStatement() method which will return the
PreparedStatement object.

The result will be displayed to you by the object of the PrintWriter class.
The code of the program is given below:

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

public class ServletJoiningTables extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection;
try{
Class.forName("org.gjt.mm.mysql.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "admin");
PreparedStatement pst = connection.prepareStatement("SELECT *FROM "+"emp
_details"+"
NATURAL JOIN "+"Emp_sal");
ResultSet rs = pst.executeQuery();
pw.println("UserId" + "\t\t" + "Name" + "\t\t" + "Salary"+"<br>");
while(rs.next()){
String id = rs.getString("userId");
String name = rs.getString("Name");
String sal = rs.getString("salary");
pw.println(id + "\t\t" + name + "\t\t" + sal + "<br>");
}
}
catch (Exception e){
pw.println("The statement is not executed");
}
}
}

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>ServletJoiningTables</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/ServletJoiningTables</url-pattern>
</servlet-mapping>
</web-app>

Tables emp_details and emp_sal in the database:

mysql> select * from emp_details;


+--------+----------+---------+-----------+----------+-------+---------
+--------
-+
| userId | Name | surname | address1 | address2 | town |
country | zipcode
|
+--------+----------+---------+-----------+----------+-------+---------
+--------
-+
| 73979 | zulfiqar | Ahmed | Moradabad | Delhi | Okhla | India
| 110025
|
+--------+----------+---------+-----------+----------+-------+---------
+--------
-+
1 row in set (0.00 sec)

mysql> select * from emp_sal;


+----------+--------+
| EmpName | salary |
+----------+--------+
| zulfiqar | 15000 |
| vinod | 12000 |
+----------+--------+
2 rows in set (0.00 sec)

Here we are getting data from the two tables in the database by combining them.

The output of the program is given below:

Natural Left Join

In this program we are going to join the two table by using the servlets and the result will be
displayed in the browser. This join will be natural left join.

To join the tables firstly it is important to make a connection between the java class and the
database. In our program we are using the MySql database. To join the table in a natural left
join manner it is important to have those tables in our database. First of all make a class
named ServletNaturalJoiningTables. The name of the class should be such that it becomes
clear that what the program is going to do. The logic of the program will be written inside the
doGet() method which takes two arguments HttpServletRequest and
HttpServletResponse. call the method getWriter() of the PrintWriter class, which is
responsible for writing the contents on the browser. Our priority is to join the two tables so
pass a query in prepareStatement() method which will return the PreparedStatement
object.

The result will be displayed to you by the object of the PrintWriter class.

The code of the program is given below:

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

public class ServletNaturalJoiningTables extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection;
try{
Class.forName("org.gjt.mm.mysql.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "admin");
PreparedStatement pst = connection.prepareStatement("SELECT * FROM "+"emp
_details"+"
NATURAL LEFT JOIN "+"emp_sal");
ResultSet rs = pst.executeQuery();
pw.println("UserId" + "\t" + "Firstname" + "\t" + "Salary"+"<br>");
while(rs.next()){
String id = rs.getString("userId");
String name = rs.getString("Name");
String sal = rs.getString("salary");
pw.println(id + "\t\t" + name + "\t\t" + sal + "<br>");
}
}
catch (Exception e) {
pw.println("The statement is not executed");
}
}
}

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>ServletNaturalJoiningTables</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/ServletNaturalJoiningTables</url-pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:

Natural Right Join

In this program we are going to join the two table by using the servlets and the result will be
displayed in the browser. This join will be natural right join.
To join the tables firstly it is important to make a connection between the java class and the
database. In our program we are using the MySql database. To join the table in a natural right
join manner, it is important to have those tables in our database. First of all make a class
named ServletNaturalRightJoiningTables. The name of the class should be such that it
becomes clear that what the program is going to do. The logic of the program will be written
inside the doGet() method which takes two arguments HttpServletRequest and
HttpServletResponse. call the method getWriter() of the PrintWriter class, which is
responsible for writing the contents on the browser. Our priority is to join the two tables so
pass a query in prepareStatement() method which will return the PreparedStatement
object.

The result will be displayed to you by the object of the PrintWriter class.

The code of the program is given below:

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

public class ServletNaturalRightJoiningTables extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Connection connection;
try{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "admin");
PreparedStatement pst = connection.prepareStatement("SELECT *FROM "+"emp
_details"+"
NATURAL RIGHT JOIN "+"emp_sal");
ResultSet rs = pst.executeQuery();
pw.println("userId" + "\t" + "Firstname" + "\t" + "salary"+"<br>");
while(rs.next()){
String id = rs.getString("userId");
String name = rs.getString("Name");
String sal = rs.getString("salary");
pw.println(id + "\t\t" + name + "\t\t" + sal + "<br>");
}
}
catch (Exception e) {
pw.println("The statement is not executed");
}
}
}

web.xml file for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.
3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>Zulfiqar</servlet-name>
<servlet-
class>ServletNaturalRightJoiningTables</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/ServletNaturalRightJoiningTables</url-
pattern>
</servlet-mapping>
</web-app>

The output of the program is given below:

GET and POST Method of HTTP

GET

The Get is one the simplest Http method. Its main job is to ask the server for the resource. If
the resource is available then then it will given back to the user on your browser. That
resource may be a HTML page, a sound file, a picture file (JPEG) etc. We can say that get
method is for getting something from the server. It doesn't mean that you can't send
parameters to the server. But the total amount of characters in a GET is really limited. In get
method the data we send get appended to the URL so whatever you will send will be seen by
other user so can say that it is not even secure.

POST

The Post method is more powerful request. By using Post we can request as well as send some
data to the server. We use post method when we have to send a big chunk of data to the
server, like when we have to send a long enquiry form then we can send it by using the post
method.

There are few more rarely used http methods including HEAD, PUT, TRACE, DELETE, OPTIONS
and CONNECT.

Select Color

In this program we are going to selected the various color and on the basis of the selection the
output will be displayed to the user.

To make this program firstly we need to make one html page. Inside the page we will have one
select option in which we will have our colors. We will also have a submit, clicking on which the
values we have entered will be transferred to the server.

On the server we will create a session. The values which we have entered in the html form will
be retrieved by the getParameterValues() of the request object. It returns the array of
String. We will check the condition if there is any session available or not. If yes then we will
set the attribute by using the setAttribute() method of the HttpSession object. The
attribute we have set will be retrieved by the getAttribute method of the HttpSession object
in the next page and the value will be displayed on the browser by the PrintWriter object.

The code of the program is given below:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Select the list of colors</title>
</head>
<body>
<form action = "/ServletProject/ColorPage">
<select name = "colors" size = 5 multiple>
<option selected>Green</option>
<option>Red</option>
<option>Yellow</option>
<option>Blue</option>
<option>Black</option>
</select>
<input type = "submit" name = "submit">
</form>
</body>
</html>

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

/**
* Servlet implementation class for Servlet: ColorPage
*
*/
public class ColorPage extends javax.servlet.http.HttpServlet implements
javax.servlet.Servlet {
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public ColorPage() {
super();
}

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet
(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
HttpSession session = request.getSession();
String colors[] = request.getParameterValues("colors");
if(session!=null)
{
session.setAttribute("color",colors);
session.setMaxInactiveInterval(60);
}
pw.println("<html><body bgcolor =cyan>");
for(int i = 0; i<colors.length; i++)
{
pw.println("The selected colors are" + colors[i]+ "<br>");
}
pw.println("<form action = /ServletProject/GetColors>");
pw.println("<input type = submit name= submit)>");
pw.println("</form></body></html>");
}

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest
request,
HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
}

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

/**
* Servlet implementation class for Servlet: GetColors
*
*/
public class GetColors extends HttpServlet {
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public GetColors() {
super();
}

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet(
HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
HttpSession session = request.getSession(false);
if(session == null)
{
pw.println("No session is available");
pw.println("We are creating a session for you. Creating.....");
session = request.getSession();
}
else
{
String getColors[] = (String[])session.getAttribute("color");
pw.println("<html><body bgcolor = cyan>");
for(int i= 0; i<getColors.length;i++)
{
pw.println("The selected colors are " + getColors[i] + "<br>");
}
pw.println("<html><body>");
}
}

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(
HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
}

The output of the program is given below:

Das könnte Ihnen auch gefallen