Solved

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

Posted on 2004-08-03
7
1,651 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
ID: 11711760
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
ID: 11711761
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
ID: 11714896
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Assisted Solution

by:drpina
drpina earned 100 total points
ID: 11721696
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
ID: 11722709
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
ID: 11722736
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
ID: 11738801
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Can I clean log of  running tomcat 7 server ? 3 125
eclipse problems view not showing all the time 4 87
SimpleDateFormat.parse examples 19 87
spring example non maven 4 82
Microsoft Office Picture Manager was included in Office 2003, 2007, and 2010, but not in Office 2013. Users had hopes that it would be in Office 2016/Office 365, but it is not. Fortunately, the same zero-cost technique that works to install it with …
Large Outlook files lead to various unwanted errors and corruption issues. Furthermore, large outlook files can also make Outlook take longer to start-up, search, navigate, and shut-down. So, In this article, i will discuss a method to make your Out…
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…
Need to grow your business through quality cloud solutions? With everything required to build a cloud platform and solution, you may feel like the distance between you and the cloud is quite long. Help is here. Spend some time learning about the Con…

914 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

21 Experts available now in Live!

Get 1:1 Help Now