+ All Categories
Home > Documents > Servlet Examples

Servlet Examples

Date post: 24-Oct-2014
Category:
Upload: rajib-saha
View: 63 times
Download: 3 times
Share this document with a friend
80
example1-Hello world import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<html>"); pw.println("<head><title>Hello World</title></title>"); pw.println("<body>"); pw.println("<h1>Hello World</h1>"); pw.println("</body></html>"); } } example2- Display date 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("<html>"+"<body><h1>Today Date is</h1>"); pw.println("<b>"+ today+"</b></body>"+ "</html>"); } } 1 1
Transcript
Page 1: Servlet Examples

example1-Hello world

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

public class HelloWorld extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{ response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<html>"); pw.println("<head><title>Hello World</title></title>"); pw.println("<body>"); pw.println("<h1>Hello World</h1>"); pw.println("</body></html>"); }}

example2- Display date

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("<html>"+"<body><h1>Today Date is</h1>"); pw.println("<b>"+ today+"</b></body>"+ "</html>"); }}

example3- Counter

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

public class SimpleCounter extends HttpServlet{

1

1

Page 2: Servlet Examples

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

example4- Holistic counter

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

example5- Init Coutnter

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 =

2

2

Page 3: Servlet Examples

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

example6- Snooping server

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

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

example7- Snooping headers

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

3

3

Page 4: Servlet Examples

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

example8- Dice roller

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

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

example9- Init Parameter

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

4

4

Page 5: Servlet Examples

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

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

<web-app> <servlet> <init-param> <param-name>AdminEmail</param-name> <param-value>[email protected]</param-value> </init-param> <init-param> <param-name>Address</param-name> <param-value>Okhla</param-value> </init-param> <init-param> <param-name>PhoneNo</param-name> <param-value>9911217074</param-value> </init-param> <servlet-name>Zulfiqar</servlet-name> <servlet-class>InitServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/InitServlet</url-pattern> </servlet-mapping>

5

5

Page 6: Servlet Examples

</web-app>

example10- Parameter Passing html

<html><head><title>New Page 1</title></head><body><h2>Login</h2><p>Please enter your username and password</p><form method="GET" action="/htmlform/LoginServlet"> <p> Username <input type="text" name="username" size="20"></p> <p> Password <input type="text" name="password" size="20"></p> <p><input type="submit" value="Submit" name="B1"></p></form><p>&nbsp;</p></body></html>

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

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

example11- Multiple Parameter

Index.html

6

6

Page 7: Servlet Examples

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

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

GetParameterValues.java

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

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

example12- Time updater

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

7

7

Page 8: Servlet Examples

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());}}

example13- Send Redirect

<html><head><title>New Page 1</title></head><body><form method="POST" action="/SendRedirect/SendRedirectServlet"> <p>Enter your name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="username" size="20"></p> <p>Enter your password&nbsp; <input type="text" name="password" size="20"></p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp; <input type="submit" value="Submit" name="B1"></p></form></body></html>

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

public class SendRedirectServlet extends HttpServlet{ protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String name = request.getParameter("username"); String password = request.getParameter("password"); if(name.equals("James")&& password.equals("abc")){ response.sendRedirect("/SendRedirect/ValidUserServlet");

8

8

Page 9: Servlet Examples

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

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

Hidden Form Fields: This is one of the way to support the session tracking. As we know by the name, that in this fields are added to an HTML form which are not displayed in the client's request. The hidden form field are sent back to the server when the form is submitted. In hidden form fields the html entry will be like this : <input type ="hidden" name = "name" value="">. This means that when you submit the form, the specified name and value will be get included in get or post method. In this session ID information would be embedded within the form as a hidden field and submitted with the Http POST command.

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

9

9

Page 10: Servlet Examples

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.

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.

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 Determine whether the Session is New or OldIn this program we are going to make one servlet on session in which we will

check whether the session is new or old.

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

The code of the program is given below:import java.io.*;import javax.servlet.*;import javax.servlet.http.*;

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

10

10

Page 11: Servlet Examples

pw.println("Session already exists"); } }}

In this example we are going to find out whether the session is pre-existing or not.Pre- Existing SessionIn 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"); } }}

11

11

Page 12: Servlet Examples

example15- Last Access Time

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.net.*;import java.util.*;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpSession;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

public class LastAccessTime extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String head; Integer count = new Integer(0); if (session.isNew()) { head = "New Session Value "; } else { head = "Old Session value"; Integer oldcount =(Integer)session.getValue("count"); if (oldcount != null) { count = new Integer(oldcount.intValue() + 1); } }session.putValue("count", count); out.println("<HTML><BODY BGCOLOR=\"#FDF5E6\">\n" + "<H2 ALIGN=\"CENTER\">" + head + "</H2>\n" + "<H4 ALIGN=\"CENTER\">Session Access Time:</H4>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"pink\">\n" + "<TD>Session Creation Time\n" +" <TD>" + new Date(session.getCreationTime()) + "\n" + "<TR BGCOLOR=\"pink\">\n" +" <TD>Last Session Access Time\n" + " <TD>" + new Date(session.getLastAccessedTime()) + "</TABLE>\n" +"</BODY></HTML>"); }public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

12

12

Page 13: Servlet Examples

doGet(request, response); }}

example16- Get Session Id

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

example17- Display Session Value

Sometime while developing web application it is necessary to interact with the different values of the Session object.

Display session value Using Servlet

Sometime while developing web application it is necessary to interact with the different values of the Session object. In this example we will explore the different values of the Session object and then learn how to use it in our programming code.

You will learn how to find all the session related information like:

getId. This method is used to find the identifier of the session which is unique. isNew. This method is used when find, whether session is newly created or preexisted. If session has never seen by user then this method return "true" but if session is preexisted then it return "false". getCreationTime. This method is used to find the creation time of session. To use of this method we can find the following details about session i.e. day, month, date, time, GMT(Greenwich Mean Time) and year will be displayed. getLastAccessedTime. This method is used to find the last accessed time of session. It returns the time, in milliseconds. getMaxInactiveInterval. This method returns the total time, in seconds, during which session remains active if user does not accesses the session for this maximum time

13

13

Page 14: Servlet Examples

interval. After this time the session will be invalidated automatically. A negative value indicates that the session should never timeout.

Here is the sample code for HttpSessionDisplay.java:import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.net.*;import java.util.*;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpSession;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

public class HttpSessionDisplay extends HttpServlet { String head; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); response.setContentType("text/html"); PrintWriter out = response.getWriter(); Integer count = new Integer(0); if (session.isNew()) { head = "New Session Value"; } else { head = "Old Session value"; Integer oldcount =(Integer)session.getValue("count"); if (oldcount != null) { count = new Integer(oldcount.intValue() + 1); } }session.putValue("count", count); out.println("<HTML><BODY BGCOLOR=\"pink\">\n" + "<H2 ALIGN=\"CENTER\">" + head + "</H2>\n" + "<H3 ALIGN=\"CENTER\">Description about Session:</H3>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"voilet\">\n" + "<TH>Information Type<TH>Session Value\n"+ "<TR>\n" + "<TD>ID\n" +"<TD>" + session.getId() + "\n" +"<TR>\n" + " <TD>Session Creation Time\n" +" <TD>" + new Date(session.getCreationTime()) + "\n" + "<TR>\n" +" <TD>Last Session Access Time\n" +" <TD>" +

14

14

Page 15: Servlet Examples

new Date(session.getLastAccessedTime()) + "\n" + "<TR>\n" +" <TD>Number of Previous Session Accesses\n" + "<TD>" + count + "\n" +"</TABLE>\n" +"</BODY></HTML>"); } public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { doGet(request, response); }}

example18- Hit Counter

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

public class CounterServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); response.setContentType("text/html"); PrintWriter out = response.getWriter(); Integer count = new Integer(0); String head; if (session.isNew()) { head = "This is the New Session"; } else { head = "This is the old Session"; Integer oldcount =(Integer)session.getValue("count"); if (oldcount != null) { count = new Integer(oldcount.intValue() + 1); } } session.putValue("count", count); out.println("<HTML><BODY BGCOLOR=\"#FDF5E6\">\n" + "<H2 ALIGN=\"CENTER\">" + head + "</H2>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"#FFAD00\">\n" +" <TH>Information Type<TH>Session Count\n" +"<TR>\n" +" <TD>Total Session Accesses\n" + "<TD>" + count + "\n" + "</TABLE>\n" +"</BODY></HTML>" ); }

15

15

Page 16: Servlet Examples

}

example19- Inserting data

In this program we are going to insert the data in the database from our java program in the table stored in the database.Inserting Data In Database table using Statement

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

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

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

If the record will get inserted in the table then output will show "record has been inserted" otherwise "sorry! Failure".

The code of the program is given below: import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;

public class DataInsertion extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{ response.setContentType("text/html");

16

16

Page 17: Servlet Examples

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

example20- Retrieving data

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

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

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

17

17

Page 18: Servlet Examples

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

The code of the program is given below:import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;

public class ServletFetchingDataFromDatabase1 extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse 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"); Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("Select * from emp_sal"); while(rs.next()){ pw.println("EmpName" + " " + "EmpSalary" + "<br>"); pw.println(rs.getString(1) + " " + rs.getString(2) + "<br>"); } } catch (Exception e){ pw.println(e); } }}

18

18

Page 19: Servlet Examples

example21- Inserting data from html

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.Inserting data from the HTML page to the database

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

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

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

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

If the record will get inserted in the table then output will show "record has been inserted" otherwise "sorry! Failure".

The code of the program is given below:<html><head><title>New Page 1</title></head><body><form method="POST" action="/InDataByHtml/ServletInsertingDataUsingHtml"><!--webbot bot="SaveResults" U-File="fpweb:///_private/form_results.txt"

19

19

Page 20: Servlet Examples

S-Format="TEXT/CSV" S-Label-Fields="TRUE" --> <p>Enter Name:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="username" size="20"></p> <p>Enter Password: <input type="text" name="password" size="20"></p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="submit" value="Submit" name="B1"></p></form></body></html>

ServletInsertingDataUsingHtml.java

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

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

20

20

Page 21: Servlet Examples

} } catch (Exception e){ pw.println(e); } }}

example22- 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.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.*;

21

21

Page 22: Servlet Examples

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)+"<br>"); } } catch (Exception e){ pw.println(e); } pw.println("hello"); }}

example23- Getting Column Names

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 *

22

22

Page 23: Servlet Examples

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 + "<br>"); //It shows the name of the columns pw.println("The name of the columns are: <br>"); for(int i =1; i<=noOfColumns;i++){ String names = rsmd.getColumnName(i); pw.println(names); } } catch(Exception e){ pw.println("The exception is " + e); } }}

example24- Getting Number Column

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

23

23

Page 24: Servlet Examples

catch(Exception e){ pw.println("The exception is " + e); } }}

example25- Getting Number Rows

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

example26- Deleting Rows

24

24

Page 25: Servlet Examples

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

example27- Deleting all rows

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

25

25

Page 26: Servlet Examples

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

example28- Adding New columns

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

26

26

Page 27: Servlet Examples

else{ pw.println("No column has been added"); } } catch(Exception e){ pw.println("The exception is " + e); } }}

example29- Deleting Table

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

27

27

Page 28: Servlet Examples

example30- Changing Column Names

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

example31- insert into statement in sql using servlets

<html><head><meta http-equiv="Content-Language" content="en-us"><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"><meta name="GENERATOR" content="Microsoft FrontPage 4.0"><meta name="ProgId" content="FrontPage.Editor.Document"><title>New Page 1</title></head><body><form method="POST" action="/sqlStatServlet/ServletUserEnquiryForm"> <!--webbot bot="SaveResults" U-File="fpweb:///_private/form_results.txt" S-Format="TEXT/CSV" S-Label-Fields="TRUE" -->

28

28

Page 29: Servlet Examples

<p>User Id:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="userId" size="20"></p> <p>First Name: <input type="text" name="firstname" size="20"></p> <p>Surname: <input type="text" name="surname" size="20"></p> <p>Address1: <input type="text" name="address1" size="20"></p> <p>Address2:<input type="text" name="address2" size="20"></p> <p>Town:<input type="text" name="town" size="20"></p> <p>City: <input type="text" name="country" size="20"></p> <p>Zip code:<input type="text" name="zipcode" size="20"></p> <p> <input type="submit" value="Submit" name="B1"></p></form></body></html>

ServletUserEnquiryForm.java

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

public class ServletUserEnquiryForm extends HttpServlet{ public void init(ServletConfig config) throws ServletException{ super.init(config); } /**Process the HTTP Get request*/ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection=null; ResultSet rs; res.setContentType("text/html"); PrintWriter out = res.getWriter(); //get the variables entered in the form String uId = req.getParameter("userId"); String fname = req.getParameter("firstname"); String sname = req.getParameter("surname"); String address1 = req.getParameter("address1"); String address2 = req.getParameter("address2"); String town = req.getParameter("town"); String county = req.getParameter("country"); String zipcode = req.getParameter("zipcode"); try { // Load the database driver Class.forName("org.gjt.mm.mysql.Driver");

29

29

Page 30: Servlet Examples

// 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); } } }}

example32- join tables mysql using servlets

30

30

Page 31: Servlet Examples

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

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

example33- Natural Left Join using servlets

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

public class ServletNaturalJoiningTables extends HttpServlet{

31

31

Page 32: Servlet Examples

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

example34- Natural Right Join using servlets

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{

32

32

Page 33: Servlet Examples

Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection (connectionURL, "root", "admin"); PreparedStatement pst = connection. prepareStatement("SELECT *FROM "+"emp_details"+" NATURAL RIGHT JOIN "+"emp_sal"); ResultSet rs = pst.executeQuery(); pw.println("userId" + "\t" + "Firstname" + "\t" + "salary"+"<br>"); while(rs.next()){ String id = rs.getString("userId"); String name = rs.getString("Name"); String sal = rs.getString("salary"); pw.println(id + "\t\t" + name + "\t\t" + sal + "<br>"); } } catch (Exception e) { pw.println("The statement is not executed"); } }}

Difference between Servlet 2.4 and Servlet 2.5

33

33

Page 34: Servlet Examples

Features of Servlet 2.4

1. Upgraded supports for Http, J2SE, and J2EE: Servlet 2.4 depends on Http1.1 and J2SE 1.3.

2. Additional ServletRequest methods : In Servlet 2.4 four new methods are added in the ServletRequest

o getRemotePort(): It returns the IP source port of the client.o getLocalName(): It returns the host name on which the request was

recieved.o getLocalAddr(): It returns the IP address on which the request was

recieved. o getLocalPort(): It returns the IP port number.

3. New Support for internationalization and charset choice: For  the support of internationization Servlet 2.4 has added to new methods in the ServletReponse interface.

o setCharacterEncoding(String encoding): The purpose of this method is to set the response's character encoding.  This  method helps us to pass a charset parameter to setContentType(String) or passing a Locale to setLocale(Locale). We can now avoid setting the charset in the setContentType("text/html;charset=UTF-8") as setCharacterEncoding() methods pairs with the preexisting getCharacterEncoding() method to manipulate and view the response's character encoding. 

o getContentType(): It is responsible for returning the response's content type. The content type can be dynamically set with a combination of setContentType(), setLocale(), and setCharacterEncoding() calls, and the method getContentType() provides a way to view the generated type string. 

4. New features has been added in RequestDispatcher: In Servlet 2.4 five new request attributes has been added to provide the extra information during a RequestDispatcher forward() call. This features has been added is Servlet 2.4 to know the true original request URI. The following request attributes are:

o javax.servlet.forward.request_urio javax.servlet.forward.context_patho javax.servlet.forward.servlet_patho javax.servlet.forward.path_infoo javax.servlet.forward.query_string

5. SingleThreadModel interface has been deprecated: In Servlet 2.4 the SingleThreadModel interface has been deprecated. 

6. HttpSession details and interaction with logins has been clarified: The new method HttpSession.logout() has been added in the Servlet 2.4. Now session allows zero or negative values in the <session-timeout> element to indicate

34

34

Page 35: Servlet Examples

sessions should never time out. If the object in the session can't be serialized in a distributed environment then it must throw an IllegalArgumentException. 

7. Welcome file behavior and Classloading has been clarified: In servlet 2.4 welcome file can be servlets. 

8. The web.xml file now uses XML Schema: Version 2.4 servers must still accept the 2.2 and 2.3 deployment descriptor formats, but all new elements are solely specified in Schema.  

Features of Servlet 2.5

This version has been released on September 26, 2005 by the Sun MicroSystems. It is not necessary that all web servers and application servers support the features of Servlet 2.5. Still most of the popular containers like Tomcat 5.5 and JBoss 4.0 still support Servlet 2.4. 

The list of the added features is given below:

1. Dependency on J2SE 5.0: The minimum platform requirement for Servlet2.5 is JDK 1.5. Servet2.5 can't be used in versions below that JDK1.5. All the available features of Jdk1.5 like generics, autoboxing, an improved for loop etc, etc are guaranteed available to Servlet2.5 programmers. 

2. Support For annotations: Annotations provide a mechanism for decorating java code constructs (classes, methods, fields, etc.) with metadata information. Annotations are mark code in such a way that code processors may alter their behavior based on the metadata information. 

3. Several web.xml convenience: Servlet 2.5 introduces several small changes to the web.xml file to make it more convenient to use.  For example while writing a <filter-mapping>, we can now use a asterisk in a <servlet-name> which will represent all servlets as well as Jsp. 

Previously we used to do

<filter-mapping><filter-name>FilterName</filter-name><servlet-name>FilterName</servlet-name></filter-mapping> 

Now,

<filter-mapping><filter-name>FilterName</filter-name><servlet-name>*</servlet-name></filter-mapping>  Previously in <servlet-mapping> or <filter-mapping> there used to be only one

35

35

Page 36: Servlet Examples

<url-pattern>, but now we can have multiple <url-pattern>, like

<servlet-mapping>  <servlet-name>abc</servlet-name>  <url-pattern>/abc/*</url-pattern>  <url-pattern>/abc/*</url-pattern></servlet-mapping>

Apart from these changes, many more facilities added in web.xml. 4. A Handful of removed restrictions: Servlet 2.5 removed a few restrictions around

error handling and session tracking. Now it has removed the restriction that the <error-page> could not call the setStatus() method to alter the error code that triggered them. In session tracking, Servlet 2.5 eased a rule that a servlet called by RequestDispatcher include() couldn't set response headers.

5. Some edge case clarifications: : The servlet2.4 specification says that before calling request.getReader() we  must call request.setCharacterEncoding().  However there is no such clarification given why it is so. It has been described properly in Servlet 2.5.

Get And Post Method of Http

GETThe 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.

POSTThe 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.

example35 - Select Color

36

36

Page 37: Servlet Examples

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

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

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

The code of the program is given below:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Select the list of colors</title></head><body>

<form action = "/ServletProject/ColorPage"><select name = "colors" size = 5 multiple>

<option selected>Green</option><option>Red</option><option>Yellow</option><option>Blue</option><option>Black</option>

</select><input type = "submit" name = "submit">

</form></body></html>

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

/*** Servlet implementation class for Servlet: ColorPage**/

37

37

Page 38: Servlet Examples

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 stubresponse.setContentType("text/html");PrintWriter pw = response.getWriter();HttpSession session = request.getSession();String colors[] = request.getParameterValues("colors");if(session!=null){session.setAttribute("color",colors);session.setMaxInactiveInterval(60);}pw.println("<html><body bgcolor =cyan>");for(int i = 0; i<colors.length; i++){pw.println("The selected colors are" + colors[i]+ "<br>");}pw.println("<form action = /ServletProject/GetColors>");pw.println("<input type = submit name= submit)>");pw.println("</form></body></html>");}

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

38

38

Page 39: Servlet Examples

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 stubresponse.setContentType("text/html");PrintWriter pw = response.getWriter();HttpSession session = request.getSession(false);if(session == null){pw.println("No session is available");pw.println("We are creating a session for you. Creating.....");session = request.getSession();}else{String getColors[] = (String[])session.getAttribute("color");pw.println("<html><body bgcolor = cyan>");for(int i= 0; i<getColors.length;i++){pw.println("The selected colors are " + getColors[i] + "<br>");}pw.println("<html><body>");}}

/* (non-Java-doc)* @see javax.servlet.http.HttpServlet#doPost(

39

39

Page 40: Servlet Examples

HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub} }

example36 - Send Redirect in Servlet

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

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

The output of the program is given below:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Redirecting the page</title></head><body>

<form action = "/ServletProject/SendRedirect" method = "post"><tr>

<td>Enter your name :</td><td><input type = "text" name = "username"></td>

</tr><br><tr>

<td>Enter your password :</td><td><input type = "password" name = "password"></td>

</tr><br><tr>

<td><input type = "submit" name = "submit"></td></tr></form>

40

40

Page 41: Servlet Examples

</body></html>

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

public class SendRedirect extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {public SendRedirect() {super();} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubresponse.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**/

41

41

Page 42: Servlet Examples

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 stubPrintWriter pw = response.getWriter();pw.println("Welcome to roseindia.net<br>");pw.println("how are you");} }

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

42

42

Page 43: Servlet Examples

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

Servlet Context

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

Web application initialization: 1. First of all the web container reads the deployment descriptor file and then creates a name/value pair for each <context-param> tag. 2. After creating the name/value pair it creates a new instance of ServletContext.

43

43

Page 44: Servlet Examples

3. Its the responsibility of the Container to give the reference of the ServletContext to the context init parameters. 4. The servlet and jsp which are part of the same web application can have the access of the ServletContext.

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

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

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

<context-param> <param-name>Email</param-name> <param-value>[email protected]</param-value></context-param>

In the servlet code we will write this as

ServletContext context = getServletContext();pw.println(context.getInitParameter("Email");

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.

44

44

Page 45: Servlet Examples

Example38 - 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)

45

45

Page 46: Servlet Examples

{

}}

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 stubresponse.setContentType("text/html");PrintWriter pw = response.getWriter();pw.println("context attributes set by the listener <br>");Furniture f = (Furniture)getServletContext().getAttribute("furniture");pw.println("The furniture you have selected is :" + f.getTypeSelected());}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub} }

ServletContextAttributeListener

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

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

46

46

Page 47: Servlet Examples

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.

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

47

47

Page 48: Servlet Examples

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.xmlimport javax.servlet.*;import javax.servlet.http.*;

public class MySessionListenerimplements 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

48

48

Page 49: Servlet Examples

HttpSession session = sessionEvent.getSession();// Log a messageSystem.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);}}

Example40- 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.

49

49

Page 50: Servlet Examples

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 SessionAttributeListenerExampleimplements HttpSessionAttributeListener {public void attributeAdded(HttpSessionBindingEvent sessionBindingEvent) {// Get the sessionHttpSession session = sessionBindingEvent.getSession();// Log some informationSystem.out.println("[SessionAttr] "+new java.util.Date()+" Attribute added, session "+session+": "+sessionBindingEvent.getName()+"="+sessionBindingEvent.getValue());} public void attributeRemoved(HttpSessionBindingEvent sessionBindingEvent) {// Get the sessionHttpSession session = sessionBindingEvent.getSession();System.out.println(new java.util.Date()+" Attribute removed, session "+session+": "+sessionBindingEvent.getName());} public void attributeReplaced(HttpSessionBindingEvent sessionBindingEvent) {// Get the sessionHttpSession session = sessionBindingEvent.getSession();// Log some informationSystem.out.println(new java.util.Date()+" Attribute replaced, session "+session+": "+sessionBindingEvent.getName()+"="+sessionBindingEvent.getValue());

50

50

Page 51: Servlet Examples

}}

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

Example41 - 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.

51

51

Page 52: Servlet Examples

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 necessaryHttpSession session = req.getSession();// Add a UserNamesession.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) {

52

52

Page 53: Servlet Examples

context.log("The value bound is " + event.getName());}public void valueUnbound(HttpSessionBindingEvent event) {context.log("The value unbound is " + event.getName());}}

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.

example42 - Inserting Image in MySql Database Table

53

53

Page 54: Servlet Examples

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

54

54

Page 55: Servlet Examples

/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);}}}

example-43- Insert Image into Database Using Servlet

This example illustrate the process of inserting image into database table using Servlet. This type of program is useful in social networking or HR application where it is necessary to save the uploaded photograph of the user. If the image is stored in the database you can easily retrieve using JDBC program. In the next section you will see a program to retrieve the image from database using Servlet. After retrieving the image from database you can display it on the browser.

This type of program is really very useful, which makes your program very attractive.How to Compile Servlet program

1. Save your file ImageInsertInTable.java .

2. Open Command Prompt and set the class path so that it includes the servlet api jar file. The servlet api is available in servlet-api.jar file which you can take from tomcat's lib directory.

3. Map your servlet in web.xml file.

Here is the mapping code that you can put in web.xml file:<servlet><servlet-name>ImageInsertInTable</servlet-name><servlet-class>ImageInsertInTable</servlet-class>

55

55

Page 56: Servlet Examples

</servlet> <servlet-mapping><servlet-name>ImageInsertInTable</servlet-name><url-pattern>/ImageInsertInTable</url-pattern></servlet-mapping>

4. Compile your servlet class file by using javac <file_name.java>.

command prompt> javac ImageInsertInTable.java

5. Move the class file into WEB-INF/classes directory.

6. Run your program on the Browser by url-pattern which define in web.xml file.

You should type http://localhost:8080/MyApplication/ImageInsertInTable in your browser to test the application.

MySql Table Structure:

Here is the table structure used to store the image into database. Please not the filed type used is blog.CREATE TABLE `pictures` (`id` int(11) NOT NULL auto_increment,`image` blob,PRIMARY KEY (`id`))

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

public class ImageInsertInTable extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://192.168.10.59:3306/example"; Connection con=null; try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); con = DriverManager.getConnection (connectionURL, "root", "root"); PreparedStatement ps =

56

56

Page 57: Servlet Examples

con.prepareStatement("INSERT INTO pictures VALUES(?,?)"); File file =new File("C:/apache-tomcat-6.0.16/webapps/CodingDiaryExample/images/5.jpg"); FileInputStream fs = new FileInputStream(file); ps.setInt(1,8); ps.setBinaryStream(2,fs,fs.available()); int i = ps.executeUpdate(); if(i!=0){ pw.println("image inserted successfully"); } else{ pw.println("problem in image insertion"); } } catch (Exception e){ System.out.println(e); } }}

Program description:

The following code is actually used to save the image data into database.

PreparedStatement ps = con.prepareStatement("INSERT INTO pictures VALUES(?,?)"); File file = new File("C:/apache-tomcat-6.0.16/webapps/CodingDiaryExample/images/5.jpg"); FileInputStream fs = new FileInputStream(file); ps.setInt(1,8); ps.setBinaryStream(2,fs,fs.available()); int i = ps.executeUpdate();

example44- Retrieve image from database using Servlet

In this example we will show you how to develop a Servlet that connects to the MySQL database and retrieves the image from the table. After completing this tutorial you will be able to develop program for your java based applications that retrieves the image from database. You can use this type of program to retrieve the employee image in HR application. In case social networking site you can save the user's photo in database and then retrieve the photo for display.

Our Servlet connects to the MySQL database and then retrieves the saved password. Here is the structure of MySQL table used in this program.

57

57

Page 58: Servlet Examples

In this example the Image field will be blob and access by image id.How to Compile Servlet program

1. Save your file same name as class name.

2. Map your servlet in web.xml file.

3. Open Command Prompt and give appropriate path of your class file.

4. Compile your servlet class file by using javac file_name.java .

5. Run your program on the Browser by url-pattern which is define in web.xml file.

MySql Table Structure:CREATE TABLE `pictures` (`id` int(11) NOT NULL auto_increment,`image` blob,PRIMARY KEY (`id`))

Here is the Example: import java.sql.*;import java.io.*;import javax.servlet.*;import javax.servlet.http.*;

public class DisplayImage extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ //PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://192.168.10.59:3306/example"; java.sql.Connection con=null; try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); con=DriverManager.getConnection(connectionURL,"root","root"); Statement st1=con.createStatement(); ResultSet rs1 = st1.executeQuery("select image from"+ " pictures where id='5'"); String imgLen=""; if(rs1.next()){ imgLen = rs1.getString(1); System.out.println(imgLen.length()); } rs1 = st1.executeQuery ("select image from pictures where id='5'"); if(rs1.next()){

58

58

Page 59: Servlet Examples

int len = imgLen.length(); byte [] rb = new byte[len]; InputStream readImg = rs1.getBinaryStream(1); int index=readImg.read(rb, 0, len); System.out.println("index"+index); st1.close(); response.reset(); response.setContentType("image/jpg"); response.getOutputStream().write(rb,0,len); response.getOutputStream().flush(); } } catch (Exception e){ e.printStackTrace(); } }}

59

59


Recommended