Solved

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

Posted on 2004-08-03
7
1,639 Views
Last Modified: 2010-08-05
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
0
Comment
Question by:Gar04
  • 4
  • 2
7 Comments
 
LVL 11

Accepted Solution

by:
sompol_kiatkamolchai earned 400 total points
Comment Utility
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>
0
 
LVL 11

Expert Comment

by:sompol_kiatkamolchai
Comment Utility
I just give you some part of sample application if you need more please feel free to ask from me.
0
 

Author Comment

by:Gar04
Comment Utility
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
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

Assisted Solution

by:drpina
drpina earned 100 total points
Comment Utility
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"));

%>
0
 
LVL 11

Assisted Solution

by:sompol_kiatkamolchai
sompol_kiatkamolchai earned 400 total points
Comment Utility
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

:)
0
 
LVL 11

Expert Comment

by:sompol_kiatkamolchai
Comment Utility
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.
0
 

Author Comment

by:Gar04
Comment Utility
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
:)
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

This article explains in simple steps how to renew expiring Exchange Server Internal Transport Certificate.
Describes a method of obtaining an object variable to an already running instance of Microsoft Access so that it can be controlled via automation.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now