Friday, January 2, 2009

Servlet

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("");
pw.println("Hello World");
pw.println("");
pw.println("

Hello World

");
pw.println("");
}
}

web.xml file for this program:

"1.0" encoding="ISO-8859-1"?>




Hello
class>HelloWorldclass>


Hello
/HelloWorld

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, HttpServletResponse
response)
throws ServletException, IOException{
PrintWriter pw = response.getWriter();
Date today = new Date();
pw.println(""+"

Today Date is

");
pw.println(""+ today+""+ "");
}
}

XML File for this program

"1.0" encoding="ISO-8859-1"?>




Hello
class>DateDisplayclass>


Hello
/DateDisplay

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 threads

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
"
);
hashTable.put(this,this);
pw.println("There are currently" + hashTable.size() + "threads
"
);
}
}

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/html");
PrintWriter pw = response.getWriter();
counter++;
pw.println("Since loading this servlet has been accessed" + counter + "times");
}
}

web.xml file for this program:

"1.0" encoding="ISO-8859-1"?>




Hello
class>CounterInInitclass>


Hello
/CounterInInit

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() + "
"
);
pw.println("The server port number is " + request.getServerPort()+ "
"
);
pw.println("The protocol is " + request.getProtocol()+ "
"
);
pw.println("The scheme used is " + request.getScheme());
}
}

web.xml file for this program:

"1.0" encoding="ISO-8859-1"?>




Hello
class>SnoopingServerServletclass>


Hello
/SnoopingServerServlet

The output of the program is given below:


nooping 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 response)
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:

"1.0" encoding="ISO-8859-1"?>




Hello
class>HeaderSnoopServletclass>


Hello
/HeaderSnoopServlet


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("");
pw.println("dice roller
"
);
pw.println("dice1 value is " + dice1 + " and
dice2 value is "
+dice2);
}
}

XML File for this program:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>DiceRollerServletclass>


Zulfiqar
/DiceRollerServlet

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("AdminEmail"));
pw.println("The address is " + getServletConfig().getInitParameter("Address"));
pw.println("The phone no is " + getServletConfig().getInitParameter("PhoneNo"));
}
}

web.xml file of this program:

"1.0" encoding="ISO-8859-1"?>

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




AdminEmail
zulfiqar_mca@yahoo.co.in


Address
Okhla


PhoneNo
9911217074

Zulfiqar
class>InitServletclass>


Zulfiqar
/InitServlet

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:




New Page </span></code><code><span style="font-family: ">1</span></code><code><span style="font-family: ">




Login


Please enter your username and password


"GET" action="/htmlform/LoginServlet">

Username "text" name="username" size="20">


Password "text" name="password" size="20">


"submit" value="Submit" name="B1">







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("");
out.println("");
out.println("Thanks Mr." + " " + name + " " + "for visiting roseindia
"
);
out.println("Now you can see your password : " + " " + pass + "
"
);
out.println("");
}
}

web.xml file for this program:

"1.0" encoding="ISO-8859-1"?>




Hello
class>LoginServletclass>


Hello
/LoginServlet

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

"-//W3C//DTD HTML 4.01 Transitional//EN">



Insert title here


"post" action = "/GetParameterServlet/GetParameterValues">

Which of the whisky you like most


"checkbox" name ="whisky" value = "RoyalChallenge">RoyalChallenge.

"checkbox" name ="whisky" value = "RoyalStag">RoyalStag.

"checkbox" name ="whisky" value = "Bagpiper">Bagpiper.

"submit" name= "submit">


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
pw.println("
whisky : "
+ whisky[i]);
}
}
}

web.xml file for this program:

"1.0" encoding="ISO-8859-1"?>




Hello
class>GetParameterValuesclass>


Hello
/GetParameterValues

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:




New Page </span></code><code><span style="font-family: ">1</span></code><code><span style="font-family: ">




"POST" action="/SendRedirect/SendRedirectServlet">

Enter your name


"text" name="username" size="20">

Enter your password "text" name="password" size="20">





"submit" value="Submit" name="B1">






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:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>SendRedirectServletclass>


Zulfiqar
/SendRedirectServlet


Hello
class>ValidUserServletclass>


Hello
/ValidUserServlet

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 : . 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
"
);
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:

"1.0" encoding="ISO-8859-1"?>




Hello
class>CheckingTheSessionclass>


Hello
/CheckingTheSession

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:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>PreExistingSessionServletclass>


Zulfiqar
/PreExistingSessionServlet

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:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>SessionIdServletclass>


Zulfiqar
/SessionIdServlet

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:

                               
                               
               

               
                               
                               
               

               
                               
               
               
Redirecting the page
               
               
Enter your name :
Enter your password :

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
");
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 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


Mapping
ContextMapping



Email
admin@roseindia.net


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
");
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 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 <>
String str = valueNames[i];
String str1 = session.getValue(str).toString();
pw.println(str + " = " + str1);
}
}
}
}

Download of this program:

XML file for this program:






amar
AccessedDateServlet


amar
/AccessedDateServlet

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:



post servlet


Post Massage


"/amar/PostServlet" Method="GET">

Username: "text" name="username" size="20">


Password: "password" name="password" size="20">


Comment:



"submit" VALUE="submit">
"reset" value="reset">


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("" </span></code><code><span style="font-family: ">+ </span></code><code><span style="font-family: ">"");
out.println("

" + "

");
String name = request.getParameter("username" );
String password = request.getParameter("password" );
String comment = request.getParameter( "comment" );
out.println("Name:" + name + "
"
);
out.println("Password:" + password + "
"
);
out.println("Comment: " + comment + "
"
);
}
catch(Throwable t ) {
out.println("

");

t.printStackTrace( new PrintStream(out) );
out.println ("

"

);
}
out.println ("");
}
}
}

Download of this program:

xml file of this program.





amar
PostServlet


amar
/PostServlet

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:



Form Post


"#FFFFFF">

"center">A Sample FORM using POST



"/amar/ShowParameterServlet" method="GET">
Item Number:
"text" name="ItemNum">

Quantity:
"text" name="Quantity">



First Name:
"text" name="FirstName">


Last Name:
"text" name="LastName">

Address:


Credit Card:

"RADIO" name="CardType" value="Visa">Visa


"RADIO" name="CardType" value="Master Card">Master Card


"RADIO" name="CardType" value="India Express">India Express


Enter the Credit Card Number:
"password" name="CardNum">

Reenter the Credit Card Number:
"password" name="CardNum">



"submit" VALUE="Submit ">
"reset" value= "Reset">



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("" </span></code><code><span style="font-family: ">+</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">"<body bgcolor="\">\n" </span></code><code><span style="font-family: ">+</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">"<h1 align="center">" </span></code><code><span style="font-family: ">+ title + </span></code><code><span style="font-family: ">"</h1>\n" </span></code><code><span style="font-family: ">+</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">"<table border="1" align="center">\n" </span></code><code><span style="font-family: ">+</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">"<tr bgcolor="\">\n" </span></code><code><span style="font-family: ">+</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">"<td>Parameter Name</td><td>Parameter Value(s)</td>\n"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">Enumeration Names = request.getParameterNames();</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">while</span></b></code><code><span style="font-family: ">(Names.hasMoreElements()) {</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">String str = (String)Names.nextElement();</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">pw.println(</span></code><code><span style="font-family: ">"<tr><td>" </span></code><code><span style="font-family: ">+ str + </span></code><code><span style="font-family: ">"</td><td>"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">String[] Values = request.getParameterValues(str);</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">if </span></b></code><code><span style="font-family: ">(Values.length == </span></code><code><span style="font-family: ">1</span></code><code><span style="font-family: ">) {</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">String paramValue = Values[</span></code><code><span style="font-family: ">0</span></code><code><span style="font-family: ">];</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">if </span></b></code><code><span style="font-family: ">(paramValue.length() == </span></code><code><span style="font-family: ">0</span></code><code><span style="font-family: ">)</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">pw.print(</span></code><code><span style="font-family: ">"<i>No Value</i>"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">else</span></b></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">pw.print(paramValue);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">}</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">else </span></b></code><code><span style="font-family: ">{</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">pw.println(</span></code><code><span style="font-family: ">"<ul>"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">for</span></b></code><code><span style="font-family: ">(</span></code><code><b><span style="font-family: ">int </span></b></code><code><span style="font-family: ">i=</span></code><code><span style="font-family: ">0</span></code><code><span style="font-family: ">; i<values.length;></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">pw.println(</span></code><code><span style="font-family: ">"<li>" </span></code><code><span style="font-family: ">+ Values[i]);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">}</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">pw.println(</span></code><code><span style="font-family: ">"</ul>"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">}</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">}</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">pw.println(</span></code><code><span style="font-family: ">"</td></tr></table>\n</body></html>"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">}</span></code><br /> <code><span style="font-family: ">}</span></code> <o:p></o:p></span></p> </td> </tr> </tbody></table> <p><code><b><span style="font-size: 9pt; font-family: "><a href="http://www.roseindia.net/servlets/ShowParameterServlet.java">Download of this program:</a></span></b></code><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <p><code><b><span style="font-size: 9pt; font-family: ">xml file for this program:</span></b></code><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <table class="MsoNormalTable" style="background: rgb(255, 255, 221) none repeat scroll 0% 0%; width: 332.25pt; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" border="0" cellpadding="0" cellspacing="0" width="443"> <tbody><tr style=""> <td style="padding: 0in; width: 330.75pt;" width="441"> <p class="MsoNormal"><span style="font-size: 9pt; font-family: "><?xml version="1.0" encoding="ISO-8859-1"?><br /> <!--<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> --><br /> <br /> <web-app><br /> <servlet><br /> <servlet-name>amar</servlet-name><br /> <servlet-class>ShowParameterServlet</servlet-class><br /> </servlet><br /> <servlet-mapping><br /> <servlet-name>amar</servlet-name><br /> <url-pattern>/ShowParameterServlet</url-pattern><br /> </servlet-mapping><br /> </web-app><o:p></o:p></span></p> </td> </tr> </tbody></table> <p><b><span style="font-size: 9pt; font-family: ">Output of this program.</span></b><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <table class="MsoNormalTable" style="width: 150pt;" border="0" cellpadding="0" cellspacing="0" width="200"> <tbody><tr style=""> <td style="padding: 0in;"> <p class="MsoNormal"><span style="font-size: 9pt; font-family: "><!--[if gte vml 1]><v:shape id="_x0000_i1198" type="#_x0000_t75" alt="" style="'width:327pt;height:225pt'"> <v:imagedata src="file:///D:\USERPR~1\sshende\LOCALS~1\Temp\msohtmlclip1\01\clip_image046.gif" href="http://www.roseindia.net/servlets/showparameter1.gif"> </v:shape><![endif]--><!--[if !vml]--><br /><!--[endif]--><o:p></o:p></span></p> </td> </tr> </tbody></table> <p><span style="font-size: 9pt; font-family: "> <o:p></o:p></span></p> <table class="MsoNormalTable" style="width: 150pt;" border="0" cellpadding="0" cellspacing="0" width="200"> <tbody><tr style=""> <td style="padding: 0in;"> <p class="MsoNormal"><span style="font-size: 9pt; font-family: "><!--[if gte vml 1]><v:shape id="_x0000_i1199" type="#_x0000_t75" alt="" style="'width:441.75pt;height:429pt'"> <v:imagedata src="file:///D:\USERPR~1\sshende\LOCALS~1\Temp\msohtmlclip1\01\clip_image047.gif" href="http://www.roseindia.net/servlets/showparameter2.gif"> </v:shape><![endif]--><!--[if !vml]--><br /><!--[endif]--><o:p></o:p></span></p> </td> </tr> </tbody></table> <p><span style="font-size: 9pt; font-family: "> <o:p></o:p></span></p> <table class="MsoNormalTable" style="width: 150pt;" border="0" cellpadding="0" cellspacing="0" width="200"> <tbody><tr style=""> <td style="padding: 0in;"> <p class="MsoNormal"><span style="font-size: 9pt; font-family: "><!--[if gte vml 1]><v:shape id="_x0000_i1200" type="#_x0000_t75" alt="" style="'width:345.75pt;height:373.5pt'"> <v:imagedata src="file:///D:\USERPR~1\sshende\LOCALS~1\Temp\msohtmlclip1\01\clip_image048.gif" href="http://www.roseindia.net/servlets/showparameter3.gif"> </v:shape><![endif]--><!--[if !vml]--><br /><!--[endif]--><o:p></o:p></span></p> </td> </tr> </tbody></table> <p class="MsoNormal"><span style="font-size: 9pt; font-family: "><o:p> </o:p></span></p> <h1><span style="font-size: 9pt; font-family: ">Inserting Data In Database table using Statement</span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></h1> <p style="text-align: center;" align="center"><span style="font-size: 9pt; font-family: "><script type="text/javascript"> <!-- google_ad_client = "pub-0714075272818912"; google_ad_width = 300; google_ad_height = 250; google_ad_format = "300x250_as"; google_ad_type = "text_image"; google_ad_channel = ""; google_color_border = "FFFFFF"; google_color_bg = "FFFFFF"; google_color_link = "000080"; google_color_text = "000080"; google_color_url = "000080"; //--> </script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script><a href="http://www.roseindia.net/servlets/SessionId.shtml"><span style="text-decoration: none;"><!--[if gte vml 1]><v:shape id="_x0000_i1203" type="#_x0000_t75" alt="" style="'width:9.75pt;height:9.75pt'" button="t"> <v:imagedata src="file:///D:\USERPR~1\sshende\LOCALS~1\Temp\msohtmlclip1\01\clip_image014.gif" href="http://www.roseindia.net/images/previous.gif"> </v:shape><![endif]--><!--[if !vml]--><img src="file:///D:/USERPR%7E1/sshende/LOCALS%7E1/Temp/msohtmlclip1/01/clip_image014.gif" shapes="_x0000_i1203" border="0" width="13" height="13" /><!--[endif]--></span></a> <a href="http://www.roseindia.net/servlets/index.shtml"><span style="text-decoration: none;"><!--[if gte vml 1]><v:shape id="_x0000_i1204" type="#_x0000_t75" alt="" style="'width:1in;height:14.25pt'" button="t"> <v:imagedata src="file:///D:\USERPR~1\sshende\LOCALS~1\Temp\msohtmlclip1\01\clip_image015.gif" href="http://www.roseindia.net/images/bt_home.gif"> </v:shape><![endif]--><!--[if !vml]--><img src="file:///D:/USERPR%7E1/sshende/LOCALS%7E1/Temp/msohtmlclip1/01/clip_image015.gif" shapes="_x0000_i1204" border="0" width="96" height="19" /><!--[endif]--></span></a> <a href="http://www.roseindia.net/servlets/ServletFetchingData.shtml"><span style="text-decoration: none;"><!--[if gte vml 1]><v:shape id="_x0000_i1205" type="#_x0000_t75" alt="" style="'width:9.75pt;height:9.75pt'" button="t"> <v:imagedata src="file:///D:\USERPR~1\sshende\LOCALS~1\Temp\msohtmlclip1\01\clip_image016.gif" href="http://www.roseindia.net/images/next.gif"> </v:shape><![endif]--><!--[if !vml]--><img src="file:///D:/USERPR%7E1/sshende/LOCALS%7E1/Temp/msohtmlclip1/01/clip_image016.gif" shapes="_x0000_i1205" border="0" width="13" height="13" /><!--[endif]--></span></a><o:p></o:p></span></p> <p><span style="font-size: 9pt; font-family: ">In this program we are going to insert the data in the database from our java program in the table stored in the database. </span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <p><span style="font-size: 9pt; font-family: ">To accomplish our goal we first have to make a class named as <b>ServletInsertingData,</b> which must extends the abstract <b>HttpServlet</b> 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 <b>doGet()</b> method that takes two arguments, first is <b><i>HttpServletRequest</i></b> interface and the second one is the <b><i>HttpServletResponse</i></b> interface and this method can throw <b>ServletException.</b></span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <p><span style="font-size: 9pt; font-family: ">Inside this method call the <b>getWriter() </b>method of the <b>PrintWriter</b> 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 <b>forName(),</b> 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 <b>getConnection()</b> of the <b>DriverManager</b> class. This method takes three arguments and returns the <i>Connection</i> 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 <b>createStatement()</b> of the <i>Connection</i> object which will return the <i>Statement</i> 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 <b>executeUpdate()</b> method of the <i>Statement </i>object. This method returns int value. </span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <p><span style="font-size: 9pt; font-family: ">If the record will get inserted in the table then output will show "record has been inserted" otherwise "sorry! Failure".</span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <p><b><span style="font-size: 9pt; font-family: ">The code of the program is given below:</span></b><span style="font-size: 9pt; font-family: "> <o:p></o:p></span></p> <table class="MsoNormalTable" style="background: rgb(255, 255, 204) none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" border="0" cellpadding="0" cellspacing="0"> <tbody><tr style=""> <td style="padding: 2.25pt;" valign="top" nowrap="nowrap"> <p class="MsoNormal"><code><b><span style="font-size: 9pt; font-family: ">import </span></b></code><code><span style="font-size: 9pt; font-family: ">java.io.*;</span></code><span style="font-size: 9pt; font-family: "><br /> <code><b><span style="font-family: ">import </span></b></code><code><span style="font-family: ">java.sql.*;</span></code><br /> <code><b><span style="font-family: ">import </span></b></code><code><span style="font-family: ">javax.servlet.*;</span></code><br /> <code><b><span style="font-family: ">import </span></b></code><code><span style="font-family: ">javax.servlet.http.*;</span></code><br /> <br /> <code><b><span style="font-family: ">public class </span></b></code><code><span style="font-family: ">DataInsertion </span></code><code><b><span style="font-family: ">extends </span></b></code><code><span style="font-family: ">HttpServlet{</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">public void </span></b></code><code><span style="font-family: ">doGet(HttpServletRequest request, HttpServletResponse response)</span></code><code><b><span style="font-family: ">throws </span></b></code><span style="color: black;"><br /> <code><span style="font-family: "> ServletException, IOException{ </span></code></span><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">response.setContentType(</span></code><code><span style="font-family: ">"text/html"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">PrintWriter out = response.getWriter();</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">String url = </span></code><code><span style="font-family: ">"jdbc:mysql://localhost/zulfiqar?user=root&password=admin"</span></code><code><span style="font-family: ">;</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">Connection conn;</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">ResultSet rs;</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">try</span></b></code><code><span style="font-family: ">{</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">Class.forName(</span></code><code><span style="font-family: ">"org.gjt.mm.mysql.Driver"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">conn = DriverManager.getConnection(url);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">Statement statement = conn.createStatement();</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">String query = </span></code><code><span style="font-family: ">"insert into emp_sal values('zulfiqar', 15000)"</span></code><code><span style="font-family: ">;</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">int </span></b></code><code><span style="font-family: ">i = statement.executeUpdate(query);</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">if</span></b></code><code><span style="font-family: ">(i!=</span></code><code><span style="font-family: ">0</span></code><code><span style="font-family: ">){</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">out.println(</span></code><code><span style="font-family: ">"The record has been inserted"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">}</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">else</span></b></code><code><span style="font-family: ">{</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">out.println(</span></code><code><span style="font-family: ">"Sorry! Failure"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">}</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">rs = statement.executeQuery(</span></code><code><span style="font-family: ">"select * from emp_sal"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">while</span></b></code><code><span style="font-family: ">(rs.next()){</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">out.println(</span></code><code><span style="font-family: ">"<p><table>" </span></code><code><span style="font-family: ">+ rs.getString(</span></code><code><span style="font-family: ">1</span></code><code><span style="font-family: ">) + </span></code><code><span style="font-family: ">" " </span></code><code><span style="font-family: ">+ rs.getInt(</span></code><code><span style="font-family: ">2</span></code><code><span style="font-family: ">) + </span></code><code><span style="font-family: ">"</p></table>"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">}</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">rs.close();</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">statement.close();</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">}</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">catch </span></b></code><code><span style="font-family: ">(Exception e){</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">System.out.println(e);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">}</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">}</span></code><br /> <code><span style="font-family: ">}</span></code> <o:p></o:p></span></p> </td> </tr> </tbody></table> <p><b><span style="font-size: 9pt; font-family: ">XML File for this program</span></b><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <table class="MsoNormalTable" style="background: rgb(255, 255, 204) none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" border="0" cellpadding="0" cellspacing="0"> <tbody><tr style=""> <td style="padding: 2.25pt;" valign="top" nowrap="nowrap"> <p class="MsoNormal"><code><span style="font-size: 9pt; font-family: "><?xml version=</span></code><code><span style="font-size: 9pt; font-family: ">"1.0" </span></code><code><span style="font-size: 9pt; font-family: ">encoding=</span></code><code><span style="font-size: 9pt; font-family: ">"ISO-8859-1"</span></code><code><span style="font-size: 9pt; font-family: ">?></span></code><span style="font-size: 9pt; font-family: "><br /> <code><span style="font-family: "><!--<!DOCTYPE web-app</span></code><br /> <code><span style="font-family: "Tahoma","sans-serif"; color: white;"> </span></code><code><span style="font-family: "Tahoma","sans-serif"; color: black;">PUBLIC </span></code><code><span style="font-family: "Tahoma","sans-serif"; color: rgb(42, 0, 255);">"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"</span></code><br /> <code><span style="font-family: "Tahoma","sans-serif"; color: white;"> </span></code><code><span style="font-family: "Tahoma","sans-serif"; color: rgb(42, 0, 255);">"http://java.sun.com/dtd/web-app_2_3.dtd"</span></code><code><span style="font-family: "Tahoma","sans-serif"; color: black;">> --></span></code><br /> <br /> <code><span style="font-family: "><web-app></span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: "><servlet></span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: "><servlet-name>Hello</servlet-name></span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: "><servlet-</span></code><code><b><span style="font-family: ">class</span></b></code><code><span style="font-family: ">>DataInsertion</servlet-</span></code><code><b><span style="font-family: ">class</span></b></code><code><span style="font-family: ">></span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: "></servlet></span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: "><servlet-mapping></span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: "><servlet-name>Hello</servlet-name></span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: "><url-pattern>/DataInsertion</url-pattern></span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: "></servlet-mapping></span></code><br /> <code><span style="font-family: "></web-app></span></code> <o:p></o:p></span></p> </td> </tr> </tbody></table> <p><b><span style="font-size: 9pt; font-family: ">Table in the database before Insertion:</span></b><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <table class="MsoNormalTable" style="background: black none repeat scroll 0% 0%; width: 24%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" border="0" cellpadding="0" width="24%"> <tbody><tr style=""> <td style="padding: 0.75pt; width: 100%;" width="100%"> <p class="MsoNormal"><span style="font-size: 9pt; font-family: ">mysql> select * from emp_sal;<br /> Empty set (0.02 sec)</span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> </td> </tr> </tbody></table> <p><b><span style="font-size: 9pt; font-family: ">The output of the program is given below:</span></b><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <table class="MsoNormalTable" style="width: 53%;" border="1" cellpadding="0" width="53%"> <tbody><tr style=""> <td style="padding: 0.75pt; width: 100%;" width="100%"> <br /></td> </tr> </tbody></table> <p><b><span style="font-size: 9pt; font-family: ">Table in the database after Insertion:</span></b><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <table class="MsoNormalTable" style="background: black none repeat scroll 0% 0%; width: 24%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" border="0" cellpadding="0" width="24%"> <tbody><tr style=""> <td style="padding: 0.75pt; width: 97.14%;" width="97%"> <p class="MsoNormal"><span style="font-size: 9pt; font-family: ">mysql> select * from emp_sal;<br /> +----------+--------+<br /> | EmpName | salary |<br /> +----------+--------+<br /> | zulfiqar | 15000 |<br /> +----------+--------+<br /> 1 row in set (0.02 sec)</span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> </td> </tr> </tbody></table> <h1><span style="font-size: 9pt; font-family: ">Retrieving Data from the table using Statement</span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></h1> <p style="text-align: center;" align="center"><span style="font-size: 9pt; font-family: "><script type="text/javascript"> <!-- google_ad_client = "pub-0714075272818912"; google_ad_width = 300; google_ad_height = 250; google_ad_format = "300x250_as"; google_ad_type = "text_image"; google_ad_channel = ""; google_color_border = "FFFFFF"; google_color_bg = "FFFFFF"; google_color_link = "000080"; google_color_text = "000080"; google_color_url = "000080"; //--> </script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script><a href="http://www.roseindia.net/servlets/ServletInsertingData.shtml"><span style="text-decoration: none;"><!--[if gte vml 1]><v:shape id="_x0000_i1209" type="#_x0000_t75" alt="" style="'width:9.75pt;height:9.75pt'" button="t"> <v:imagedata src="file:///D:\USERPR~1\sshende\LOCALS~1\Temp\msohtmlclip1\01\clip_image014.gif" href="http://www.roseindia.net/images/previous.gif"> </v:shape><![endif]--><!--[if !vml]--><img src="file:///D:/USERPR%7E1/sshende/LOCALS%7E1/Temp/msohtmlclip1/01/clip_image014.gif" shapes="_x0000_i1209" border="0" width="13" height="13" /><!--[endif]--></span></a> <a href="http://www.roseindia.net/servlets/index.shtml"><span style="text-decoration: none;"><!--[if gte vml 1]><v:shape id="_x0000_i1210" type="#_x0000_t75" alt="" style="'width:1in;height:14.25pt'" button="t"> <v:imagedata src="file:///D:\USERPR~1\sshende\LOCALS~1\Temp\msohtmlclip1\01\clip_image015.gif" href="http://www.roseindia.net/images/bt_home.gif"> </v:shape><![endif]--><!--[if !vml]--><img src="file:///D:/USERPR%7E1/sshende/LOCALS%7E1/Temp/msohtmlclip1/01/clip_image015.gif" shapes="_x0000_i1210" border="0" width="96" height="19" /><!--[endif]--></span></a> <a href="http://www.roseindia.net/servlets/ServletInsertingDataUsingUsingHtml.shtml"><span style="text-decoration: none;"><!--[if gte vml 1]><v:shape id="_x0000_i1211" type="#_x0000_t75" alt="" style="'width:9.75pt;height:9.75pt'" button="t"> <v:imagedata src="file:///D:\USERPR~1\sshende\LOCALS~1\Temp\msohtmlclip1\01\clip_image016.gif" href="http://www.roseindia.net/images/next.gif"> </v:shape><![endif]--><!--[if !vml]--><img src="file:///D:/USERPR%7E1/sshende/LOCALS%7E1/Temp/msohtmlclip1/01/clip_image016.gif" shapes="_x0000_i1211" border="0" width="13" height="13" /><!--[endif]--></span></a><o:p></o:p></span></p> <p><span style="font-size: 9pt; font-family: ">In this program we are going to fetch the data from the database in the table from our java program. </span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <p><span style="font-size: 9pt; font-family: ">To accomplish our goal we first have to make a class named as <b>ServletFetchingData</b> which must extends the abstract <b>HttpServlet</b> 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 <b>doGet()</b> method which takes two arguments, first is <b><i>HttpServletRequest</i></b> interface and the second one is the <b><i>HttpServletResponse</i></b> interface and this method can throw <b>ServletException</b>.</span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <p><span style="font-size: 9pt; font-family: ">Inside this method call the <b>getWriter() </b>method of the <b>PrintWriter</b> 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 <b>forName()</b> which is static in nature of the class <b>ClassLoader</b>. It takes one argument which tells about the database driver we are going to use. Now use the static method <b>getConnection()</b> of the <b>DriverManager</b> class. This method takes three arguments and returns the <i>Connection</i> 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 <b>createStatement()</b> of the <i>Connection</i> object which will return the <i>Statement</i> 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 <b>executeQuery()</b> method of <i>Statement</i> object, which returns the <i>ResultSet</i> object. Now the data will be retrieved by using the <b>getString()</b> method of the <i>ResultSet</i> object.</span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <p><b><span style="font-size: 9pt; font-family: ">The code of the program is given below:</span></b><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <table class="MsoNormalTable" style="background: rgb(255, 255, 204) none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" border="0" cellpadding="0" cellspacing="0"> <tbody><tr style=""> <td style="padding: 2.25pt;" valign="top" nowrap="nowrap"> <p class="MsoNormal"><code><b><span style="font-size: 9pt; font-family: ">import </span></b></code><code><span style="font-size: 9pt; font-family: ">java.io.*;</span></code><span style="font-size: 9pt; font-family: "><br /> <code><b><span style="font-family: ">import </span></b></code><code><span style="font-family: ">java.sql.*;</span></code><br /> <code><b><span style="font-family: ">import </span></b></code><code><span style="font-family: ">javax.servlet.*;</span></code><br /> <code><b><span style="font-family: ">import </span></b></code><code><span style="font-family: ">javax.servlet.http.*;</span></code><br /> <br /> <code><b><span style="font-family: ">public class </span></b></code><code><span style="font-family: ">ServletFetchingDataFromDatabase1 </span></code><code><b><span style="font-family: ">extends </span></b></code><code><span style="font-family: ">HttpServlet{</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">public void </span></b></code><code><span style="font-family: ">doGet(HttpServletRequest request, HttpServletResponse response) </span></code><code><b><span style="font-family: ">throws </span></b></code><span style="color: black;"><br /> <code><span style="font-family: "> ServletException, IOException{</span></code></span><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">response.setContentType(</span></code><code><span style="font-family: ">"text/html"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">PrintWriter pw = response.getWriter();</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">String connectionURL = </span></code><code><span style="font-family: ">"jdbc:mysql://localhost/zulfiqar"</span></code><code><span style="font-family: ">;</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">Connection connection=</span></code><code><b><span style="font-family: ">null</span></b></code><code><span style="font-family: ">;</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">try</span></b></code><code><span style="font-family: ">{</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">Class.forName(</span></code><code><span style="font-family: ">"org.gjt.mm.mysql.Driver"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">connection = DriverManager.getConnection(connectionURL, </span></code><code><span style="font-family: ">"root"</span></code><code><span style="font-family: ">, </span></code><code><span style="font-family: ">"admin"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">Statement st = connection.createStatement();</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">ResultSet rs = st.executeQuery(</span></code><code><span style="font-family: ">"Select * from emp_sal"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">while</span></b></code><code><span style="font-family: ">(rs.next()){</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">pw.println(</span></code><code><span style="font-family: ">"EmpName" </span></code><code><span style="font-family: ">+ </span></code><code><span style="font-family: ">" " </span></code><code><span style="font-family: ">+ </span></code><code><span style="font-family: ">"EmpSalary" </span></code><code><span style="font-family: ">+ </span></code><code><span style="font-family: ">"<br />"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">pw.println(rs.getString(</span></code><code><span style="font-family: ">1</span></code><code><span style="font-family: ">) + </span></code><code><span style="font-family: ">" " </span></code><code><span style="font-family: ">+ rs.getString(</span></code><code><span style="font-family: ">2</span></code><code><span style="font-family: ">) + </span></code><code><span style="font-family: ">"<br />"</span></code><code><span style="font-family: ">);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">}</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">}</span></code><br /> <code><span style="font-family: "> </span></code><code><b><span style="font-family: ">catch </span></b></code><code><span style="font-family: ">(Exception e){</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">pw.println(e);</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">}</span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: ">}</span></code><br /> <code><span style="font-family: ">}</span></code> <o:p></o:p></span></p> </td> </tr> </tbody></table> <p><b><span style="font-size: 9pt; font-family: ">XML File for this program:</span></b><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <table class="MsoNormalTable" style="background: rgb(255, 255, 204) none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" border="0" cellpadding="0" cellspacing="0"> <tbody><tr style=""> <td style="padding: 2.25pt;" valign="top" nowrap="nowrap"> <p class="MsoNormal"><code><span style="font-size: 9pt; font-family: "><?xml version=</span></code><code><span style="font-size: 9pt; font-family: ">"1.0" </span></code><code><span style="font-size: 9pt; font-family: ">encoding=</span></code><code><span style="font-size: 9pt; font-family: ">"ISO-8859-1"</span></code><code><span style="font-size: 9pt; font-family: ">?></span></code><span style="font-size: 9pt; font-family: "><br /> <code><span style="font-family: "><!--<!DOCTYPE web-app</span></code><br /> <code><span style="font-family: "Tahoma","sans-serif"; color: white;"> </span></code><code><span style="font-family: "Tahoma","sans-serif"; color: black;">PUBLIC </span></code><code><span style="font-family: "Tahoma","sans-serif"; color: rgb(42, 0, 255);">"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"</span></code><br /> <code><span style="font-family: "Tahoma","sans-serif"; color: white;"> </span></code><code><span style="font-family: "Tahoma","sans-serif"; color: rgb(42, 0, 255);">"http://java.sun.com/dtd/web-app_2_3.dtd"</span></code><code><span style="font-family: "Tahoma","sans-serif"; color: black;">> --></span></code><br /> <br /> <code><span style="font-family: "><web-app></span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: "><servlet></span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: "><servlet-name>Hello</servlet-name></span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: "><servlet-</span></code><code><b><span style="font-family: ">class</span></b></code><code><span style="font-family: ">>ServletFetchingDataFromDatabase</servlet-</span></code><code><b><span style="font-family: ">class</span></b></code><code><span style="font-family: ">></span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: "></servlet></span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: "><servlet-mapping></span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: "><servlet-name>Hello</servlet-name></span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: "><url-pattern>/ServletFetchingDataFromDatabase</url-pattern></span></code><br /> <code><span style="font-family: "> </span></code><code><span style="font-family: "></servlet-mapping></span></code><br /> <code><span style="font-family: "></web-app></span></code> <o:p></o:p></span></p> </td> </tr> </tbody></table> <p><b><span style="font-size: 9pt; font-family: ">The output of the program is given below:</span></b><span style="font-size: 9pt; font-family: "> <o:p></o:p></span></p> <table class="MsoNormalTable" style="width: 60%;" border="1" cellpadding="0" width="60%"> <tbody><tr style=""> <td style="padding: 0.75pt; width: 100%;" width="100%"> <p class="MsoNormal"><span style="font-size: 9pt; font-family: "><!--[if gte vml 1]><v:shape id="_x0000_i1212" type="#_x0000_t75" alt="" style="'width:434.25pt;height:146.25pt'"> <v:imagedata src="file:///D:\USERPR~1\sshende\LOCALS~1\Temp\msohtmlclip1\01\clip_image050.gif" href="http://www.roseindia.net/servlets/FetchingData.gif"> </v:shape><![endif]--><!--[if !vml]--><br /><!--[endif]--><o:p></o:p></span></p> </td> </tr> </tbody></table> <p><b><span style="font-size: 9pt; font-family: ">Table in the database:</span></b><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <table class="MsoNormalTable" style="background: black none repeat scroll 0% 0%; width: 26%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" border="0" cellpadding="0" width="26%"> <tbody><tr style=""> <td style="padding: 0.75pt; width: 100%;" width="100%"> <p class="MsoNormal"><span style="font-size: 9pt; font-family: ">mysql> select * from emp_sal;<br /> +----------+--------+<br /> | EmpName | salary |<br /> +----------+--------+<br /> | zulfiqar | 15000 |<br /> | vinod | 12000 |<br /> +----------+--------+<br /> 2 rows in set (0.00 sec)</span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> </td> </tr> </tbody></table> <p class="MsoNormal"><span style="font-size: 9pt; font-family: "><o:p> </o:p></span></p> <h1><span style="font-size: 9pt; font-family: ">Inserting data from the HTML page to the database</span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></h1> <p style="text-align: center;" align="center"><span style="font-size: 9pt; font-family: "><script type="text/javascript"> <!-- google_ad_client = "pub-0714075272818912"; google_ad_width = 300; google_ad_height = 250; google_ad_format = "300x250_as"; google_ad_type = "text_image"; google_ad_channel = ""; google_color_border = "FFFFFF"; google_color_bg = "FFFFFF"; google_color_link = "000080"; google_color_text = "000080"; google_color_url = "000080"; //--> </script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script><a href="http://www.roseindia.net/servlets/ServletFetchingData.shtml"><span style="text-decoration: none;"><!--[if gte vml 1]><v:shape id="_x0000_i1215" type="#_x0000_t75" alt="" style="'width:9.75pt;height:9.75pt'" button="t"> <v:imagedata src="file:///D:\USERPR~1\sshende\LOCALS~1\Temp\msohtmlclip1\01\clip_image014.gif" href="http://www.roseindia.net/images/previous.gif"> </v:shape><![endif]--><!--[if !vml]--><img src="file:///D:/USERPR%7E1/sshende/LOCALS%7E1/Temp/msohtmlclip1/01/clip_image014.gif" shapes="_x0000_i1215" border="0" width="13" height="13" /><!--[endif]--></span></a> <a href="http://www.roseindia.net/servlets/index.shtml"><span style="text-decoration: none;"><!--[if gte vml 1]><v:shape id="_x0000_i1216" type="#_x0000_t75" alt="" style="'width:1in;height:14.25pt'" button="t"> <v:imagedata src="file:///D:\USERPR~1\sshende\LOCALS~1\Temp\msohtmlclip1\01\clip_image015.gif" href="http://www.roseindia.net/images/bt_home.gif"> </v:shape><![endif]--><!--[if !vml]--><img src="file:///D:/USERPR%7E1/sshende/LOCALS%7E1/Temp/msohtmlclip1/01/clip_image015.gif" shapes="_x0000_i1216" border="0" width="96" height="19" /><!--[endif]--></span></a> <a href="http://www.roseindia.net/servlets/ServletFetchingDataFromDatabase.shtml"><span style="text-decoration: none;"><!--[if gte vml 1]><v:shape id="_x0000_i1217" type="#_x0000_t75" alt="" style="'width:9.75pt;height:9.75pt'" button="t"> <v:imagedata src="file:///D:\USERPR~1\sshende\LOCALS~1\Temp\msohtmlclip1\01\clip_image016.gif" href="http://www.roseindia.net/images/next.gif"> </v:shape><![endif]--><!--[if !vml]--><img src="file:///D:/USERPR%7E1/sshende/LOCALS%7E1/Temp/msohtmlclip1/01/clip_image016.gif" shapes="_x0000_i1217" border="0" width="13" height="13" /><!--[endif]--></span></a><o:p></o:p></span></p> <p><span style="font-size: 9pt; font-family: ">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. </span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <p><span style="font-size: 9pt; font-family: ">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. </span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <p><span style="font-size: 9pt; font-family: ">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 <b>ServletInsertingDataUsingHtml</b> which must extends the abstract <b>HttpServlet</b> 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 <b>doGet()</b> method which takes two arguments, first is <b><i>HttpServletRequest</i></b> interface and the second one is the <b><i>HttpServletResponse</i></b> interface and this method can throw <b>ServletException</b>.</span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <p><span style="font-size: 9pt; font-family: ">Inside this method call the <b>getWriter() </b>method of the <b>PrintWriter</b> 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 <b>forName()</b> 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 <b>getConnection()</b> of the <b>DriverManager</b> class. This method takes three arguments and returns the <i>Connection</i> 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 <b>prepareStatement()</b> of the <i>Connection</i> object which will return the <i>PreparedStatement</i> 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 <b>setString()</b> method of the <i>PreparedStatement</i> object. </span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <p><span style="font-size: 9pt; font-family: ">If the record will get inserted in the table then output will show "record has been inserted" otherwise "sorry! Failure".</span><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <p><b><span style="font-size: 9pt; font-family: ">The code of the program is given below:</span></b><span style="font-size: 9pt; font-family: "><o:p></o:p></span></p> <table class="MsoNormalTable" style="background: rgb(255, 255, 204) none repeat scroll 0% 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial;" border="0" cellpadding="0" cellspacing="0"> <tbody><tr style=""> <td style="padding: 2.25pt;" valign="top" nowrap="nowrap"> <p class="MsoNormal"><code><span style="font-size: 9pt; font-family: "><html></span></code><span style="font-size: 9pt; font-family: "><br /> <br /> <code><span style="font-family: "><head></span></code><br /> <code><span style="font-family: "><title>New Page </span></code><code><span style="font-family: ">1</span></code><code><span style="font-family: ">




"POST" action="/InDataByHtml/ServletInsertingDataUsingHtml">

Enter Name: "text"
name="username" size="20">


Enter Password: "text" name="password" size="20">




"submit" value="Submit" name="B1">





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 values(?,?)");
pst.setString(1,username);
pst.setString(2,password);
int i = pst.executeUpdate();
if(i!=0){
pw.println("
Record has been inserted"
);
}
else{
pw.println("failed to insert the data");
}
}
catch (Exception e){
pw.println(e);
}
}
}

web.xml file for this program:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>ServletInsertingDataUsingHtmlclass>


Zulfiqar
/ServletInsertingDataUsingHtml

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 response) 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)+"
"
);
}
}
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 response)
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_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 + "
"
);
//It shows the name of the columns
pw.println("The name of the columns are:
"
);
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:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>ServletGettingColumnsNamesclass>


Zulfiqar
/ServletGettingColumnsNames

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 response) 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 emp_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:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>ServletGettingNoOfColumnsclass>


Zulfiqar
/ServletGettingNoOfColumns

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 response) 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:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>ServletGettingNoOfRowsclass>


Zulfiqar
/ServletGettingNoOfRows

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 response) 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:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>ServletDeletingRowsFromTableclass>


Zulfiqar
/ServletDeletingRowsFromTable

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 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("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:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>ServletDeletingAllRowsFromTableclass>


Zulfiqar
/ServletDeletingAllRowsFromTable

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 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 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:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>ServletAddingNewColumnclass>


Zulfiqar
/ServletAddingNewColumn

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 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("drop table emp_sal");
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:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>ServletDeletingTableclass>


Zulfiqar
/ServletDeletingTable

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:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>ServletChangingColumnNameclass>


Zulfiqar
/ServletChangingColumnName

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:




"Content-Language" content="en-us">
"Content-Type" content="text/html; charset=windows-1252">
"GENERATOR" content="Microsoft FrontPage 4.0">
"ProgId" content="FrontPage.Editor.Document">
New Page </span></code><code><span style="font-family: ">1</span></code><code><span style="font-family: ">




"POST" action="/sqlStatServlet/ServletUserEnquiryForm">

User Id:


"text" name="userId" size="20">

First Name: "text" name="firstname" size="20">


Surname: "text" name="surname" size="20">


Address1: "text" name="address1" size="20">


Address2: "text" name="address2" size="20">


Town: "text"
name="town" size="20">


City:


"text" name="country" size="20">


Zip code: "text" name="zipcode" size="20">




"submit" value="Submit" name="B1">






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:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>ServletUserEnquiryFormclass>


Zulfiqar
/ServletUserEnquiryForm

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"+"
"
);
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 + "
"
);
}
}
catch (Exception e){
pw.println("The statement is not executed");
}
}
}

web.xml file for this program:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>ServletJoiningTablesclass>


Zulfiqar
/ServletJoiningTables

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"+"
"
);
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 + "
"
);
}
}
catch (Exception e) {
pw.println("The statement is not executed");
}
}
}

web.xml file for this program:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>ServletNaturalJoiningTablesclass>


Zulfiqar
/ServletNaturalJoiningTables

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"+"
"
);
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 + "
"
);
}
}
catch (Exception e) {
pw.println("The statement is not executed");
}
}
}

web.xml file for this program:

"1.0" encoding="ISO-8859-1"?>

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



Zulfiqar
class>ServletNaturalRightJoiningTablesclass>


Zulfiqar
/ServletNaturalRightJoiningTables

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:

Select the list of colors
               
                               
                               
               

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("");
for(int i = 0; i
");
}
pw.println("

");
pw.println("");
pw.println("
");
}

/* (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("");
for(int i= 0; i
");
}
pw.println("");
}
}

/* (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:

0 comments:

Search

My Blog List