Populating a html form using jsp resultset and then forwarding from data to a bean??

hey
i just wanted to know if it is possible to populate a html form with data retrieved from a jsp resultset (quering a database)
and then on the form submit, have that parsed to a javabean
for further processing
i have tried several other methods and none work correctly
like:
<%
        String siteId = rs.getString("SiteID");
        Bean5.setSiteId(siteId);
%>
      <td height="10"><div align="center"><%= siteId %></div></td>

what would i do if i put the value "siteId" in a textfield and then sent it to the bean called Bean5 above????
what is the correct code for this??
Gaz
Gar04Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

sompol_kiatkamolchaiCommented:
After review your code it seems that you are new to JSP.
I would like to give you some code that you can follow.
This code have a good design by following one of the most popular design pattern "MVC" Model-View-Controller
You can study from this it and use as a guideline.

DatabaseConnection.java
================
package shoppingcart.database;

import java.sql.*;

public class DatabaseConnection {
  public DatabaseConnection() {
  }

  public static Connection getConnection() {
    Connection con = null;
    try {
      Class.forName("com.borland.datastore.jdbc.DataStoreDriver");
      con = DriverManager.getConnection("jdbc:borland:dslocal:C:\\Documents and Settings\\sompol\\jbproject\\shoppingcart\\database\\shopping.jds", "sample", "");
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
    return con;
  }
}


Book.java
======
package shoppingcart.database;

import java.util.*;
import java.sql.*;
import shoppingcart.bean.*;
public class Book {
  public Book() {
  }

  public Vector listAll() {
    Vector result = new Vector();
    Connection con = DatabaseConnection.getConnection();
    try {
      PreparedStatement stmt = con.prepareStatement("select * from book");
      ResultSet rs = stmt.executeQuery();
      while ( rs.next() ) {
        BookBean bean = new BookBean();
        bean.setBookId(rs.getInt("id"));
        bean.setBookName(rs.getString("name"));
        bean.setBookPrice(rs.getDouble("price"));
        result.add(bean);
      }
    }
    catch (SQLException ex) {
    }
    finally{
      try {
        con.close();
      }
      catch (SQLException ex1) {
      }
    }
    return result;
  }
}

BookBean.java
=========
package shoppingcart.bean;

public class BookBean {
  private int bookId;
  private String bookName;
  private double bookPrice;
  public BookBean() {
  }
  public int getBookId() {
    return bookId;
  }
  public void setBookId(int bookId) {
    this.bookId = bookId;
  }
  public String getBookName() {
    return bookName;
  }
  public void setBookName(String bookName) {
    this.bookName = bookName;
  }
  public double getBookPrice() {
    return bookPrice;
  }
  public void setBookPrice(double bookPrice) {
    this.bookPrice = bookPrice;
  }

}

ShoppingCartServlet.java
================
package shoppingcart.servlet;

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

public class ShoppingCartServlet extends HttpServlet {
  //Process the HTTP Post request
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession();

    Hashtable cart = (Hashtable) session.getAttribute("cart");
    if ( cart == null ) {
      cart = new Hashtable();
      session.setAttribute("cart", cart);
    }

    String action = request.getParameter("action");

    if ( action.equals("Check Out") ) {
      response.sendRedirect("checkout.jsp");
    }

    if ( action.equals("Add")  || action.equals("Remove")) {
      String[] amounts = request.getParameterValues("amount");
      String[] bookIds = request.getParameterValues("bookId");

      for (int i = 0; i < bookIds.length; i++) {
        if (amounts[i].trim().length() > 0) {
          Integer curAmount = (Integer) cart.get(bookIds[i]);
          if (curAmount == null) curAmount = new Integer(0);
          int curAmountIntValue = curAmount.intValue();
          if (action.equals("Add")) {
            curAmountIntValue += Integer.parseInt(amounts[i]);
          }
          else {
            curAmountIntValue -= Integer.parseInt(amounts[i]);
          }
          cart.put(bookIds[i], new Integer(curAmountIntValue));
        }
      }
      response.sendRedirect("shopping.jsp");
    }
  }
}

shopping.jsp
========
<%@ page session="true"%>
<%@ page import="shoppingcart.database.*"%>
<%@ page import="shoppingcart.bean.*"%>
<%@ page import="java.util.*"%>
<%
      // Get user's cart from session
      // If it does not exist, create an empty new one
      // and store into session object.
      Hashtable cart = (Hashtable) session.getAttribute("cart");
      if ( cart == null ) {
             cart = new Hashtable();
            session.setAttribute("cart", cart);
      }
      // Get book list from session
      // If it does not exist, create a new one from database
      // and store into session object.
      Vector list = (Vector) session.getAttribute("bookList");
      if ( list == null ) {
            Book book = new Book();
            list = book.listAll();
            session.setAttribute("bookList", list);
      }
%>

<html>
<head>
<title>Shopping</title>
</head>
<body>
<h1>Book List</h1>

<form name="form1" action="/web/shoppingcartservlet" method="POST">
<table border="1">
  <tr>
    <td>ID</td>
    <td>NAME</td>
    <td>PRICE</td>
    <td>AMOUNT</td>
  </tr>
<%
for(int i=0; i<list.size(); i++) {
  BookBean bean = (BookBean)list.elementAt(i);
%>
  <tr>
    <td><%=bean.getBookId()%><input type="hidden" name="bookId" value="<%=bean.getBookId()%>"></td>
    <td><%=bean.getBookName()%></td>
    <td><%=bean.getBookPrice()%></td>
    <td><input type="text" size="5" name="amount"></td>
  </tr>
<%
}
%>
</table>
<br>
<input type="button" value="Add to Shopping Cart" onclick="document.form1.action.value='Add'; document.form1.submit();"/>
<input type="button" value="Remove from Shopping Cart" onclick="document.form1.action.value='Remove'; document.form1.submit();"/>

<h1>Your Cart</h1>
<table border="1">
  <tr>
    <td>ID</td>
    <td>NAME</td>
    <td>PRICE</td>
    <td>AMOUNT</td>
    <td>TOTAL PRICE</td>
  </tr>
<%
Enumeration enum = cart.keys();
double total = 0.0;
while(enum.hasMoreElements()) {
      String bookId = (String)enum.nextElement();
          int amount = ((Integer)cart.get(bookId)).intValue();

       // Find name and price
       BookBean bean = null;
       for(int i=0; i<list.size(); i++) {
         bean = (BookBean)list.elementAt(i);
         if ( bean.getBookId() == Integer.parseInt(bookId) ) {
           break;
         }
       }
       total += (bean.getBookPrice()*amount);
%>
  <tr>
    <td><%=bookId%></td>
    <td><%=bean.getBookName()%></td>
    <td><%=bean.getBookPrice()%></td>
    <td><%=amount%></td>
    <td><%=bean.getBookPrice()*amount%></td>
  </tr>
<%
}
%>
  <tr>
    <td colspan="4" align="center">Total</td>
    <td><%=total%></td>
    </td>
  </tr>
</table>
<br>
<input type="button" value="Check Out" onclick="document.form1.action.value='Check Out'; document.form1.submit();"/>
<input type="hidden" name="action">
</form>
</body>
</html>

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sompol_kiatkamolchaiCommented:
I just give you some part of sample application if you need more please feel free to ask from me.
Gar04Author Commented:
hey sompol,
can you explain logically how the code works and how it interacts with the other code a little,
as i am a little confused with it right now???
Gaz
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

drpinaCommented:
Gaz, if I understood what you want to do, here's something that should work:

<%
        // ... previous code to make the query
        String siteId = rs.getString("SiteID");
%>
...
<form action="another.jsp">
      <td height="10"><div align="center"><input type="text" name="textfield" value="<%= siteId %>"</div></td>
...
</form>

Then, as part of "another.jsp" code:
<%
...
Bean5.setSiteId(request.getParameter("textfield"));

%>
sompol_kiatkamolchaiCommented:
My code is a sample for book shopping store.

DatabaseConnection.java
================
this class provide a method to get Connection.

Book.java
=======
this class provide a method listAll which query data from database and return as a list of data by using class Vector

BookBean.java
==========
this class is used as a java bean for encapsulating data to a bean.

ShoppingCartServlet.java
================
this servlet work as a cgi that handle any request submit from shopping.jsp

shopping.jsp
========
this jsp provide user interface, they can add book to shopping cart and display the summary of their cart in the bottom part of the page.

If you would like to run this application, you need to create table in database by using this schema.

Table Book
Column Name             Data Type
=========            =======
ID                               numeric
NAME                          varchar
PRICE                          double

And then change database driver, url, username, password in DatabaseConnection.java

:)
sompol_kiatkamolchaiCommented:
For my sample application
I am going to explain MVC in more detail.
MVC --> Model-View-Controller
this model separate application in to three component which would be easier to maintain and develop.
Model --> Business Model, Data Model represent by Book.java,BookBean.java
View --> User Interface (JSP)
Controller --> Control the flow of application by using Servlet.

After reiview your code I see that you use resultset in JSP, I think it should be better to move that to javabean(like Book.java in my sample) and return as a list of data instead.

If you agree that MVC is good and you want to learn it more, I suggest you to look at Struts which is a very good framework to do MVC in web application.

Hope this help.
Gar04Author Commented:
thanks sompol
this has helped a lot
i managed to get my application working
it does not adhere exactly to MCV model you suggested
but it does use a good deal of the design strategy
because i use JSP and JavaBeans
i guess that the java beans communicate with servlets in the background

can this be called MCV???
thank you for the explanation, i will take your advise about struts!!

Gaz
:)
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JSP

From novice to tech pro — start learning today.