Core Java| JSP| Servlets| XML| EJB| JEE5| Web Services| J2ME| Glossary| Questions?

 

 

 

 

 

 

 

 

 

 

 

 

 

Search Tutorials

Latest Questions
Comments
 
Calling Servlet to build a List of data from database and show this on the JSP page in table 
 

In this example we are calling a servet to retrieve all the data from database and then add the data into list. The list is then added to the request object and sen to JSP page. On the JSP page this value is displayed.

 

Calling Servlet to build a List of data from database and show this on the JSP page in table

                          

In this example we are calling a servet to retrieve all the data from database and then add the data into list. The list is then added to the request object and sen to JSP page. On the JSP page this value is displayed.

This example illustrate how a servlet can be used to create a data list from database and how it can be added to the request object and sent to the JSP page. We are using tomcat to run and test the application

In our example "DataServlet.java" is the servlet which is making the connection to the database and retrieves the data from database. After getting the values from database, data is added to the Data List. Then data list is added to the request object and sent to the JSP page. In JSP page the values are displayed using Iterator class object.

Table structure for "message" is :

create table `message` (
`id` double ,
`message` varchar (256)
); 
insert into `message` (`id`, `message`) values('1','amit');
insert into `message` (`id`, `message`) values('2','kumar');
insert into `message` (`id`, `message`) values('3','singh');
insert into `message` (`id`, `message`) values('4','raghuwanshi');
insert into `message` (`id`, `message`) values('5','vineet');
insert into `message` (`id`, `message`) values('6','sandeep');
insert into `message` (`id`, `message`) values('7','suman');
insert into `message` (`id`, `message`) values('8','vineet');

Following code ads the data into request object:

request.setAttribute("data",dataList);

Following code forwards the request to a JSP page:

RequestDispatcher dispatcher = request.getRequestDispatcher(page);
if (dispatcher != null){
dispatcher.forward(request, response);
}

The code for "DataServlet.java" is given as below:

1. DataServlet.java

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

public class DataServlet extends HttpServlet{

  private ServletConfig config;
  //Setting JSP page
  String page="DataPage.jsp";

  public void init(ServletConfig config)
    throws ServletException{
     this.config=config;
     }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
              
throws ServletException,IOException {
    
    PrintWriter out = response.getWriter();
    //Establish connection to MySQL database
    String connectionURL = "jdbc:mysql://192.168.10.59/messagepaging";
    Connection connection = null;
    ResultSet rs;
    response.setContentType("text/html");
    List dataList = new ArrayList()
      try {
       // Load the database driver
      Class.forName("com.mysql.jdbc.Driver");
      // Get a Connection to the database
      connection = DriverManager.getConnection(connectionURL, "root""root")
      //Select the data from the database
      String sql = "select * from message";
      Statement s = connection.createStatement();
      s.executeQuery (sql);
      rs = s.getResultSet();
      while (rs.next ()){
        //Add records into data list
        dataList.add(rs.getInt("id"));
        dataList.add(rs.getString("message"));
      }
      rs.close ();
      s.close ();
      }catch(Exception e){
      System.out.println("Exception is ;"+e);
      }
      request.setAttribute("data",dataList);
      //Disptching request
      RequestDispatcher dispatcher = request.getRequestDispatcher(page);
      if (dispatcher != null){
        dispatcher.forward(request, response);
      
  }
}

Code for "DataPage.jsp" is given as below:

2. DataPage.jsp

<%@page language="java" import="java.util.*" %>
<html>
<head>
<title>Data Page</title>
</head>
<body> 
<table border="1" width="303">
<tr>
<td width="119"><b>ID</b></td>
<td width="168"><b>Message</b></td>
</tr>
<%Iterator itr;%>
<% List data= (List)request.getAttribute("data");
for (itr=data.iterator(); itr.hasNext(); )
{
%>
<tr>
<td width="119"><%=itr.next()%></td>
<td width="168"><%=itr.next()%></td>
</tr>
<%}%>
</table>
</body>
</html>

For servlet to be invoked we have to do following entry in the web.xml file for servlet mapping.

3. web.xml

<!--web.xml code -->

<servlet>
<servlet-name>DataServlet</servlet-name>
<servlet-class>DataServlet</servlet-class>
</servlet>

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

For running the above example we have to follow the following steps:

1.Create and Save "DataServlet.java".
2.Compile that java file and place the DataServlet.class file into classes folder.
3.Do the servlet mapping in the web.xml
4.Create and Save "DataPage.jsp" and place it into appropriate folder.
5.Deploy the Tomcat Server.
6.Type following line in address bar "http://localhost:8080/JSPMultipleForms/DataServlet".

Output:

Download Source Code

                          

» View all related tutorials
Related Tags: java c string jsp ide class strings script object io objects method get char ip using sequence id declaration length

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Training Courses
Tell A Friend
Your Friend Name
Software Solutions
Least Viewed
Most Rated
Recently Viewed
Search Tutorials

 

 
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Flex Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.