Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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>"); } }
example3- Counter
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SimpleCounter extends HttpServlet{ int counter = 0; 1
2 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); } }
3 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"); } }
4 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); } } } } }
5 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>zulfiqar_mca@yahoo.co.in</param-value> </init-param> <init-param> <param-name>Address</param-name> <param-value>Okhla</param-value> </init-param> <init-param> <param-name>PhoneNo</param-name> <param-value>9911217074</param-value> </init-param> <servlet-name>Zulfiqar</servlet-name> <servlet-class>InitServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Zulfiqar</servlet-name> <url-pattern>/InitServlet</url-pattern> </servlet-mapping> </web-app>
<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]); } } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); response.addHeader("Refresh", "1"); pw.println(new Date().toString()); } }
9 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"); } }
10 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 Old In this program we are going to make one servlet on session in which we will check whether the session is new or old. To make this program firstly we need to make one class named CheckingTheSession. Inside the doGet() method, which takes two objects one of request and second of response. Inside this method call the method getWriter() of the response object. Use getSession() of the request object, which returns the HttpSession object. Now by using the HttpSession we can find out whether the session is new or old. The code of the program is given below: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class CheckingTheSession extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("Checking whether the session is new or old<br>"); HttpSession session = request.getSession(); if(session.isNew()){ pw.println("You have created a new session"); } else{
10
11 pw.println("Session already exists"); } } } In this example we are going to find out whether the session is pre-existing or not. Pre- Existing Session In this example we are going to find out whether the session is pre-existing or not. Consider a situation where servlet want to use only a existing session. It is not always a good idea to create a new session. To perform this work we have one overloaded method getSession(boolean) of the request object. If we don't want to create a new session then we should use getSession(false). In the example below we have used the method getSession(false) which will test whether the session is null or not. If there will be no session then the new session will be created by the method getSession(). The code of the program is given below: PreExistingSessionServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class PreExistingSessionServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("Testing The Session : "); HttpSession session = request.getSession(false); if(session==null){ pw.println("There is no session"); pw.println("Can we create a session for you. Creating........."); session = request.getSession(); } else{ pw.println("Session already exists"); } } }
11
12
13 doGet(request, response); } }
13
14 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 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>" +
14
15 new Date(session.getCreationTime()) + "\n" + "<TR>\n" +" <TD>Last Session Access Time\n" +" <TD>" + 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); } }
16 +"</BODY></HTML>" ); } }
17 ServletException, IOException{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String url = "jdbc:mysql://localhost/zulfiqar?user=root&password=admin"; Connection conn; ResultSet rs; try{ Class.forName("org.gjt.mm.mysql.Driver"); conn = DriverManager.getConnection(url); Statement statement = conn.createStatement(); String query = "insert into emp_sal values('zulfiqar', 15000)"; int i = statement.executeUpdate(query); if(i!=0){ out.println("The record has been inserted"); } else{ out.println("Sorry! Failure"); } rs = statement.executeQuery("select * from emp_sal"); while(rs.next()){ out.println("<p><table>" + rs.getString(1) + " " + rs.getInt(2) + "</p></table>"); } rs.close(); statement.close(); } catch (Exception e){ System.out.println(e); } } }
18 HttpServletRequest interface and the second one is the HttpServletResponse interface and this method can throw ServletException. Inside this method call the getWriter() method of the PrintWriter class. We can retrieve the data from the database only and only if there is a connectivity between our database and the java program. To establish the connection between our database and the java program we firstly need to call the method forName() which is static in nature of the class ClassLoader. It takes one argument which tells about the database driver we are going to use. Now use the static method getConnection() of the DriverManager class. This method takes three arguments and returns the Connection object. SQL statements are executed and results are returned within the context of a connection. Now your connection has been established. Now use the method createStatement() of the Connection object which will return the Statement object. This object is used for executing a static SQL statement and obtaining the results produced by it. As we need to retrieve the data from the table so we need to write a query to select all the records from the table. This query will be passed in the executeQuery() method of Statement object, which returns the ResultSet object. Now the data will be retrieved by using the getString() method of the ResultSet object. The code of the program is given below: import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletFetchingDataFromDatabase1 extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse 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
19 }
20 <!--webbot bot="SaveResults" U-File="fpweb:///_private/form_results.txt" S-Format="TEXT/CSV" S-Label-Fields="TRUE" --> <p>Enter Name: <input type="text" name="username" size="20"></p> <p>Enter Password: <input type="text" name="password" size="20"></p> <p> <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{
20
22
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"); } }
23 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 + "<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); } } }
25
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); } } }
26 PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost/zulfiqar"; Connection connection; try{ Class.forName("org.gjt.mm.mysql.Driver"); connection = DriverManager.getConnection(connectionURL, "root", "admin"); PreparedStatement pst = connection.prepareStatement("delete from emp_sal"); int i = pst.executeUpdate(); if (i==0){ pw.println("All rows are deleted"); } else{ pw.println("no rows has been deleted"); } } catch(Exception e){ pw.println("The exception is " + e); } } }
27 } else{ pw.println("No column has been added"); } } catch(Exception e){ pw.println("The exception is " + e); } } }
27
28
28
29 <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"); // Get a Connection to the database
29
30 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); } } } }
30
31 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"); } } }
32 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"); } } }
33 (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"); } } }
34 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. 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_uri o javax.servlet.forward.context_path o javax.servlet.forward.servlet_path o javax.servlet.forward.path_info o javax.servlet.forward.query_string
o
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 sessions should never time out.
34
35 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 <url-pattern>, but now we can have multiple <url-pattern>, like
35
36
<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.
36
37 In this program we are going to selected the various color and on the basis of the selection the output will be displayed to the user. To make this program firstly we need to make one html page. Inside the page we will have one select option in which we will have our colors. We will also have a submit, clicking on which the values we have entered will be transferred to the server. On the server we will create a session. The values which we have entered in the html form will be retrieved by the getParameterValues() of the request object. It returns the array of String. We will check the condition if there is any session available or not. If yes then we will set the attribute by using the setAttribute() method of the HttpSession object. The attribute we have set will be retrieved by the getAttribute method of the HttpSession object in the next page and the value will be displayed on the browser by the PrintWriter object. The code of the program is given below: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Select the list of colors</title> </head> <body> <form action = "/ServletProject/ColorPage"> <select name = "colors" size = 5 multiple> <option selected>Green</option> <option>Red</option> <option>Yellow</option> <option>Blue</option> <option>Black</option> </select> <input type = "submit" name = "submit"> </form> </body> </html> import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** * Servlet implementation class for Servlet: ColorPage * */ public class ColorPage extends javax.servlet.http.HttpServlet implements
37
38 javax.servlet.Servlet { /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#HttpServlet() */ public ColorPage() { super(); } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doGet (HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html"); PrintWriter pw = response.getWriter(); HttpSession session = request.getSession(); String colors[] = request.getParameterValues("colors"); if(session!=null) { session.setAttribute("color",colors); session.setMaxInactiveInterval(60); } pw.println("<html><body bgcolor =cyan>"); for(int i = 0; i<colors.length; i++) { pw.println("The selected colors are" + colors[i]+ "<br>"); } pw.println("<form action = /ServletProject/GetColors>"); pw.println("<input type = submit name= submit)>"); pw.println("</form></body></html>"); } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } } import java.io.*;
38
39 import javax.servlet.*; import javax.servlet.http.*; /** * Servlet implementation class for Servlet: GetColors * */ public class GetColors extends HttpServlet { /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#HttpServlet() */ public GetColors() { super(); } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doGet( HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html"); PrintWriter pw = response.getWriter(); HttpSession session = request.getSession(false); if(session == null) { pw.println("No session is available"); pw.println("We are creating a session for you. Creating....."); session = request.getSession(); } else { String getColors[] = (String[])session.getAttribute("color"); pw.println("<html><body bgcolor = cyan>"); for(int i= 0; i<getColors.length;i++) { pw.println("The selected colors are " + getColors[i] + "<br>"); } pw.println("<html><body>"); } } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doPost( HttpServletRequest request, HttpServletResponse response)
39
40 */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
40
41 </html> import java.io.*; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class SendRedirect extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { public SendRedirect() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html"); PrintWriter pw = response.getWriter(); String name = request.getParameter("username"); String password = request.getParameter("password"); if(name.equals("James")&& password.equals("abc")) { response.sendRedirect("/ServletProject/ValidUser"); } else { pw.println("u r not a valid user"); } } } import java.io.*; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class for Servlet: ValidUser * */ public class ValidUser extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { /* (non-Java-doc)
41
42 * @see javax.servlet.http.HttpServlet#HttpServlet() */ public ValidUser() { super(); } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /* (non-Java-doc) * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter pw = response.getWriter(); pw.println("Welcome to roseindia.net<br>"); pw.println("how are you"); } }
43
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. 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.
43
44 The Context init parameters are available to the entire web application not just to the single servlet like servlet init parameters. How can we do the mapping of the Context init parameters in web.xml <servlet> <servlet-name>Mapping</servlet-name> <servlet-class>ContextMapping</servlet-class> </servlet> <context-param> <param-name>Email</param-name> <param-value>admin@roseindia.net</param-value> </context-param> In the servlet code we will write this as ServletContext context = getServletContext(); pw.println(context.getInitParameter("Email"); 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
45 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
46
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ListenerTester extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { public ListenerTester() { super(); } public void doGet(HttpServletRequest request, } HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("context attributes set by the listener <br>"); Furniture f = (Furniture)getServletContext().getAttribute("furniture"); pw.println("The furniture you have selected is :" + f.getTypeSelected()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } } ServletContextAttributeListener As we know that the javax.servlet.ServletContext interface used to represents a Servlet's view of the web application it belongs to. All the servlets in an application can access the SevletContext. It means that we keep such information in the servlet context which are common to all the servlets. The elements of the ServletContext are stored in web.xml file. Whenever the container gets start it reads the web.xml file. Occurrence of <context-param> tag should appear before the Servlet tags. ServletContext is a interface which helps us to communicate with the servlet container. There is only one ServletContext for the entire web application and the components of the web application can share it. The information in the ServletContext will be common to all the components. Remember that each servlet will have its own ServletConfig. The ServetContext is created by the container when the web application is deployed and after that only the context is available to each servlet in the web application. The listener ServletContextAttributeListener is an interface and extends the java.util.EventListener class. This listener come into existence when this interface receives
46
47 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 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.
47
48 Listeners listen the events. Whenever any event occurs it is listened by the listener. The listener will be controller by the web servers. HttpSessionListener is an interface which extends java.util.EventListener class. The main purpose of this listener is to notify whenever there is a change in the list of active sessions in a web application This interface has two methods: 1. sessionCreated(HttpSessionEvent event): It will notify when the session is created. 2. sessionDestroyed(HttpSessionEvent event): It will notify when the session gets invalidated. In the above methods we can see that we have used HttpSessionEvent as the parameter of both the methods. This class has only one method getSession() which returns the current session. The code of the program is given below: Make the entry of this file in the deployment descriptor file that is web.xml import javax.servlet.*; import javax.servlet.http.*; public class MySessionListener implements HttpSessionListener { public MySessionListener() { } public void sessionCreated(HttpSessionEvent sessionEvent) { // Get the session HttpSession session = sessionEvent.getSession(); try { System.out.println("Session created: "+session); session.setAttribute("foo","bar"); } catch (Exception e) { System.out.println("Error in setting session attribute: " }+ e.getMessage()); } } public void sessionDestroyed(HttpSessionEvent sessionEvent) { // Get the session that was invalidated HttpSession session = sessionEvent.getSession(); // Log a message System.out.println("Session invalidated: "+session); System.out.println("The name is: " + session.getAttribute("foo")); }
48
49 } 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); } }
49
50 In the above methods you can see that we have used HttpSessionBindingEvent class as a parameter to the above methods. This class is a event class which is used for notifications when the changes are made to the attributes of in a session. The class HttpSessionBindingEvent has two methods: 1. getName() : This method returns the name of the attribute that has been change in the session. 2. getValue(): This method will return the value of the attribute that has been added, removed or replaced by other attribute. 3. getSession(): This method will return the session that has been changed. The code of the program is given below: import javax.servlet.*; import javax.servlet.http.*; public class SessionAttributeListenerExample implements HttpSessionAttributeListener { public void attributeAdded(HttpSessionBindingEvent sessionBindingEvent) { // Get the session HttpSession session = sessionBindingEvent.getSession(); // Log some information System.out.println("[SessionAttr] "+new java.util.Date()+ " Attribute added, session "+session+": " +sessionBindingEvent.getName()+"="+ sessionBindingEvent.getValue()); } public void attributeRemoved(HttpSessionBindingEvent sessionBindingEvent) { // Get the session HttpSession session = sessionBindingEvent.getSession(); System.out.println(new java.util.Date()+" Attribute removed, session "+session+": "+sessionBindingEvent.getName()); } public void attributeReplaced(HttpSessionBindingEvent sessionBindingEvent) { // Get the session HttpSession session = sessionBindingEvent.getSession(); // Log some information System.out.println(new java.util.Date()+" Attribute replaced, session "+session+": "+sessionBindingEvent .getName()+"="+sessionBindingEvent.getValue()); } }
50
51
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"); } }
51
52 1. valueBound(HttpSessionBindingEvent event): It notifies the object that is being bound to a session and is responsible for identifying the session. 2. valueUnBound(HttpSessionBindingEvent event): It notifies the object that is being unbound from a session and is responsible for identifying the session. In the above method we can see that we have used the class HttpSessionBindingEvent as a argument to the methods. The object is notified by an HttpSessionBindingEvent object This class has two methods: 1. getName(): It returns the name with which the object is bound or unbound from the session. 2. getSession(): This method returns the session to or from which the object is bound or unbound. The code of the program is given below: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SessionBindingListenerExample extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); // Get the current session object, create one if necessary HttpSession session = req.getSession(); // Add a UserName session.setAttribute("name", new UserName(getServletContext())); out.println("This is the example of HttpSessionBindingListener"); } } import javax.servlet.*; import javax.servlet.http.*; public class UserName implements HttpSessionBindingListener { ServletContext context; public UserName(ServletContext context){ this.context = context; } public void valueBound(HttpSessionBindingEvent event) { context.log("The value bound is " + event.getName()); }
52
53 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.
53
54 To get the program working we need to use a doGet() method to write our business logic as it is server side programming so all the processing will be done by the container. First of all make a class named JdbcInsertImage, the name of the class should be such that the person can understand what the program is going to do. This class must extend the HttpServlet class which is an abstract method. Now inside the doGet() method call the method getWriter() of the class PrintWriter. To insert a image from our java program we need to make a connection between our java class and the MySql database which we are using. After the connection establishment we will pass a insertion query for the image in the prepareStatement() method of the Connection object which returns the PreparedStatement object. Note that the data type for the image we have used is mediumblob. It is case sensitive. As we have to insert an image file in our database so there is a need to use a File class of the java.io package. In the constructor of the File class pass the path of the file. To read the image file we will use FileInputStream class. To set the image in the database use the method setBinaryStream() of the PreparedStatement interface. If the image will be inserted in the database you will get the message "image has been inserted" otherwise "image is not inserted". The code of the program is given below: import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class JdbcInsertImage extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter pw = response.getWriter(); String connectionURL = "jdbc:mysql://localhost:3306/roseindia"; java.sql.Connection connection=null; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); connection = DriverManager.getConnection(connectionURL, "root", "root"); PreparedStatement pst = connection.prepareStatement ("insert into image values(?,?)"); File file = new File("C:/apache-tomcat-5.5.20/webapps /mywork/grad_sm.gif"); FileInputStream fis = new FileInputStream(file); pst.setBinaryStream(1,fis,fis.available()); pst.setString(2, "Tim"); int i = pst.executeUpdate();
54
55 if(i!=0) { pw.println("image has been inserted"); } else { pw.println("image is not inserted"); } } catch (Exception e) { System.out.println(e); } } }
55
56 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.java import 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 = 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());
56
57 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-tomcat6.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();
58
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()){ 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");
58
59