• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 428
  • Last Modified:

Presenting Data In JSPp From Database Query Using Struts

Hi,

I am trying to learn struts within the Websphere env, I have an insert into a database working fine but now i want to read the data back and display it. I have the following components;

*) I have generated my data access beans "CdAllSel" and "CdAllSelRow"
*) Query Entry Form to start the event called "cdAllSel.jsp"
*) This fires an Action Class called "CdAllSelAction"
*) The Action Class calls "error.jsp" for exceptions
*) The Action Class calls "cdAllUpd.jsp" in the event of a success it should display the results found by the query.
*) I have an Action Form Class called "CdAllSelForm"

I beleive I need to place an iterational loop in the success jsp to display the data. I am assuming that the query via the Action Class & Action Fortm all works because I generated this code following the same procedure for the database insert function which works. I am stuck on the syntax, in my success jsp "cdAllUpd.jsp"  I have the following;

<TBODY>
<TR>

     <nested:iterate id="CdAllSelRow" name="CdAllSelRow">
         Code: <nested:write name="CdAllSelRow" property="CD_CODES_CD_CODE"/>
         Desc: <nested:write name="CdAllSelRow" property="CD_CODES_CD_DESC"/>
         Type: <nested:write name="CdAllSelRow" property="CD_CODES_CD_TYPE"/>
     </nested:iterate>

</TR>
</TBODY>

Am I missing an important piece of code or logic here? As I dont know the syntax I am unsure what "id" and "name" should be set to.
0
adlikon
Asked:
adlikon
  • 6
  • 4
  • 4
  • +1
3 Solutions
 
suprapto45Commented:
Hi,

I do not really know about nested:iterate but I normally use logic:iterate and bean:write. Perhaps, you can have some idea by URL below.

http://javaboutique.internet.com/tutorials/StrutsTags/logic_tags2.html

Regards
Dave
0
 
bloodredsunCommented:
I would recommend that you use JSTL. SPecifically c:forEach and c:out, it's much more powerful than the struts tags and also much easier to read (including reading nested collections or properties)
0
 
ucoolCommented:
I agree above to use JSTL, for this case, it looks like:

<TABLE>
<TR>
    table columns title (need added)
</TR>
<c:forEach var="CdAllSelRow" items="CdAllSelRow">
<TR>
    <td><c:out value="${CdAllSelRow.CD_CODES_CD_CODE}"/></td>
    <td><c:out value="${CdAllSelRow.CD_CODES_CD_DESC}"/></td>
     <td><c:out value="${CdAllSelRow.CD_CODES_CD_TYPE}"/></td>
</TR>
</c:forEach>
</TABLE>
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
bloodredsunCommented:
Actually to iterate throught the properties of an actionform in a certain scope you will need to do this

<c:forEach var="requestScope.MyActionForm.cdAllSelRow" items="CdAllSelRow">

where the form is in the request scope, has been called "MyAction" in the struts-config.xml and has a method called getCdAllSelRow() which returns an object that is a map, array, list or collection.

The rest is fine
0
 
adlikonAuthor Commented:
Hi & thanks for the suggestions,

I have copied the code above with the latest "forEach" line. I changed my config.xml to have "request scope" set against the action form "cdAllSellForm" so the code implemented in my result form looks like this;

<TABLE>
      <TBODY>
      </TBODY>
      <TBODY>
                     <TR>
                  <TH align="left" width="140">Code:</TH>
                  <TH align="left" width="235">Name:</TH>
                  <TH align="left" width="381">Type:</TH>
            </TR>
      </TBODY>
<c:forEach var="requestScope.cdAllSelForm.cdAllSelRow" items="CdAllSelRow">
<TR>
    <td><c:out value="${CdAllSelRow.CD_CODES_CD_CODE}"/></td>
    <td><c:out value="${CdAllSelRow.CD_CODES_CD_DESC}"/></td>
    <td><c:out value="${CdAllSelRow.CD_CODES_CD_TYPE}"/></td>
</TR>
</c:forEach>
</TABLE>

but the error jsp gets displayed when I run the query. I used Websphere to generate all the code so its all standard, I have in my Action Form "CdAllSelForm"  methods for all 3 fields so I have "getCd_type", "getCd_desc", "getCd_type" - I do not have a "getCdAllSelRow" method as mentioned in the last suggestion. Should I have  a method in my action form ?

Here is the source of my action form "CdAllSelForm.java";


package invsysstruts.forms;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

/**
 * Form bean for a Struts application.
 * Users may access 3 fields on this form:
 * <ul>
 * <li>cd_code - [your comment here]
 * <li>cd_desc - [your comment here]
 * <li>cd_type - [your comment here]
 * </ul>
 * @version       1.0
 * @author
 */
public class CdAllSelForm extends ActionForm {

      private String cd_code = null;
      private String cd_desc = null;
      private Integer cd_type = null;

      /**
       * Get cd_code
       * @return String
       */
      public String getCd_code() {
            return cd_code;
      }

      /**
       * Set cd_code
       * @param <code>String</code>
       */
      public void setCd_code(String c) {
            cd_code = c;
      }
      /**
       * Get cd_desc
       * @return String
       */
      public String getCd_desc() {
            return cd_desc;
      }

      /**
       * Set cd_desc
       * @param <code>String</code>
       */
      public void setCd_desc(String c) {
            cd_desc = c;
      }
      /**
       * Get cd_type
       * @return Integer
       */
      public Integer getCd_type() {
            return cd_type;
      }

      /**
       * Set cd_type
       * @param <code>Integer</code>
       */
      public void setCd_type(Integer c) {
            cd_type = c;
      }
      /**
      * Constructor
      */
      public CdAllSelForm() {

            super();

      }
      public void reset(ActionMapping mapping, HttpServletRequest request) {

            // Reset values are provided as samples only. Change as appropriate.

            cd_code = null;
            cd_desc = null;
            cd_type = null;

      }
      public ActionErrors validate(
            ActionMapping mapping,
            HttpServletRequest request) {

            ActionErrors errors = new ActionErrors();
            // Validate the fields in your form, adding
            // adding each error to this.errors as found, e.g.

            // if ((field == null) || (field.length() == 0)) {
            //   errors.add("field", new ActionError("error.field.required"));
            // }
            return errors;

      }
}


 If I need to create the method in here can I have a hint at the syntax please ?
0
 
suprapto45Commented:
Hi,

Okay I agree with bloodredsun to use JSTL :).

Can you post your error message here so that we can debug?

Regards
Dave
0
 
ucoolCommented:
Hi,

Using JSTL, make sure in JSP file has:
JSTL 1.0
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
JSTL 1.1
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

JSTL comes in two JARs: jstl.jar and standard.jar
0
 
adlikonAuthor Commented:
Ok I have added the tag at the top of the jsp but also had to include the tags in the project, the web.xml file now shows these and in /WEB-INF/lib I have jstl.jar and under /{Project Name}/Libraries I now have entries such as "jstl.jar" that include packages such as "javax.servlet.jsp.jstl.core" - I am confused why I reference in my project a remote link "http://java.sun.com/jstl/core" when I have what appears to be the files locally after I went to the properties of the project and selected "WEB" and included the jstl tag libraries, Web Sphere then Rebuilt my project.  Why do I reference the remote library, what is the difference?

The JSP compiles and runs but it still jumps to the error jsp, I have tried in debug mode but the debugger just hangs after I select "step into" after starting the query, should it not display the code it reaches on the first step or is there something I am supposed to do?
0
 
suprapto45Commented:
Hi adlikon,

What is the error message?

Regards
Dave
0
 
ucoolCommented:
I think you may try some simple examples which can help you to understand, here is a link you may like to check to may the simple things work:

http://www.developer.com/java/ejb/article.php/1447551
0
 
suprapto45Commented:
Hi,

>>"I am confused why I reference in my project a remote link "http://java.sun.com/jstl/core"

I am not sure on that. If someone can answer it. It would be beneficial to me too :)

regards
Dave
0
 
adlikonAuthor Commented:
OK I will take  a look. I really appreciate all the help  i am getting - there is just so much to understand. In debug mode i do not get any error, when i step into the action on starting my query the debugger hangs, the browser shows the busy indicator stuck on about half way of loading the next step (as i would expect because i assume I am supposed to step through code, but no window is opened to me - all i have get is a question to step into or skip and thats it).

I will take  a look at the example of the tags posted, websphere seems to have taken care of the installation aspect it mentions but i will look at the examples.
0
 
bloodredsunCommented:
>>"I am confused why I reference in my project a remote link "http://java.sun.com/jstl/core"

The remote call means that you have a clean and valid copy of the tld. You can just as easily extract the tlds (c.tld, fmt.tld, sql.tld and x.tld and their runtime counterparts) from standard.jar, as for some curious reason they are not in the jstl.jar. This also means that you do not have to map the tlds in the web.xml to use JSTL but you can just drop in the jars and the taglib ref at the top of the jsp and off you go...

I would temporarily comment out the error page in the web,xmnl so that you get to see the error stacktrace.

Here's some code from a working struts webapp, the actionform and the jsp so hopefully you can see the relationship.

ActionForm
--------------
package examples;

//import standard
import javax.servlet.http.HttpServletRequest;
//import struts
import org.apache.struts.action.*;


public final class TrackingForm extends ActionForm {

      //jobNumber
      private String jobNumber;
      private String jobHTML ;
      private String jobDate ;
      private int jobDays ;
      private boolean jobStatusPresent ;
      private boolean jobStatusPositionOne ;
      private boolean showEmail ;
      private boolean moreThanRoutine ;
      private boolean notRecognised ;


      public TrackingForm() {
            super();
            this.resetFields();
      } // constructor

      //accessors and mutators            
      public String getJobNumber() {      return (this.jobNumber);      }
      public void setJobNumber( final String jobNumber) {this.jobNumber = jobNumber.trim().toUpperCase();      }
      
      public String getJobHTML() {return (this.jobHTML);      }
      public void setJobHTML( final String jobHTML) {this.jobHTML = jobHTML;      }
      
      public String getJobDate() {return (this.jobDate);      }
      public void setJobDate( final String jobDate) {this.jobDate = jobDate;      }      
      
      public int getJobDays() {return (this.jobDays);      }
      public void setJobDays( final int jobDays) {this.jobDays = jobDays;      }      
      
      public void setJobStatusPresent( final boolean pJobStatusPresent){this.jobStatusPresent = pJobStatusPresent;      }
      public boolean isJobStatusPresent(){return (this.jobStatusPresent);      }
      
      public void setJobStatusPositionOne( final boolean pJobStatusPositionOne){this.jobStatusPositionOne = pJobStatusPositionOne;      }
      public boolean isJobStatusPositionOne(){return (this.jobStatusPositionOne);      }
      
      public void setShowEmail( final boolean pShowEmail){this.showEmail = pShowEmail;      }
      public boolean isShowEmail(){return (this.showEmail);      }
      
      public void setMoreThanRoutine( final boolean moreThanRoutine){this.moreThanRoutine = moreThanRoutine;      }
      public boolean isMoreThanRoutine(){return (this.moreThanRoutine);      }
      
      public void setNotRecognised( final boolean notRecognised){this.notRecognised = notRecognised;      }
      public boolean isNotRecognised(){return (this.notRecognised);      }

      /**
       * Called by the framework to validate the user input
       *@param ActionMapping pMapping
       *@param HttpServletRequest pRequest
       *@return ActionErrors
       */
       public ActionErrors validate( final ActionMapping pMapping, final HttpServletRequest pRequest ) {
            ActionErrors errors = new ActionErrors();
            if ( jobNumber == null || jobNumber.length() == 0 ){
                  errors.add( "track" , new ActionError( "errors.tracking.missingjobnumber" ));
            }
          else if ( isValidTrackingCode() ){
                  errors.add( "track" , new ActionError( "errors.tracking.incorrectjobnumber" ));
            }
            return errors;
      }//validate      
            
      public void reset( final ActionMapping pMapping, final HttpServletRequest pRequest) {
            // Clear out the form fields
            resetFields();
      } // reset
      
      protected void resetFields() {
            this.jobNumber = "";
            this.jobHTML = "";
            this.jobStatusPresent = false;
            this.jobStatusPositionOne = false;
            this.showEmail = false ;
      } // resetFields

      /**
       * ourCodeCheck()
       * checks the first 3 characters of the 8 digit jobnumber to
       * ebsure it is our specific 3 letter code
       * @return boolean
       */
      
      protected boolean isValidTrackingCode(){
            return true ;
      }
}


Part of the JSP
--------------------
<%@ page language="java" contentType="text/html" %>
<%@ taglib uri='http://java.sun.com/jstl/core' prefix='c' %>
<%@ taglib uri="/tags/struts-html" prefix="html" %>
...........
...........
<table width="100%" border="0" cellpadding="1" cellspacing="0" bordercolor="#FFFFFF" bgcolor="#C9DCED" class="table">
      <tr>
            <td height="14" align="left" valign="middle" class="tableheadbg">
            <c:choose>
            <c:when test='${requestScope.jobNumberBean.jobStatusPositionOne == true}'>
                  <table width="100%" border="0" cellpadding="3" cellspacing="0" bgcolor="#023D75">
                  <tr>
                  <td id="header1" width="30%" align="left" class="tablehead">Tracking results </td>
                  </tr>
                  </table>
            </c:when>
            <c:otherwise>
                  <table width="100%" border="0" cellpadding="3" cellspacing="0">
                  <tr>
                  <td id="header1" width="30%" align="left" class="tablehead">Time</td>
                  <td id="header2" width="30%" align="left" class="tablehead">Date</td>
                  <td id="header3" width="30%" align="left" class="tablehead">Status</td>
                  </tr>
                  </table>
            </c:otherwise>
            </c:choose>
            </td>
      </tr>
      <tr>
            <td align="left" valign="top" class="table">
            <html:errors property="track"/>
            
            <c:out value='${requestScope.jobNumberBean.jobHTML}'  escapeXml='false' />
            
            </td>
      </tr>
</table>
0
 
adlikonAuthor Commented:
haven't had a chance to continue because of flu, look later this week hopefully
0
 
adlikonAuthor Commented:
Hi,  this is still not all clear to me - which is ok because i am trying to learn it but i need to operate in the most common denominator mode to keep things really simple.

This is what I have;

*) Data access bean "CdAllSel"/"CdAllSelRow"
*) Query Entry Form to start the event called "cdAllSel.jsp" - just a button
*) Action Class called "CdAllSelAction"
*) The Action Class calls "cdAllUpd.jsp" to display the results found by the query.
*) I have an Action Form Class called "CdAllSelForm"

In the Action Class I removed the forward for failure, now I get my result form "cdAllUpd.jsp" displayed but with no results. I am assuming if there was an exception of some kind as I am not trapping it I would see it. Later on I need to work on my forwards logic, but first I want my query to work.

The debugger does not work after I inserted a break point in my Action Class execute function, ut just hangs after I choose to step through.

I have removed all syntax in my result JSP that tries to display the data retrieved as I doubt if the Action/Form is handling the Query correctly. So now I just have the "Foreach" loop and a constant text entry, I would expect this to be displayed for as many records it finds from the query. (I also removed all joins and critera from the query and re-generated my bean)

But as I mentioned the result form does not appear to do a loop of the records found in the query because the constant text that I have used only appears once ie "X", I expected about 20. I beleive my problem is only in the syntax of the Foreach delaration;

<c:forEach var="requestScope.CdAllSelForm.cdAllSelRow" items="CdAllSelRow">

Can someone please tell me what each element here refers to but in relation to the objects I have listed at the start of this paragraph  ,please dont use words like 'container' but for example the name of the function you would expect to exist in my code. - I cant join the dots if I dont know what the dots are...
0
 
bloodredsunCommented:
<c:forEach var="requestScope.CdAllSelForm.cdAllSelRow" items="CdAllSelRow">

requestScope = the request object
CdAllSelForm = your actionform , retrived by calling getAttribute( this ) on the scope above
cdAllSelRow = the method in your form getCdAllSelRow() that returns an object

In the c:forEach, you want to return an object that can be iterated/looped over, so a hashmap, an array or a list or even a collection will work
0
 
adlikonAuthor Commented:
OK - now I think I understand. In My Action form (CdAllSelForm) generated by Websphere it has all the get & set routines for the database/form fields, but I must enter in the code myself that takes the data from the database and makes it available for the JSP (thus using the MVC principle). Any chance you can give me a helping hand here on the syntax for getCdAllSelRow() ?
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 6
  • 4
  • 4
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now