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

Similar Messages

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

  • Trouble displaying results from a database call

    Hi Everyone,
    I have written a JSP page that sends and receives information to a MySQL database. It is not completely functional unfortunately. The first section of the page that is responsible for updating a database table works fine. However when I go to retrieve information from the same database table something is going astray.
    I feel that I am doing something wrong with regard to the ResultSet object. Please see the bottom of the code section below. Ultimately this code only displays beach_percent as Zero, no matter how many entries there are in the database table for the corresponding value of Beach & Sea Stamps.
    <%@ page import="javax.servlet.*" %>
    <%@ page import="javax.servlet.http.*" %>
    <%@ page import="java.sql.*" %>
    <%
         Connection connect = null;
         Statement state = null;
         ResultSet rs = null;
         Class.forName("com.mysql.jdbc.Driver").newInstance();
         String password = "theOne";
         String url = "jdbc:mysql://localhost/survey_database";
         String user = "David";
         connect = DriverManager.getConnection(url, user, password);
         state = connect.createStatement();
         if(request.getParameter("radiobutton") != null)
              String enter_text = "insert into craft_survey values('";
              enter_text = enter_text.concat(request.getParameter("radiobutton"));
              enter_text = enter_text.concat("')");
              rs = state.executeQuery(enter_text);
         else
              pageContext.forward("craftSurvey.jsp");
         rs = state.executeQuery("SELECT stamp FROM craft_survey");
         int beach = 0;
         int bear = 0;
         int christmas = 0;
         int country = 0;
         int easter = 0;
         int faux = 0;
         int floral = 0;
         int heart = 0;
         int phrase = 0;
         int special = 0;
         int total = 0;
         while(rs.next())
              String type = rs.getString("stamp");
              if(type.equals("Beach & Sea Stamps"))
                   beach++;
                   total++;
              else
              if(type.equals("Bear & Cuddly Stamps"))
                   bear++;
                   total++;
              else
              if(type.equals("Christmas Stamps"))
                   christmas++;
                   total++;
              else
              if(type.equals("Country & Garden Stamps"))
                   country++;
                   total++;
              else
              if(type.equals("Easter Stamps"))
                   easter++;
                   total++;
              else
              if(type.equals("Faux Postage"))
                   faux++;
                   total++;
              else
              if(type.equals("Floral Stamps"))
                   floral++;
                   total++;
              else
              if(type.equals("Heart & Romance Stamps"))
                   heart++;
                   total++;
              else
              if(type.equals("Phrase & Wording Stamps"))
                   phrase++;
                   total++;
              else
              if(type.equals("Special Occasion Stamps"))
                   special++;
                   total++;
         int beach_percent = 0;
         int bear_percent = 0;
         int christmas_percent = 0;
         int country_percent = 0;
         int easter_percent = 0;
         int faux_percent = 0;
         int floral_percent = 0;
         int heart_percent = 0;
         int phrase_percent = 0;
         int special_percent = 0;
         if(beach > 0)
              beach_percent = (beach / total) * 100;
         if(bear > 0)
              bear_percent = (bear / total) * 100;
         if(christmas > 0)
              christmas_percent = (christmas / total) * 100;
         if(country > 0)
              country_percent = (country / total) * 100;
         if(easter > 0)
              easter_percent = (easter / total) * 100;
         if(faux > 0)
              faux_percent = (faux / total) * 100;
         if(floral > 0)
              floral_percent = (floral / total) * 100;
         if(heart > 0)
              heart_percent = (heart / total) * 100;
         if(phrase > 0)
              phrase_percent = (phrase / total) * 100;
         if(special > 0)
              special_percent = (special / total) * 100;
    %>
    <html>
    <head>
    <title> Craft Stamp Survey Results </title>
    </head>
    <body background="#ffffff">
    <h1> Craft Stamp Survey Results </h1>
    <table width="100%">
         <tr align="center">
         <td><img src="green_bar.jpg" height="20" width="<%=beach_percent *3%>"></td>
            <td>Beach & Sea Stamps</td>
            <td><%=beach_percent%></td>
    </tr>
    </table>
    </body>
    </html>Any help with getting this page to display anything other than zero will be great appreciated.
    Thanks
    David

    Hi,
    One reason could be of spaces .Before checking in the loop use trim function on the data retrieved from the database. You can also debug using System.out.println.
    Also just a suggestion - it is always a good coding practice to declare the variablse outside the loop. Don't declare the variables within a for loop.

  • HELP! Displaying results from a database in table format

    I'm developing a web application that will use a considerable number of database queries that need to be displayed back to the web-browser in HTML table format.
    I have been told that that result sets can allow tables to be built automatically without having to write the same loop and display code over and over.
    So far I have a HtmlResultSet class as follows:
    import java.sql.*;
    public class HtmlResultSet {
    private ResultSet rs;
    public HtmlResultSet(ResultSet rs) {
    this.rs = rs;
    public String toString() {  // can be called at most once
    StringBuffer out = new StringBuffer();
    // Start a table to display the result set
    out.append("<TABLE>\n");
    try {
    ResultSetMetaData rsmd = rs.getMetaData();
    int numcols = rsmd.getColumnCount();
    // Title the table with the result set's column labels
    out.append("<TR>");
    for (int i = 1; i <= numcols; i++) {
    out.append("<TH>" + rsmd.getColumnLabel(i));
    out.append("</TR>\n");
    while(rs.next()) {
    out.append("<TR>"); // start a new row
    for (int i = 1; i <= numcols; i++) {
    out.append("<TD>"); // start a new data element
    Object obj = rs.getObject(i);
    if (obj != null)
    out.append(obj.toString());
    else
    out.append(" ");
    out.append("</TR>\n");
    // End the table
    out.append("</TABLE>\n");
    catch (SQLException e) {
    out.append("</TABLE><H1>ERROR:</H1> " + e.getMessage() + "\n");
    return out.toString();
    I also have created a class that includes an instance of the class above to display the results, as follows:
    import java.io.*;
    import java.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class customerLookup2 {
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    try{
    Class.forName("org.gjt.mm.mysql.Driver");
    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sandywalker");
    out.println("<html>");
    out.println("<head><title> Users</title></head>");
    out.println("<body> Customers");
    HtmlResultSet result = new HtmlResultSet ("SELECT * FROM USERS");
    out.println("</body></html>");
    catch(ClassNotFoundException e ) {
    out.println("Couldn't load database driver: " + e.getMessage());
    catch(SQLException e) {
    out.println("SQLExeption caught: " +e.getMessage());
    finally {
    try {
    if (con !=null) con.close();
    catch (SQLException ignored) { }
    I keep getting a compile error "customerLookup2.java": Error #: 300 : constructor HtmlResultSet(java.lang.String, java.sql.Connection) not found in class HtmlResultSet at line 42, column 34".
    Can anyone shed any light on this.

    Looks like you are passing a string (SELECT * FROM USERS) instead of passing a ResultSet. Try passing a Resultset.

  • How to present results from a sql-query in java

    Hi - I'm having problems finding out how to present data from a database-query in a nice looking way in a JFrame. Want to present them similar to the way they are presented in the database. Is there an easy way doing this?

    Tried to use a JTable, but it's difficult when data in the table should be able to change all the time, i.e the number of rows. What is a Html-table? Can i use it in an application?

  • Walkthrough: Displaying Data from Oracle database in a Windows application.

    This article is intended to illustrate one of the most common business scenarios such as displaying data from Oracle database on a form in a Windows application using DataSet objects and .NET Framework Data Provider for Oracle.
    You can read more at http://www.c-sharpcorner.com/UploadFile/john_charles/WalkthroughDisplayingDataOracleWindowsapplication05242007142059PM/WalkthroughDisplayingDataOracleWindowsapplication.aspx
    Enjoy my article.

    hi,
    this is the code :
    public class TableBean {
    Connection con ;
    Statement ps;
    ResultSet rs;
    private List perInfoAll = new ArrayList();
    public List getperInfoAll() {
    int i = 0;
    try
    con = DriverManager.getConnection("url","root","root");
    ps = con.createStatement();
    rs = ps.executeQuery("select * from user");
    while(rs.next()){
    System.out.println(rs.getString(1));
    perInfoAll.add(i,new perInfo(rs.getString(1),rs.getString(2),rs.getString(3)));
    i++;
    catch (Exception e)
    System.out.println("Error Data : " + e.getMessage());
    return perInfoAll;
    public class perInfo {
    String uname;
    String firstName;
    String lastName;
    public perInfo(String firstName,String lastName,String uname) {
    this.uname = uname;
    this.firstName = firstName;
    this.lastName = lastName;
    public String getUname() {
    return uname;
    public String getFirstName() {
    return firstName;
    public String getLastName() {
    return lastName;
    ADF table code:
    <af:table value="#{tableBean.perInfoAll}" var="row"
    binding="#{backing_Display.table1}" id="table1">
    <af:column sortable="false" headerText=""
    align="start">
    <af:outputText value="#{row.firstName"/>//---> Jdeveloper 11g doesn't allow me to use this.. it says firstName is an unknown property..
    </af:column>
    </af:table>
    Please tell me is this the way to do it.. or is it a must to use the DataCollection from the data controls panel...
    Thanks...

  • How to configure search results web part to display results only after a query is generated from user?

    Hi All,
    I am crawling documents from a file server. I created a new content source and crawled the documents. All documents are crawled successfully.
    Then I went to my enterprise search center site collection and created a new result source. I have added the query to use above content source.
    After that, on a page I am trying to configure the search results web part to display documents using this result source. Now the problem is:
    It displays all the documents that are crawled without searching for anything. I mean first it should not display any results. If a user searches for something , then according to that search it should display results.
    Any idea how to do this in the web part? I am using SharePoint 2013 on premise enterprise edition. No code. Totally OOTB.

    Hi Mohan,
    What did you use for the Query text in the result source?
    I could reproduce this issue when I used Query text like: {searchTerms} Path:”http://sps2k13sp/sites/First/Shared%20Documents”
    Then I changed the Query to
    {?{searchTerms}
    Path:"http://sps2k13sp/sites/First/Shared%20Documents"}
    , then Search result web part didn’t return results without searching.
    So , check your result source, and use the Query like the above(adding "{?...}").
    I hope this helps.
    Thanks,
    Wendy
    Wendy Li
    TechNet Community Support

  • Display results from dynamic query created and executed inside procedure

    Hi;
    I have created this code:
    CREATE OR REPLACE PROCEDURE RunDynamicQuery(Var1 IN VARCHAR2, Var2 IN VARCHAR2, VAR3 IN VARCHAR2) AS
    -- Do something
    -- That ends up with a variable holding a query.... (just an example)
    MainQuery :='select sysdate from dual';
    end RunDynamicQuery;
    How can I run this procedure and see the result on the dymanic query generated inside it?
    BEGIN
    compare_tables_content('VAR1','VAR2','VAR3');
    END;
    Expected Output for this given example:
    20-05-2009 11:04:44 ( the result of the dymanic query inside the procedure variable MainQuery :='select sysdate from dual';)
    I tested with 'execute immediate':
    CREATE OR REPLACE PROCEDURE RunDynamicQuery(Var1 IN VARCHAR2, Var2 IN VARCHAR2, filter IN VARCHAR2) AS
    -- Do something
    -- That ends up with a variable holding a query.... (just an example)
    MainQuery :='select sysdate from dual';
    execute immediate (MainQuery );
    end RunDynamicQuery;
    BEGIN
    compare_tables_content('VAR1','VAR2','VAR3');
    END;
    Output:"Statement processed'' (no sysdate displayed ! )
    Please consider that the collums in the query are always dynamic... PIPELINE Table would not work because I would need to define a container, example:
    CREATE OR REPLACE TYPE emp_tabtype AS TABLE OF emp_type;
    FUNCTION RunDynamicQuery (p_cursor IN sys_refcursor)
    RETURN emp_tabtype PIPELINED
    IS
    emp_in emp%ROWTYPE;
    BEGIN
    LOOP
    FETCH p_cursor
    INTO emp_in;
    EXIT WHEN p_cursor%NOTFOUND;
    PIPE ROW (...)

    That would be a nice solution, thanks :)
    ''For now'' I implemented like this:
    My dynamic query now returns a single string ( select col1 || col2 || col3 from bla)
    This way I don't have dynamic collumns issue, and from business side, this ''string'' format works for them.
    This way I can use the pipelines to get the result out...
    OPEN myCursor FOR MainQuery;
    FETCH myCursor
    INTO myRow;
    WHILE (NOT myCursor%notFound) LOOP
    PIPE ROW(myRow);
    FETCH myCursor
    INTO myRow;
    END LOOP;
    CLOSE myCursor;

  • How to generate XML file from oracle database query result

    Hi dudes,
    as stated on the subject, can anyone suggests me how can i achieve the task stated above??
    Here is a brief description of my problem:
    I need to create a XML file once i query from the oracle database, and the query result returned from the database will be stored in XML file.
    I'd searched around the JAXB, DOM, SAXP and the like basic concepts, but i still don't know how to start??
    Any suggestions ???

    Read this:
    http://www.cafeconleche.org/books/xmljava/chapters/ch08s05.html
    You might have to read more of the book to understand that chapter.

  • Last Result from Fulltext SQL Query Search Not Showing

    I am creating a custom search results page for MOSS 2007 (using inline .aspx code - don't ask) that uses Fulltext SQL Queries.  I get the results in a ResultTable (see code below) and then use a DataTable to write code to display it (I could have used
    a DataGrid, I know).
    The problem is that the last result is not showing. So, if it reports that there are 5 results, only 4 will show. I have verified that all 5 results do exist (using a slightly broadened query). If it reports 1 result, none exist in the DataTable that loads
    the result data from the ResultTable.
    FullTextSqlQuery query = new FullTextSqlQuery(site);
    query.ResultTypes = ResultType.RelevantResults;
    query.QueryText = qry;
    query.RowLimit = 50;
    query.StartRow = iPage;
    try
    ResultTableCollection results = query.Execute();
    ResultTable resultTable = results[ResultType.RelevantResults];
    DataTable table = new DataTable();
    table.Load(resultTable, LoadOption.OverwriteChanges);
    int n = resultTable.TotalRows;
    The variable "qry" is a valid SQL Query with the relevant clauses.
    I am using a foreach loop to go through "table" (a DataTable), and so I do not think that I have a "one-off error".
    Any suggestions would be most welcome.

    So in results you have all items but when you are loading it into table (type DataTable) you are loosing one last record.
    1) First you check what data you are getting in resultTable - as you are specifying RelevantResult
    2) Check last index of data in ResultTable collection and try to find out the last index ResultTable, or try to find last index of data in result table
    DataTable.Load method accepts parm of type IDataReader and IDatareader, there are cases it looses records if not read properly..check below links
    http://stackoverflow.com/questions/8396656/why-does-my-idatareader-lose-a-row
    http://msdn.microsoft.com/en-us/library/system.data.datatable.load(v=vs.110).aspx
    <hr> Mark ANSWER if this reply resolves your query, If helpful then VOTE HELPFUL <br/> <b><a href="http://insqlserver.com">Everything about SQL Server | Experience inside SQL Server </a></b>-<a href="http://insqlserver.com">Mohammad
    Nizamuddin </a>

  • JTree, displaying data from a database

    Hi, im doing an application that will display the listing of courses, and allow users to book them. For the display of courses, i plan to use JTree to display them.
    However my problem arises from fetchin data and putting them into the tree.
    This file connects to the database and fetch the 'Course Category' and puts it in an Array.
    public ArrayList<CourseCategory> getCategory() {
    ArrayList<CourseCategory> categoryArray = new ArrayList();
    try {
    String statement = "SELECT * FROM Category";
    rs = stmt.executeQuery(statement);
    while (rs.next()) {
    CourseCategory cc = new CourseCategory();
    cc.setCategoryID(rs.getInt("CategoryID"));
    cc.setCategoryName(rs.getString("CategoryName"));
    categoryArray.add(cc);
    rs.close();
    stmt.close();
    con.close();
    catch (Exception e) {
    //catch exception     }
    return categoryArray;
    CourseCategory File has the necessary accessor methods, and a toString method to display out the category name.
    The main file, which has the JTree
    public DisplayCoursesGUI() {
    try {
    courseDB = new CourseDB();
    courseDB.getCategory();
    catch (Exception e) {
    //catch exception }
    DefaultMutableTreeNode top = new DefaultMutableTreeNode("");
    for (int i=0;i<courseDB.test2().size();i++) {
    category = new DefaultMutableTreeNode(courseDB.getCategory());
    top.add(category);
    Codes for JTrees as follows.
    I have the output of
    e.g.
    [MICROSOFT OFFICE APPLICATIONS, WEB APPLICATIONS] repeated twice in the tree. Im hoping to achieve the following effects
    e.g.
    -MICROSOFT OFFICE APPLICATIONS
    ----Microsoft Word
    ----Microsoft Powerpoint
    -WEB APPLICATIONS
    -----Adobe Photoshop
    I have 2 MS Access Table.[Category]ID, CategoryName. [COURSE]ID,CourseName,CategoryID. They have a relationship.
    How do I modify my codes to get what i hope to achieve? Help really appreciated.
    Thank you!!

    Hi,
    If you read my first post, I wanted to achieve this effect.
    ----CategoryName1
    ----------SubCategoryItem1
    ----CategoryName2
    ----------SubCategoryItem2
    My Table Structure.
    CATEGORY TABLE
    ID (autonumber), Name(string)
    COURSES TABLE
    ID(autonumber),Name(string), CategoryID(int)(A Relationship is link to Category Table-ID)
    I have managed to retrieve the items from the Category Table into a result set, and I have added the result set into an Array (See 1st post)
    Now, the problem comes when im tryin to do a for loop to display out the categorynames from the array(see 1st post again).
    Now my array prints out as follows
    e.g.
    [CategoryName1,CategoryName2]
    And if i put a for look into my application to display a JTREE,
    My end results is
    ------[CategoryName1, CategoryName2]
    ------[CategoryName1, CategoryName2]
    How should I ammend my codes to get:
    -------CategoryName1
    -------CategoryName2

  • Display Image from the database but prevent it from refreshing on every pages

    Hi there,
    I can see there are many discussions around this but my query is slightly different. I'm writing this on behalf of one of my developers. (sorry for my ignorance on techie stuff.. :-))
    A logo is being displayed on a few pages, which is called from the database. However, the problem is that  - this logo refreshes every time when you traverse to each page causing a performance issue or sometimes slow loading of the image.
    My question is - how do we stop it from loading on each page from the database?.  I would rather load once when the main page loads initially and then maintain this on other pages too.
    We can keep this logo on a file system (FS)  and display it via CSS/HTML/frame but since we want to keep it flexible/dynamic where a user can upload a new one whenever it changes and hence DB seems to be the suitable option (in my opinion).
    Can someone please help?
    If you need any further info around the coding how it is being done at present, pls let me know.
    Thank you

    read this http://docs.oracle.com/cd/B28359_01/appdev.111/b28393/adlob_tables.htm#g1017777
    you can cache lobs in the database too
    you can also upload the pic in your file system using utl_file package and then put the image in the working directory mentioned in i.war
    you can then reference the image and it will not be stored in the database and will be cached
    Regards,
    Vishal
    Oracle APEX 4.2 Reporting | Packt Publishing
    Vishal's blog

  • Show results from the database to html tables?

    Hi,
    I am a PHP programmer and did a successful CMS program for a company. Now I have another project which is a web based system.
    I basically know how to do it and finish it in PHP.. but I am trying to do it using J2EE.. I am trying to learn J2EE now since I have been programming
    on J2SE for quite sometime..
    I am trying to show the results from a MySQL database on a table on J2EE but I am having hard time doing that. I am trying to research online and reading books but with no luck I can't find any resources on how to do that..If you guys can lead me into a resource where I can read how to do it? or just give any ideas on how to do it correctly I'll try to read and learn I will very much appreciate it.. here's my coding please look at it. Thank you very much
    I want to make it like this in a html table:
    userid username activated task
    1 alvin y delete(this will be a link to delete the user)
    Right now this is what I was able to do so far:
    Userid username activated task
    1
    alvin
    y
    Here are my codes... I am not even sure if I am doing it in the correct way...
    User.java
    mport java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    import java.util.List;
    public class Users {
    public List getUsers(){
    List names = new ArrayList();
    try{
    Connection con = DBConnect.getConnection();
    Statement stmt = con.createStatement();
    String sql = "select * from users";
    ResultSet rs = stmt.executeQuery(sql);
    while(rs.next())
    String userid = rs.getString("user_id");
    String usernames = rs.getString("user_name");
    String password= rs.getString("password");
    String activated= rs.getString("activated");
    names.add(userid);
    names.add(usernames);
    names.add(password);
    names.add(activated);
    catch(SQLException e)
    System.out.print(e);
    catch(Exception e)
    System.out.print(e);
    return names;
    UserServlet.java
    import java.io.IOException;
    import java.util.List;
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    public class UsersServ extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Users be =new Users();
    List result = be.getUsers();
    request.setAttribute("user_results", result);
    RequestDispatcher view = request.getRequestDispatcher("manage_users1.jsp");
    view.forward(request, response);
    manage_users1.jsp
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <%@page import = "java.util.*" %>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    <%
    List results = (List)request.getAttribute("user_results");
    Iterator it = results.iterator();
    out.print("<table border = 1>");
    out.print("<th>");
    out.print("userid");
    out.print("</th>");
    out.print("<th>");
    out.print("username");;
    out.print("</th>");
    while(it.hasNext()){
    out.print("<tr><td> " + it.next()+"</td></tr>");
    out.print("</table>");
    %>
    </body>
    </html>

    I suggest:
    1: you use this:
    e.printStackTrace()
    instead of this:
    System.out.print(e);
    so it will tell you what line it crashed on.
    2: In the code below,here is how you mix coding html tags and java scriptlets
    (you should never have to use out.print()):. In a later project, you can learn how to use JSTL
    instead of java scriplets (I suggest using java scriptlets for now until you have more JSP experience).
    FROM:
    <html>
    <%
    //some java code goes here
    out.print("<th>");
    //some more java code goes here
    out.print("<tr>");
    %>
    TO:
    <html>
    <% //some java code goes here%>
    <th>
    <%//some more java code goes here%>
    <tr>
    3: Put a lot of System.println() statements in your *.java classes to verify what its doing (you can learn how to use a debugger later).
    4: I highly recommend reading a book on JSP/servlets cover to cover.
    Here's a simple MVC design approach I previously posted:
    http://forums.sun.com/thread.jspa?messageID=10786901

  • How to display contents from a database to a jsp page

    hi im using hibernate , i want to display the conetents from a databse to jsp page which is having a form
    i want to get the data on the form fields after changing the values i want to write it back to the database
    im using struts and hibernate
    im struck with this plz help me

    j2ee_struts_hibernate wrote:
    hi im using hibernate , You probably shouldn't be using Hibernate.
    i want to display the conetents from a databse to jsp page which is having a form "contents", "database"
    i want to get the data on the form fields after changing the values i want to write it back to the databaseWhat don't you understand? (Sounds like you don't understand anything.)
    im using struts and hibernate How well do you know Struts? Hibernate? JSP? Java?
    im struck with this plz help meAsk a specific question and we'll see what we can do.
    Write a JSP with the form in it; submit to Struts; Struts interacts with the database. That's the flow.
    %

  • Returning the result of a database query to a client

    glassfish
    JAX-WS 2.0
    NetBeans 5.5
    Is it possible to send a CachedRowSet object to a client?
    I get an error when i try to do so. (I can't deploy the web service method that returns the CachedRowSet)
    Is there a better way to return the result of database query to a client?
    I'd appreciate any suggestions or sample code.

    Hi!
    The result of this query will be the max ID of users' IDs.
    Let say we have:
    String sql="select max(users.id) from users";
    Statement st = ctx.conn.createStatement();
    ResultSet rs = st.executeQuery(sql);
    rs.next();     
    So you can get the max Id in the following way:     
    int maxId=rs.getInt("id");
    Regards,
    Rossi

Maybe you are looking for