Want to display results from database pagewise ?

I have 500 records in the sql server 2000 then i query and retrieve them in a resultsets. and then i want to display 10 records per page having the facility to navigate to the Previous and Next Record also going to first and the last record.
like we are using when we navigate from this forum
FIRST PREVIOUS 1 2 3 4 5 6 7 8 9 10 NEXT LAST
secondly if their is a possiblity their should be a search page to to specific page like this
Go To this Page (Textfield)
third thing when i am on first record the it shouldnt show PREVIOUS button and when it is in the last it should not show NEXT.
this thing should be done by Using JSP , Servelets and Beans...
and PLEASE DONT SAY THAT IT HAS ALREADY BEEN ASK IF SO TELL ME THE LINK BECAUSE I CANT FIND ANYWHERE IN THE FORUM SO PLEASE TRY TO PROVIDE THE SOURCODE OR ATLEAST A REFERENCE FOR IT.

for your task there is nice keyword in MySQL:
LIMIT [offset,] rows
maybe MSSQL has something similar...
though i haven't seen such a keyword in oracle nor postgre... nor mssql (but i haven't looked for it from there...)
one way would be to skip first X results in resultset... in PyML i have used method .skip(count) for skiping count rows, but i'm not sure that in java there is equivalent for that, so you might have to just call ResultSet.next() for count times, and then ten more times to get desired data for your page.

Similar Messages

  • How to display result of database query in JFrame?

    How to display result of oracle database query in JFrame?
    This is part of my code:
    String username, password;
              DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
              OracleConnection conn = DriverManager.getConnection(String url, String username, String password);
    Statement s= conn.createStatement();
    ResultSet q= s.executeQuery("SELECT A, B, C FROM TABLE X");
    Forget what url, username & password are. Is there any problem with my code?
    What should be next if I want to display result of the query in a table in JFrame?Thx !

    How to create JTable with unknown no. of rows? How to get no. of rows of a query?
    I saw the demo of creating JTable on java.sun.com but the the table has a certain no. of rows which is not applicable to my case.
    Suppose the result of query is a table with 3 attributes so there are 3 columns in the table.
    R contains the result of the query.
    Should it be something like this if I want to create JTable of the query?
    How to make n rows of {R.getString(1),R.getString(2),R.getString(3)};?
    public SimpleTableDemo() {
    super(new GridLayout(1,0));
    String[] columnNames = {"A",
    "B",
    "C",
    while (R.next())
    // content of a row
    Object[][] data = {R.getString(1),R.getString(2),R.getString(3)};
    I can't run it because I still can't debug my code which is said before.
    Thx!

  • How to display items from database using catagorylookupdroplet

    Hi everyone,
    i want to know how to display items from database using catagorylookup droplet. if anybody have any code snippet please share it.
    Thanks in advance,

    <dsp:droplet name=".................../CategoryLookup">
         <dsp:param name="id" param="itemId"/>
         <dsp:oparam name="output">
              <dsp:valueof param="element.displayName"/>
                   <%-- This is show the Child Category --%>
                   <dsp:droplet name="......................./ForEach">
                   <dsp:param name="array" param="element.childCategories"/>
                   <dsp:oparam name="outputStart">Child Categories</dsp:oparam>
                   <dsp:oparam name="output">
                        <dsp:a href="">//bydefault it will take its own file's name
                             <dsp:param name="itemId" param="element.repositoryId"/>                                                                                          <dsp:valueof param="element.displayName"/>
                        </dsp:a>
                   </dsp:oparam>                                             
                   </dsp:droplet>
                   <%-- This is show the Child Product --%>          
                   <dsp:droplet name=".............../ForEach">
                        <dsp:param name="array" param="element.childProducts"/>
                        <dsp:oparam name="outputStart">Child Products</dsp:oparam>
                                  <dsp:oparam name="output">
                                       <dsp:droplet name="................/ProductLookup">
                                            <dsp:param name="id" param="itemId"/>
                                            <dsp:param name="elementName" value="Prod"/>
                                            <dsp:oparam name="output">
                                                 <dsp:getvalueof id="img102" param="Prod.smallImage.url" idtype="java.lang.String">
                                                      <dsp:img height="250" width="250" src="<%=img102%>"/>
                                                 </dsp:getvalueof>
                                            </dsp:oparam>
                                       </dsp:droplet>
                                       <dsp:a href="productView.jsp">
                                            <dsp:param name="itemId" param="element.repositoryId"/>
                                            <dsp:valueof param="element.displayName"/>
                                       </dsp:a>
    Hope this helps.
    -RMishra

  • Help with displaying info from database+asp

    How can I display info from a database so that it is
    formatted into rows in a table
    here is an example of what I would like
    http://www.westerveltcollege.com/new/programs/bus_admin_computers.html
    (it is the section that show the course content)
    I know it has been code into the table but how to do this
    dymanically
    hope that makes sense to someone ;)

    To do it properly you would set up two tables. The first
    would contain the
    topics and be something like this
    topicID
    topicName
    Then you would have a second table that would hold the
    content like this
    contentID
    contentName
    topicID
    The last field links this table to the topic.
    To display them you would link the topics into a master list,
    and then pass
    the topicID to the page displaying the content and use the
    topicID as a
    filter on the content table.
    Paul Whitham
    Certified Dreamweaver MX2004 Professional
    Adobe Community Expert - Dreamweaver
    Valleybiz Internet Design
    www.valleybiz.net
    "jnc1965" <[email protected]> wrote in
    message
    news:eeot1q$db0$[email protected]..
    > nice one thanks
    >
    > now one more quetion
    > how do I set up the info in the database
    > I have serveral page for different topics and each page
    has a table like
    > mentioned above
    > I dont want to make a different colunm for each for the
    course contents
    > I would like to build one table and have each subject's
    course content in
    > a
    > column but how would I do this?
    > and still have appear like the example
    >

  • Display Images from Database

    Hi all,
    I require to display images stored in database along with textual description of it on a JSP.
    The image file should not be stored intermediately on file system (i.e w/o using img HTML tag)
    It is a typical shopping cart appln. where images are fetched from database and the associated description is displayed along side.
    Please note that it is the case of Mixed content types(text and binary data).
    Thanks and Regards

    Like "Breakfast" said, you can do this with a servlet that retrieves your images from a database....
    if you create a servlet to do this, you would have a generic servlet which retrieves a picture from a database based upon a key which could be a picture name or number.
    Lets say the file is out there in the database as a BLOB or Binary Image... you could have this kind of code in the doPost(HttpRequest req, HttpResponse res) or doService(HttpRequest req, HttpResponse res) method.
    The table holding the image has at least two columns one called IMAGE which holds the binary image and the other called FILENAME. If the connection to the DB is already open, you do something like this.
    String fileToGet = (String)req.getParameter("FILENAME");
    rs = conn.createStatement().executeQuery("select from IMAGE_TABLE where FILENAME='" + fileToGet + "'");
    if(rs.next())
    InputStream in = rs.getBinaryStream("IMAGE");
    res.setContentType("image/jpg"); // or whatever type of file it is.
    ServletOutputStream sout = res.getOutputStream();
    int c;
    while((c = in.read()) != -1)
    sout.write(c);
    in.close();
    sout.close();
    This should write your image to the response output of the servlet.
    Now, where you want your image, you put.
    <img src="/servlet/ImageServlet?FILENAME="thefileIwant">
    This should do what you want... Use your favorite pipe copy method to get the input stream to the output stream. If you are worried about overhead and scaling like "breakfast" said (it CAN be a problem in high access sites), then you can add an image caching scheme and get really complex.... But this is a rough idea on what to do.
    Hope this helps.
    Stephen McConnell

  • How to display data from Database individually??? Anyone can help ?

    HI,
    i i had select a row of data from database using ,
    /* Query * From Table RESOURCEORDER where po = selected no and project = selected project */
         public ResultSet getAllData() throws SQLException
         getConnection();
         Statement stmt = conn.createStatement();
         ResultSet rs = stmt.executeQuery("SELECT * FROM RESOURCEORDER WHERE PROJECT = '" + getSelProject() + "' and PURCHASEORDERNO = '" + getPo() + "'" );
         return rs;
    After that , how do i display the data individually ?
    Eg select data is ('projectA','7891203-1', '10-4-2005','lcd',2000,'121-45217-8','electrical','pending','donwong')
    i want to display them individually, like this in a page
    Projectname: /* should display the Project A*/
    P.O no:
    Date:
    Order:
    Cost:
    Acc no:
    Type:
    status:
    Orderedby:
    Can anyone help ? cos i'm new to JSP ......Thanks alot!!!!!
    Regards,
    khim

    I assume PO being a unique key, will always return 1 row from db.
    public String[] getAllData() throws Exception
    getConnection();
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT * FROM RESOURCEORDER WHERE PROJECT = '" + getSelProject() + "' and PURCHASEORDERNO = '" + getPo() + "'" );
    String [] returnValue = new String[9];
    while(rs.next())
    returnValue[1] = rs.getString("colname");
    returnValue[2] = rs.getString("colname");
    ///and so on
    return returnValue;
    }Once you get that you could individually view it by setting a loop to run through the returned array.
    Hope it helps

  • Extract results from database

    I want to be able to re-create a test report from the results database and do statistical analysis on the results of specific tests. Are there any querries or other database tools that have already been developed for this?

    Hi Gumby,
    As far I know there aren't any tools developed specifically for this kind of a task. However depending on the environment you're using there will probably be tools developed for easily retrieving information from databases.
    In TestStand we have SQL step types that allow you to easily retrieve data from databases. There are two examples that ship with TestStand I would suggest looking at in addition to the help for these step types.
    C:\Program Files\National Instruments\TestStand 3.1\Examples\Database
    (This path will vary depending on the version of TestStand and your installation directory.)
    If you're using LabVIEW or LabWindows/CVI we have special tools developed to simplify communicating to databases.
    c.vp?cid=6429〈=US>LabVIEW Database Connectivity Toolkit
    NI LabWindows/CVI Enterprise Connectivity Toolset
    There are also lots of examples available by searching our website.
    If you're using another environment there are probably tools available as well, I just don't know enough to recommend any.
    I hope this helps!
    Regards,
    Sarah Miracle
    National Instruments

  • Displaying image from database in report

    I need to include a picture (company logo) in numerous reports. This logo will be stored in an MS SQL Image field in a table (this bit I have already sorted out).
    What I'm wondering is, what is the best way to retrieve this image from the database? Do I just include it in the view the report runs off? I'm hesitant to do this, as the view may return back hundreds of records, which means (I think) it will be sending the image along with it hundreds in time.
    In short:
    1) What is the best way to pass an image to a report.
    2) If I include the Image field in a view which returns back hundreds of line, will the image be returned also hundreds of time, causing network congestion/performance issues?
    3) If so (2), is there a way of sending the image only once, no matter how many rows are in the returned view?
    Thanks.

    Hi Shanon,
    We can display the image by making it a local copy on your machine.
    If it is possible to  get the image saved on local copy.
    If we place the image in detail section then it would return one record.
    As the image is from Database, so it would hit the database very time when you refresh the report and place it in Report Header or report fotter.
    So, place your logo as an OLE object in report and would reduce processing time.
    Regards,
    Naveen.

  • Displaying image from database table.

    Hi All,
       I am very new to Web Dynpro ABAP.
      I am developing an application to display an image in "Image" UI Element.
      For this I have one table consisting of fields image id, image data and image name. here image id is primary key field.
    Now i want to display an image from that table in "Image" UI Element. For this i am using "Filedown load" UI element.
    But by using filedownload ui element i can diaplay image in another new page.
    But my requirement is to display image in the same web page without creating a new one.
    (I want to display the image in "Image" UI element without storing that image in MIME objects.)
    Can anyone help me.
    Thanks in Advance!
    Regards,
    Sreelakshmi.

    What you describe is completely possible.  Since you have the image data (XSTRING) in the context you have everything you need.  You don't need to store the content into the MIME Repository, but you do need to get it somewhere where it has an externally accessible URL.  Remember you need to supply image UI element with a URL.  This URL is processed on the client side by the web browser.  Therefore just giving it a path to the context won't work as that isn't externally accessible.
    I would suggest instead that you place the image content into the ICM cache temporarily.  This lets you basically generate a temporary URL for the image that can be used by the Image UI element. 
    Here is some example code that pushes images into the ICM Cache:
    ****Create the cached response object that we will insert our content into
      DATA: cached_response TYPE REF TO if_http_response.
      CREATE OBJECT cached_response
        TYPE
          cl_http_response
        EXPORTING
          add_c_msg        = 1.
       try. " ignore, if compression can not be switched on
          call method cached_response->set_compression
            exporting
              options = cached_response->co_compress_based_on_mime_type
            exceptions
              others  = 1.
        catch cx_root.
      endtry.
    ****set the data and the headers
      DATA: l_app_type TYPE string.
      DATA: l_xstring TYPE xstring.
          cached_response->set_data( me->gx_content ).
          l_app_type = me->gx_mimetype
      cached_response->set_header_field( name  = if_http_header_fields=>content_type
                                         value = l_app_type ).
    ****Set the Response Status
      cached_response->set_status( code = 200 reason = 'OK' ).
    ****Set the Cache Timeout - 60 seconds - we only need this in the cache
    ****long enough to build the page and allow the Image on the Client to request it.
      cached_response->server_cache_expire_rel( expires_rel = I_CACHE_TIMEOUT ).
    ****Create a unique URL for the object
      DATA: guid TYPE guid_32.
      CALL FUNCTION 'GUID_CREATE'
        IMPORTING
          ev_guid_32 = guid.
      CONCATENATE i_path '/' guid '.' i_format INTO r_url.
    ****Cache the URL
      cl_http_server=>server_cache_upload( url      = r_url
                                           response = cached_response ).

  • Urgent:display result from JTable

    need help making the following in my code work:
    1.how do i display the whole table in my code using a dialog box or JOptionPane.
    2. i want to display a message beneath the table show the total price of items selected from the JComboBox .
    3.is there any way i could add a method or sommething that display detail of each item seleted from the list in a seperate column of the JTable in my code.say for instance,if i selects beans,1 cup, 100 and it display protein in a seperate column in the JTable.
    Thanks in advance.
    my code:
    '\n'
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.util.*;
    public class BreakFast extends JFrame implements ActionListener{
         private JList ingredient;
         private JTable table;
         private DefaultTableModel model;
         private JButton move;
         private String[] food;
         private JComboBox box,box1;
         private String[] units;
         private double[] price={100,150,200,250,300,350,400};
         private JButton finish;
         public BreakFast(){
              Container c=getContentPane();
              c.setLayout(new FlowLayout());
              food = new String[] {"Corn Flakes","Beans","Shredded Bread","Mushroom",
              "eggs","Milks","Butter","Sugar","water","Oil"};
              ingredient = new JList(food);
              ingredient.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
              ingredient.setVisibleRowCount(4);
              JPanel p = new JPanel();
              p.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
              move = new JButton(">>>");
              move.addActionListener(this);
              //meal = new JTextArea(5,20);
              //meal.setEditable(false);
              p.add(new JScrollPane(ingredient),"Wast");
              JPanel p2 = new JPanel();
              p2.setBorder(new BevelBorder(BevelBorder.RAISED));
              units = new String[]{"2 cups","3 cups","4 cups","5 cups","1 mudu","2 mudu",
                        "3 mudu","4 mudu","5 mudu","6 mudu","7 mudu","8 mudu","9 mudu",
                        "1 bag"};
              box = new JComboBox(units);
              box.addActionListener(this);
              box1 = new JComboBox();
              //box1.setEditable(true);
              box1.addActionListener(this);
              for(int i=0;i<price.length;i++){
                   box1.addItem(price);
              model = new DefaultTableModel();
              //model.addColumn("No.");
              model.addColumn("Food Items");
              model.addColumn("Units");
              model.addColumn("Price");
              table = new JTable(model);
              JScrollPane pane = new JScrollPane(table);
              pane.setPreferredSize(new Dimension(350,100));
              finish = new JButton("Finish");
              finish.addActionListener(this);
              p.add(box,"West");
              p.add(box1,"Center");
              p.add(move,"East");
              p2.add(pane,"North");
              p2.add(finish,"South");
              c.add(p);
              c.add(p2);
              setSize(450,300);
              setVisible(true);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public void actionPerformed(ActionEvent e){
         Object[] value = ingredient.getSelectedValues();
         if(e.getSource() == move){
         for(int i=0;i < value.length;i++){
         String word = (String)value[i];
         Vector<Object> data = new Vector<Object>();
         data.addElement( word );
    data.addElement( box.getSelectedItem() );
    data.addElement( box1.getSelectedItem());
         model.addRow( data );
         if(e.getSource() == finish){
              JOptionPane.showMessageDialog(BreakFast.this,table,"Selection Summary",JOptionPane.PLAIN_MESSAGE);
              System.exit(0);
         public static void main(String[] arg){
              new BreakFast();

    Multi-Post:
    http://forum.java.sun.com/thread.jspa?threadID=5122371&tstart=0
    Ignored.

  • Display image from database with jspSmart

    Hi
    I have successfully uploaded and saved images into oracle(8.1.5) table DATA_TYPE(dtid number, iconname varchar2(30), icon blob). When I try to display a specific icon in my browser, I get "javax.servlet.ServletException: General error" at:
    PreparedStatement pstmt = myConnection.prepareStatement(mySQL);
    My code looks like this:
    imgModifyDataType.jsp
    <%
    ResultSet myResultSet = null;
    Statement myStatement = null;
    Connection myConnection = null;
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
    myConnection = DriverManager.getConnection("Jdbc:Odbc:Te","te","te");
    String iconName;
    String pDTID = request.getParameter("dtid");
    String mySQL = "Select iconname, icon from data_types where dtid=?";
    PreparedStatement pstmt = myConnection.prepareStatement(mySQL);
    pstmt.setString(1,pDTID);
    myResultSet = pstmt.executeQuery();
    iconName = myResultSet.getString("iconname");
    myUpload.initialize(pageContext);
    myUpload.downloadField(myResultSet,"icon","application/x-msdownload", iconName);
    %>
    I call this JSP from another JSP like this:
    <img src="imgModifyDataType.jsp?dtid=<%=pDTID%>">
    If we cannt display image with the help of another jsp like this then please guide me how to modify the imgModifyDataType.jsp to a servlet because I have never worked in servlets.
    Please help
    Sajid

    I think that it may help you get image from database. I used two jsp page. First one is getphoto.jsp that makes as table based in sql statment and invoke the getimage.jsp this last returns images based on
    the getphoto.jsp PhotoId.
    /** getphoto.jsp source code */
    <%@page import="java.sql.*,oracle.jdbc.*"%>
    <html>
    <head>
    <title>
    jsp1
    </title>
    </head>
    <body bgcolor="#ffffff">
    <table width="781" border="2">
    <tr<<td>
    <td width="83" bgcolor="#C0C0C0"><b>PhotoId</b><td width="450" bgcolor="#C0C0C0"><b>Description</b></td><td width="228" bgcolor="#C0C0C0"><b>Photo Image</b></td>
    <%
    Connection conn = null;
    Statement stmt = null;
    ResultSet rset = null;
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    conn = DriverManager.getConnection("jdbc:oracle:thin:@itas:1521:oraITAS","yourDbUserId","yourDbPassword");
    stmt = conn.createStatement();
    rset = stmt.executeQuery("select photo_id,photo_description from photo");
    while (rset.next()) {
         %>
         <tr><td width="83"><%=rset.getObject("photo_id")%></td><td width="450"><%=rset.getObject("photo_description")%></td><td width="228"><img src="getimage.jsp?PhotoId=<%=rset.getObject("photo_id")%>" width="238" height="228"></td></tr>
         <%
    conn.close();
    %>
    </table>
    </body>
    </html>
    /** getimage.jsp source code */
    <%@ page contentType="image/jpeg; chaoResult=iso-8859-1" language="java" import="java.sql.*,java.io.*,java.util.*" errorPage="" %>
    <%
    String strConnString = null;
    Connection oDbConn;
    Statement oStmt;
    ResultSet oResult;
    String strConnection = null;
    String strUserId = "c_erober";
    String strUserPwd = "sybdev99";
    String strDatabase = "oraITAS";
    String strPhotoId;
    strConnString = "jdbc:odbc:" + strDatabase;
    String strSql;
    try {
    strPhotoId = (String) request.getParameter("PhotoId");
    strSql = "select photo_image from photo" + ( (strPhotoId==null) ? " where photo_id = '001'": (" where photo_id = '" + strPhotoId + "'") );
    DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
    oDbConn = DriverManager.getConnection(strConnString,strUserId,strUserPwd);
    response.setContentType("image/jpeg");
    oStmt = oDbConn.createStatement();
    oResult = oStmt.executeQuery(strSql);
    oResult.next();
    byte[] bytearray = new byte[4096];
    int size=0;
    InputStream sImage;
    sImage = oResult.getBinaryStream(1);
    response.reset();
    response.setContentType("image/jpeg");
    response.addHeader("Content-Disposition","filename=getimage.jpeg");
    while((size=sImage.read(bytearray))!= -1 ) {
    response.getOutputStream().write(bytearray,0,size);
    response.flushBuffer();
    sImage.close();
    oDbConn.close();
    } catch (SQLException ex) { ex.getMessage();
    %>

  • Display records from database table

    My database table has 495K records i want to display them all in se11 tcode and than download into excel ...but because of huge records it timeout.
    Do I need to write a program for this?
    Or is there any other smarter way.
    Regards,
    DNP

    Hi,
    Please follow the steps below:
    1. Go to the selection screen of SE11 and provide your selection criteria (if required).
    2. Click on Settings menu->User parameters->ALV Grid display.
    3. Now click on Program menu->Execute in background->Provide output device name as LP01 or LOCAL or any valid printer parameters->Click continue->Click Immediate button->Click Save.
    4. You can see the background job for this in SM37.
    5. Once the background job is completed, it will appear in gleen color.
    6. Click on the completed job and then click on Spool button.
    7. Once the output is displayed in spool you can now easily download it to excel by clicking on System menu->List->Save->Local File.
    Hope this will help you.
    Regards,
    Venkat

  • Prompt i want to display as From Date & To Date - as a lastmodified date

    Hi All,
    i want to displayed as a from date and to date from the column name as lastmodified date in the prompt. in the prompt i selected the between option it is displayed as a between and not as a from date - to date.
    From Date(prompt button as calender)----------To Date
    Thanks
    Chandra

    Hi,
    can u pls look into the below link
    http://docs.oracle.com/cd/E10415_01/doc/bi.1013/e12188/T421739T524310.htm

  • Trying to display results from access database query on a JSP

    Seem to be having real difficulty with this one, i keep getting a null pointer exception :(. Wondered if anyone could point me to any examples of displaying the results on jsp. The database is connected, as i can display the query on netbeans, but just not on a jsp.

    I think it would be good if we had a section in these forums for pre-canned answers to the same questions that come up again and again. It would save time.
    Here is a rough outline for using JSP:
    * Read a JSP book.
    * The JSP page (View in MVC) should get all the data it needs to display from a useBean and/or request.getAttribute().
    * The JSP page should not have any business logic. Its purpose is to display data only (and have some submit buttons such as 'update').
    You can do some basic client side validation using javascript if you want. Because there is no business logic in it, you can easily debug
    your code in the servlet or business logic. You can't set breakpoints in JSP and examine data easily.
    * When you click the submit button, all data from <input type="text" tags, etc is put into request scope via name/value pairs.
    * Submit the JSP page <form tag to a servlet (Control in MVC).
    * The servlet reads the name/value pairs of data from the JSP page via request.getParameter()
    * The servlet should then instansiate a business object (Model in MVC), passing the data it got from the page to the business logic.
    Example: ProcessPage processPage();
    if(request.getParameter("updateButtonClicked"))
    processPage.updateData(data from the jsp page)
    * The business logic should instansiate a separate database object (DAO) to get data to/from the database. Business logic should not have sql in it.
    Business logic should not generate html. Business logic should not have request objects in it.
    * The business logic should return data to the servlet that in turn will put it in request scope via request.setAttribute() so the JSP page can draw itself.
    * The servlet should then call up the approprate JSP page.

  • Displaying results from a database query using servlets

    I have this HTML form where users can search a MS Access database by entering a combination of EmployeeID, First name or last name. This form invokes a Java Servlet which searches the database and displays the results as an HTML page. I am giving the user the choice of displaying 3, 5 or 10 results per page. I want to know how to do that using servlets. If a particular search results in 20 results, the results should be displayed in sets of 3, 5 or 10 depending on the user's choice. If the user makes a choice of 5 results per page then 4 pages should be displayed with a "next" and "previous" button on each page. I want to know how this can be done.

    Arun,
    I'm not sure how to do this using JSP as I have not worked on JSP.
    But I can give you a hint on how to do this within normal java class as I've used this in my current project.
    In your core class/bean that generates the entire resultset, you need to run a loop that will scan through the desired number of records in the resultset.
    To do this, you have to have skip and max parameter in your URL.
    Somthing like http://server.com/myservlet?skip=0&max=10 to display first 10 records, http://server.com/myservlet?skip=10&max=10 to display next 10 records. The <next>parameter would be fed in by the user by a simple form in your web-page. If you need to hold this <max-num-of-recs-per-page> param, you can store it in a cookie (since this is nothing crucial piece of info, don't need to use session obj etc...cookie will do) and get the value each time you display the resultset.
    So, essentially, suppose you are at the first page and you wish to show 10 recs at a time. The link for "Next" button would be http://server.com/myservlet?skip=10&max=10
    when at the second page, you'll have
    "priv" button as http://server.com/myservlet?skip=0&max=10 and
    "next" button as http://server.com/myservlet?skip=20&max=10 and so on...
    hope this makes sense..
    Shantanu

Maybe you are looking for