facebook

[Struts] Define Action to collect database data for jsp

  1. MyEclipse IDE
  2.  > 
  3. Off Topic
Viewing 11 posts - 1 through 11 (of 11 total)
  • Author
    Posts
  • #221587 Reply

    RUFFIE
    Member

    I’m a struts newb, so this might be quite easy. All the tutorials I’ve read or either more complex or they use the jsp itself to generate a list of data.

    I want my action class to retrieve my data for me from the db and send in to the jsp page.

    So far I’ve got this (which doesn’t work ofcourse):
    I wanna use the following method in my CustomerDAO.java:

    
        /**
         * getItemList() returns list of all <code>Customer</code> objects stored in the database. 
         * 
         * @return <code>List</code> of <code>Customer</code> objects.
         */
        public List getCustomerList()
        {
            /*
             * Use the ConnectionFactory to retrieve an open
             * Hibernate Session.
             * 
             */
            Session session = null;
     
            try
            {
                session = HibernateUtil.getSession();
                /*
                * Build HQL (Hibernate Query Language) query to retrieve a list
                * of all the items currently stored by Hibernate.
                 */
                Query query = session.createQuery("select Customer from com.frontier.hibernate.Customer Customer order by Customer.customerid");
                return query.list();
     
            }
            catch (HibernateException e)
            {
                System.err.println("Session not getted!" + e.getMessage());
                throw new RuntimeException(e);
            }
            /*
             * Regardless of whether the above processing resulted in an Exception
             * or proceeded normally, we want to close the Hibernate session.  When
             * closing the session, we must allow for the possibility of a Hibernate
             * Exception.
             * 
             */
            finally
            {
                if (session != null)
                {
                    try
                    {
                        session.close();
                    }
                    catch (HibernateException e)
                    {
                        System.err.println("Hibernate Exception" + e.getMessage());
                        throw new RuntimeException(e);
                    }
     
                }
            }
        }
    

    My getAccountAction.java has:

    
    public ActionForward execute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) {
     
            List customerList = CustomerDAO.getInstance().getCustomerList();
            request.setAttribute("customers", customerList);
            return mapping.findForward("success");
        }
    

    And my struts-config has the following action mapping:

    
    <action path="/accOptions" type="com.frontier.action.doTiles">
             <forward name="success" path="account" />
          </action>
          <action path="/getAccountAction" type="com.frontier.action.getAccountAction">
             <forward name="success" path="/accOptions.do" />
          </action>
    

    My simple jsp has:

    
    <logic:iterate name="customers" id="cus">
     
    
       
       <table>
       <tr><td>Name:</td><td><bean:write name="cus" property="name" /></td></tr>
       <tr><td>Address:</td><td><bean:write name="cus" property="address" /></td></tr>
       <tr><td>City:</td><td><bean:write name="cus" property="city" /></td></tr>
       <tr><td>Number of Mortgages:</td><td><bean:write name="cus" property="noofmortgages" /></td></tr>
                 
                 
                 
       </table>
    </logic:iterate>
    

    So obviously I’m doing something wrong or forgetting something. Can anyone point me out what?

    My tomcat error logging isn’t configured well, so I’ll give you what I get on screen. I’m rather unsure as to what action to call first (getAccountAction or accOptions – the first forwards to the second that calls on a jsp, this is where my data should be – sounds complicated but it’s for Tiles).

    When calling on getAccountAction the FIRST i get:

    
    root cause
     
    java.lang.ExceptionInInitializerError
        com.frontier.hibernate.HibernateUtil.<clinit>(HibernateUtil.java:39)
        com.frontier.hibernate.service.CustomerDAO.getCustomerList(CustomerDAO.java:195)
        com.frontier.action.getAccountAction.execute(getAccountAction.java:46)
        org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
        org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
        org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
        org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:507)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    

    When i refresh the same action/page it turns to:

    
    exception
    
    javax.servlet.ServletException: Servlet execution threw an exception
    
    root cause
    
    java.lang.NoClassDefFoundError
        com.frontier.hibernate.service.CustomerDAO.getCustomerList(CustomerDAO.java:195)
        com.frontier.action.getAccountAction.execute(getAccountAction.java:46)
        org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
        org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
        org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
        org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:507)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    

    And when calling on accOptions.do i get:

    
    [ServletException in:/jsp/accOptions.jsp] Cannot find bean customerList in scope request' javax.servlet.jsp.JspException: Cannot find bean customerList in scope request at org.apache.struts.util.RequestUtils.lookup(RequestUtils.java:940) at org.apache.struts.taglib.logic.IterateTag.doStartTag(IterateTag.java:277) at org.apache.jsp.jsp.accOptions_jsp._jspService(org.apache.jsp.jsp.accOptions_jsp:76) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:99) at javax.servlet.http.HttpServlet.service(HttpServlet.java:802) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:325) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:245) at javax.servlet.http.HttpServlet.service(HttpServlet.java:802) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:674) at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:576) at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:501) at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:966) at org.apache.jasper.runtime.PageContextImpl.include(PageContextImpl.java:601) at org.apache.struts.tiles.TilesUtilImpl.doInclude(TilesUtilImpl.java:137) at org.apache.struts.tiles.TilesUtil.doInclude(TilesUtil.java:177) at org.apache.struts.taglib.tiles.InsertTag.doInclude(InsertTag.java:756) at org.apache.struts.taglib.tiles.InsertTag$InsertHandler.doEndTag(InsertTag.java:881) at org.apache.struts.taglib.tiles.InsertTag.doEndTag(InsertTag.java:473) at org.apache.jsp.layouts.mslDefaultLayout_jsp._jspx_meth_tiles_insert_2(org.apache.jsp.layouts.mslDefaultLayout_jsp:198) at org.apache.jsp.layouts.mslDefaultLayout_jsp._jspService(org.apache.jsp.layouts.mslDefaultLayout_jsp:105) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:99) at javax.servlet.http.HttpServlet.service(HttpServlet.java:802) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:325) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:245) at javax.servlet.http.HttpServlet.service(HttpServlet.java:802) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:674) at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:465) at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:400) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:303) at org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1069) at org.apache.struts.tiles.TilesRequestProcessor.doForward(TilesRequestProcessor.java:274) at org.apache.struts.tiles.TilesRequestProcessor.processTilesDefinition(TilesRequestProcessor.java:254) at org.apache.struts.tiles.TilesRequestProcessor.processForwardConfig(TilesRequestProcessor.java:309) at
     
    etc
    etc
    

    But is my approach correct?

    #221601 Reply

    Riyad Kalla
    Member

    RUFFIE,
    You approach looks really good actually, the problem right off the bat I see is so common with Struts applications that they should include it in the FAQ: you are placing a var (the customer list) into the request, then returning the “success” forward which is itself another Struts action (.do mapping), so what happens is between your first action (getCustomerList) and your JSP page, you are injecting another step of request/response which effectively clears your request so by the time you get to your JSP page, your request with the customer list has already been trashed. You can either:
    a) Make your success forward your JSP page itself (not another .do mapping, but a striaght .jsp mapping) and make sure to have redirect=false so the url for the user doesn’t change and you won’t loose your request scoped var

    OR

    b) put the list in your session, and in your page after displaying it, remove it from the session so it doesn’t take up space.

    I imagine you probably want to do a) more as keeping things exclusively in the request is typically thought of as good bookeeping (unless you need it in the session). As far as the Hibernate query throwing an exception, it is hard to say why… just make sure your classpath is setup properly and the class you are referencing is there.

    #221638 Reply

    RUFFIE
    Member

    Hey rkalla, I haven’t had the tiime to try out your suggestions yet, but you have some good points.
    But there’s one problem, cuz I use Tiles (see that other topic you helped me with) I use the action to load the jsp in my content tile.
    This to reduce the amount of jsp pages. The ones that will put the tiles into the layout won’t be necessary anymore.
    I hope you understand me, I can put an example if you want to, but by calling accOptions.do in my menu tile, I call on DoTiles.java which is an action that will call on my definition by the name “account” (see the action mapping) in my tiles-defs, which is set to open the page accOptions.jsp in the content tile.
    This is said to be the most efficient use of Tiles, cuz of reduced jsp pages and maximum reusablity or so they say.

    Anyways, I don’t think I can use option a) as where to call the jsp directly in this way of using Tiles, cuz that wouldn’t fit this way of using Tiles, wouldn’t it.
    So I was thinking, can I in someway with one action class do both getAccountAction and doTiles.
    So as in, when i click on accOptions.do it calls on the action to make the list, call upon my account definition and show the results in that jsp page? If so, how do I do that?

    OR

    just have the accOptions.do as it is, it calls on the accOptions.jsp and that page uses the getAccountAction class, something like jsp:useBean but with Struts tags? Is this also possible and how?

    #221639 Reply

    RUFFIE
    Member

    Oh yeah one more thing..about classpath set up properly. I don’t really understand that, how to check that and how to fix that.. 🙁

    #221646 Reply

    Riyad Kalla
    Member

    RUFFIE,
    We are running into the limit of my Struts knowledge, I never got very advanced with Tiles but the repost/cleared-request problem is one of the biggest reasons Struts drove me crazy (and why I’m using JSF now). However, I would say that the Struts-user mailing list was one of the most helpful lists I participated in; I would highly suggest that you subscribe and try and simplify your question into the form:

    * This is my setup …
    * I use Tiles like this …
    * My problem is that my request is cleared before I display my page because of this …

    Then post the question and see if the list can help you. Sorry I can’t help more.

    Oh yeah one more thing..about classpath set up properly. I don’t really understand that, how to check that and how to fix that.. 🙁

    You mean in Eclipse? Just navigate to your Project properties > Java Build Path > Libraries (tab)

    From your error it looks like your “Customer” class is missing or cannot be found, you might narrow down where that is located and if you have added to your classpath correctly.

    #263030 Reply

    optimalsoft
    Member

    Hi,

    I have been stuck with a similar problem when doing the “Struts Quickstart — MyEclipse Enterprise Workbench” sample and am wondering whether I have made a mistake somewhere or they simply overlooked this problem. If the latter, I strongly suggest you update your help files, because I have wasted lot of time looking for the error in my code.

    My second question is if there has been a correction in the Struts framework regarding this issue, or we are supposed to call the destination jsp directly every time we deal with attributes in request scope. I had the feeling that the whole point of frameworks like Struts was to be able to externalize all this navigation between pages, so having to call them directly would certainly be a step backwards.

    Anyway, thanks for your help so far.

    Mariano

    #263038 Reply

    Riyad Kalla
    Member

    Mariano,
    It’s hard to see where the error might be in your code or specifically what the error is (e.g. “When I click login, I get XYZ error”). As far the tutorial we’ve had many many thousand people run through it so I am not aware of any glaring errors in it (although that’s not to say some portions of it couldn’t be clarified, that’s always the case)

    #263147 Reply

    optimalsoft
    Member

    I was referring to the issue you describe here:

    @support-rkalla wrote:

    RUFFIE,
    You approach looks really good actually, the problem right off the bat I see is so common with Struts applications that they should include it in the FAQ: you are placing a var (the customer list) into the request, then returning the “success” forward which is itself another Struts action (.do mapping), so what happens is between your first action (getCustomerList) and your JSP page, you are injecting another step of request/response which effectively clears your request so by the time you get to your JSP page, your request with the customer list has already been trashed. You can either:
    a) Make your success forward your JSP page itself (not another .do mapping, but a striaght .jsp mapping) and make sure to have redirect=false so the url for the user doesn’t change and you won’t loose your request scoped var

    OR

    b) put the list in your session, and in your page after displaying it, remove it from the session so it doesn’t take up space.

    I imagine you probably want to do a) more as keeping things exclusively in the request is typically thought of as good bookeeping (unless you need it in the session).

    Does this mean that it’s not possible to pass attributes within a request scope when using redirections in xml-config? If so, the sample I mention in the MyEclipse does exactly that and displays the userName in the main page, after the login. When I have tried that, I get an error message that the bean “userName” was not found…

    #263156 Reply

    Riyad Kalla
    Member

    You can do that as long as it’s only 1 redirection, if you do two back to back, you will clear the request scope on the second redirect and as soon as you get where you want to go, it’s been reset and you have no object.

    If you’d like, you can export your project to a ZIP (File > Export > Archive) and email it to me, support@genuitec.com ATTN Riyad, with a link to this thread so I know why I’ m getting it, and I’ll hvae a look.

    #263316 Reply

    optimalsoft
    Member

    @support-rkalla wrote:

    You can do that as long as it’s only 1 redirection, if you do two back to back, you will clear the request scope on the second redirect and as soon as you get where you want to go, it’s been reset and you have no object.

    If you’d like, you can export your project to a ZIP (File > Export > Archive) and email it to me, support@genuitec.com ATTN Riyad, with a link to this thread so I know why I’ m getting it, and I’ll hvae a look.

    Thanks. Would you care to detail a bit more what is a double redirection? Is it when you select “redirect=true” in the forward?

    #263325 Reply

    Riyad Kalla
    Member

    Meaning that two redirects are performed, so the client is updated twice, meaning two requests cycles are performed.

Viewing 11 posts - 1 through 11 (of 11 total)
Reply To: [Struts] Define Action to collect database data for jsp

You must be logged in to post in the forum log in