Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2004-08-03
7
Medium Priority
?
1,699 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
7 Comments
 
LVL 11

Accepted Solution

by:
sompol_kiatkamolchai earned 1600 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Assisted Solution

by:drpina
drpina earned 400 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 1600 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
Whoever said that “a picture is worth one thousand words” observed a fact that can dramatically affect your marketing success. Most people tend to learn visually, so many publishers commonly acknowledge the effectiveness of visual learning by using…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

722 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