aspose file tools*
The moose likes Servlets and the fly likes How Do you pass data from the DataBase class back to the servlet? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "How Do you pass data from the DataBase class back to the servlet?" Watch "How Do you pass data from the DataBase class back to the servlet?" New topic
Author

How Do you pass data from the DataBase class back to the servlet?

Raymond Gillespie
Ranch Hand

Joined: Oct 08, 2012
Posts: 135
I have a JSP file that takes in several inputs. I then have a servlet that uses the request.getParameter to get the data from the JSP file. It then calls a method in my database class passing it the values. The database method then uses these values to search the database. Once I have the ResultSet, then what? I thought I could just write a class and store the data in an object and then return the object back to the servlet, but that doesn't seem to work or I don't know how to do it properly. After thinking about it, I am not sure that would work anyway. If I am using while(rs.next()), wouldn't it just replace the first row of data with the second row, so on and so forth, if there were more than one row return? I think using JavaBeans would be the solution but I don't quite understand it or how it works. I have been reading about it but still need to wrap my head around it if that is the way to do it.


So I ask the good people here, please help me figure this out. Many thanks to anyone taking a look at this.

Here is the code in the servlet


Here is the database class code
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61764
    
  67

Raymond Gillespie wrote:I thought I could just right [sic] a class and store the data in an object and then return the object back to the servlet

Yup. That's the right thing to do.

After thinking about it, I am not sure that would work anyway.

Of course it would; done right.

If I am using while(rs.next()), wouldn't it just replace the first row of data with the second row, so on and so forth, if there were more than one row return? I think using JavaBeans would be the solution but I don't quite understand it or how it works.

You create a List of beans; one for each row.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Raymond Gillespie
Ranch Hand

Joined: Oct 08, 2012
Posts: 135
So how do I create the list of Beans? This is what I don't understand.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61764
    
  67

Let's say your bean is of class Something. To create a list of somethings:
To add a something to the list:
You would create an instance of Something for each row in the result set and add it to the list.

This is all pretty basic Java; is it new to you? (It helps us help you to know where you are on the learning curve.)
Raymond Gillespie
Ranch Hand

Joined: Oct 08, 2012
Posts: 135
Bear Bibeault wrote:Let's say your bean is of class Something. To create a list of somethings:
To add a something to the list:
You would create an instance of Something for each row in the result set and add it to the list.

This is all pretty basic Java; is it new to you? (It helps us help you to know where you are on the learning curve.)



I'm fairly new to Java. I'm not sure that I would say that I am a novice but pretty close it it. I have been playing around with it off and on for the past year or so. I am far better with JavaScript and PHP although I wouldn't call myself advanced in those either.

So I think the first thing I need to do is make the Flights class I created into a Beans class. Would you say this is correct?

Then I could do something like this?



What I still don't understand is how to properly return the ArrayList back to the servlet that calls this method.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61764
    
  67

Yup, pretty much. Though the class should be named Flight, not Flights. An instance only represents one flight, correct?
Raymond Gillespie
Ranch Hand

Joined: Oct 08, 2012
Posts: 135
Bear Bibeault wrote:Yup, pretty much. Though the class should be named Flight, not Flights. An instance only represents one flight, correct?


Yes, an instance only represents one flight. Of course when the user searches, there could be more than one instance in the database that meets the search criteria.

To better phrase my last question. I am not sure how to handle/accept what is returned to the servlet from the database class.

This is the bit of code that is calling the database method to do the search and return.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61764
    
  67

Raymond Gillespie wrote:Yes, an instance only represents one flight. Of course when the user searches, there could be more than one instance in the database that meets the search criteria.

Right. That's what the list if for.

To better phrase my last question. I am not sure how to handle/accept what is returned to the servlet from the database class.

What do you want to do with it?

This is the bit of code that is calling the database method to do the search and return.

Is that in the servlet? You should not be handling SQLExceptions in the servlet. That should have been handled by the lower-level code.
Raymond Gillespie
Ranch Hand

Joined: Oct 08, 2012
Posts: 135
Bear Bibeault wrote:
Raymond Gillespie wrote:Yes, an instance only represents one flight. Of course when the user searches, there could be more than one instance in the database that meets the search criteria.

Right. That's what the list if for.

To better phrase my last question. I am not sure how to handle/accept what is returned to the servlet from the database class.

What do you want to do with it?


I need to get the data from the data base via the database class, return it to the servlet and then have the servlet send it to a JSP page to be displayed to the user.
I can't figure out how to accept the return from the DBClass.

This is the method call. What do I do to accept what this returns?



Bear Bibeault wrote:
This is the bit of code that is calling the database method to do the search and return.

Is that in the servlet? You should not be handling SQLExceptions in the servlet. That should have been handled by the lower-level code.

Yes it is in the servlet. I removed the try catch. At some point Eclipse was showing an error and that made it go away.

So now I have another issue that I don't understand. The search criteria I enter will return two rows in the database. When I loop through the ArrayList, it only gives me:

airline.javas.Flights@6f454f66
airline.javas.Flights@2f5fea9c

What am I doing wrong here?
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61764
    
  67

Raymond Gillespie wrote:
This is the method call. What do I do to accept what this returns?

If the method returns the list of Flight instances:

Yes it is in the servlet. I removed the try catch. At some point Eclipse was showing an error and that made it go away.

Yes, you need to deal with the SQLExceptions, but they should be dealt with at a lower level, perhaps throwing a less specific exception if need be. You servlet should never ever have to import anything from the SQL packages.

When I loop through the ArrayList, it only gives me:

airline.javas.Flights@6f454f66
airline.javas.Flights@2f5fea9c

What am I doing wrong here?

Nothing. Those are the two flight instances. What you are seeing is the output created by the default implementation of toString().

Please take this as constructive, but there is a lot of basic Java here that it is assumed you have under your belt before diving off into servlets; which is rather an advanced topic. Unless you have to be doing this for your job, I recommend you get a better handle on basic Java prior to tackllng servlets and JDBC.
Raymond Gillespie
Ranch Hand

Joined: Oct 08, 2012
Posts: 135
Bear Bibeault wrote:
Raymond Gillespie wrote:
This is the method call. What do I do to accept what this returns?

If the method returns the list of Flight instances:

Yes it is in the servlet. I removed the try catch. At some point Eclipse was showing an error and that made it go away.

Yes, you need to deal with the SQLExceptions, but they should be dealt with at a lower level, perhaps throwing a less specific exception if need be. You servlet should never ever have to import anything from the SQL packages.

When I loop through the ArrayList, it only gives me:

airline.javas.Flights@6f454f66
airline.javas.Flights@2f5fea9c

What am I doing wrong here?

Nothing. Those are the two flight instances. What you are seeing is the output created by the default implementation of toString().

Please take this as constructive, but there is a lot of basic Java here that it is assumed you have under your belt before diving off into servlets; which is rather an advanced topic. Unless you have to be doing this for your job, I recommend you get a better handle on basic Java prior to tackllng servlets and JDBC.


I certainly realize a lot of this is basic Java. Unfortunately this is what I have been thrown into so I am trying to learn everything at once. Thank you very much for talking me through some of this.


Nothing. Those are the two flight instances. What you are seeing is the output created by the default implementation of toString().


So from you statement here, it sounds like I may need to override the default toString() to get the data stored in the object? Is this something I do in the class?
So
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61764
    
  67

Ah, so you've been thrown into the swamp of alligators, eh? Yeah, been there.

You'd only override toString() if you have a need to. That need could be for important business reasons, or just to have readable logging (which is what you seems to be doing here).

So yes, it's fine to override toString() (be sure to use @Override) to emit what makes the most sense for the class.
Raymond Gillespie
Ranch Hand

Joined: Oct 08, 2012
Posts: 135
Bear Bibeault wrote:Ah, so you've been thrown into the swamp of alligators, eh? Yeah, been there.

You'd only override toString() if you have a need to. That need could be for important business reasons, or just to have readable logging (which is what you seems to be doing here).

So yes, it's fine to override toString() (be sure to use @Override) to emit what makes the most sense for the class.


I think that is what I am trying to do anyway. I am trying to learn how to get data from a user, search the database for it, and if a result is returned, display it to the user on a JSP page. Now to figure out how to display the output.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61764
    
  67

Once you have the List in the servlet (returned from your call to the model class that fetched it from the DB) you:

  • Set the list as a scoped variable in request scope using request.setAttribute(). Be sure to give it a good name such as flights or flightList.
  • Forward the request to the JSP with the request dispatcher.
  • In the JSP, reference the list by the scoped variable name that you gave it.
  • Use the <c:forEach> JSTL tag to iterate over the list.
  • In the body of the forEach, use <c:out> and the EL (expression Language) to display the flight details in the HTML.
  • Bear Bibeault
    Author and ninkuma
    Marshal

    Joined: Jan 10, 2002
    Posts: 61764
        
      67

    I also recommend that newcomers to JSP and servlets read these articles:
  • The Secret Life of JSPs
  • The Front Man

  • Raymond Gillespie
    Ranch Hand

    Joined: Oct 08, 2012
    Posts: 135
    So here is where I am now.

    I used setAttribute() and getRequestDispatcher as you said in the servlet.



    I then went to the JSP file and added this




    And now I get an exception and have no idea why.

    Bear Bibeault
    Author and ninkuma
    Marshal

    Joined: Jan 10, 2002
    Posts: 61764
        
      67

    One thing at a time: what is the following doing in the JSP?

    No scriptlets in a JSP! Ever! (And certainly not in one where the JSTL is also being used).
    Bear Bibeault
    Author and ninkuma
    Marshal

    Joined: Jan 10, 2002
    Posts: 61764
        
      67

    Raymond Gillespie wrote:


    You don't show in the above what flightList is declared as, so it's hard to know if: is correct. But I'm betting it's not.
    Raymond Gillespie
    Ranch Hand

    Joined: Oct 08, 2012
    Posts: 135
    Bear Bibeault wrote:One thing at a time: what is the following doing in the JSP?

    No scriptlets in a JSP! Ever! (And certainly not in one where the JSTL is also being used).


    I thought I needed that to retrieve the flightList but I guess not huh.
    Raymond Gillespie
    Ranch Hand

    Joined: Oct 08, 2012
    Posts: 135
    Bear Bibeault wrote:
    Raymond Gillespie wrote:


    You don't show in the above what flightList is declared as, so it's hard to know if: is correct. But I'm betting it's not.


    I was looking through a book I have and didn't quite understand the proper way to do this.

    This is in the servlet.


    And of course this is the JSP

    ------------------------------------------------EDIT----------------------------------------------------------------------------------

    I thought I found my error, or maybe I did find one of them.


    Changed it to
    Bear Bibeault
    Author and ninkuma
    Marshal

    Joined: Jan 10, 2002
    Posts: 61764
        
      67

    Raymond Gillespie wrote:I thought I needed that to retrieve the flightList but I guess not huh.

    OK, I understand that you are drinking from a firehose, and I'm going to try and help as much as I can. To such, I'll be asking some questions about your thought process and reasoning about things, That'll help us help you better.

    So, why did you think you needed this? It's important to understand what you were thinking.
    Bear Bibeault
    Author and ninkuma
    Marshal

    Joined: Jan 10, 2002
    Posts: 61764
        
      67

    Raymond Gillespie wrote:This is in the servlet.

    OK, so the scoped variable is a List of Flight.

    <c:forEach var="list" items="${flightList.list}">


    OK, another "what were you thinking?" question. Why the .list suffix? What, under heaven and earth, would make you add .list to the name of the scoped variable?
    Raymond Gillespie
    Ranch Hand

    Joined: Oct 08, 2012
    Posts: 135
    So, why did you think you needed this? It's important to understand what you were thinking.


    The reason I thought that I needed that is because looking at the book I have it showed it that way, although when I looked closer, it was comparing JSP code with JSTL with scripting using scriptlets.

    Plus it sort of made sense to use it to me. I thought that if I set it in the servlet, it made sense to get it in the JSP in the same way you can use a setter and getter in a class.


    OK, another "what were you thinking?" question. Why the .list suffix? What, under heaven and earth, would make you add .list to the name of the scoped variable?


    Again looking at the example in the book it shows:


    Bear Bibeault
    Author and ninkuma
    Marshal

    Joined: Jan 10, 2002
    Posts: 61764
        
      67

    Raymond Gillespie wrote:The reason I thought that I needed that is because looking at the book I have it showed it that way, although when I looked closer, it was comparing JSP code with JSTL with scripting using scriptlets.

    Right, because you are using modern JSP with the JSTL and EL, anytime you see anything starting with <% think "vacuum tubes", "rotary phones", "engine cranks" and other obsolete things that belong in a museum and nowhere else.

    Plus it sort of made sense to use it to me.

    Even better -- you don't need to do anything. You just reference it in the EL.

    Again looking at the example in the book it shows:

    Copying without understanding, and worse, just guessing, is going to be your worst enemy. I recommend getting out of that habit. That example, ${cart.items}, shows how to get the items property of a scoped variable named cart (items is presumed to be a List or array)]. In your case, the scoped variable is a List which is what you want to iterate over, so just ${flightList}. A List has no property named list, so the suffix is nonsense.

    Make sense? So what's next?

    Bear Bibeault
    Author and ninkuma
    Marshal

    Joined: Jan 10, 2002
    Posts: 61764
        
      67

    <c:forEach var="list" list="${flightList}">


    Also, list is not a good name for the var. the var names the scoped variable within the loop that represents the current List item. In your case, that's a Flight instance, so var="flight" makes a lot more sense.
    Raymond Gillespie
    Ranch Hand

    Joined: Oct 08, 2012
    Posts: 135
    I don't know what's next. I just do not understand how the for each loop works or what each part of it means. I realize that this should be a very simple concept but I just can't seem to grasp how it works.
    Bear Bibeault
    Author and ninkuma
    Marshal

    Joined: Jan 10, 2002
    Posts: 61764
        
      67

    I actually order the forEach tag slightly differently, which I find makes it more readable:Now it reads like: "for each item in flightList create a var named flight".

    The body of the forEach is repeated once for each item in the List. Each time, the current item (in your case, a Flight instance) is referenced by the scoped variable flight.

    So if the List had three items, the body would repeat three times, once for each flight.

    So far, so good?
    Raymond Gillespie
    Ranch Hand

    Joined: Oct 08, 2012
    Posts: 135
    Raymond Gillespie wrote:I don't know what's next. I just do not understand how the for each loop works or what each part of it means. I realize that this should be a very simple concept but I just can't seem to grasp how it works.




    EDIT

    I thought I may have made sense of it but maybe not.



    So "var" is the scope variable? Similar to "i" in most regular for loops? "items" points to the variable that contains the data that we want to iterate over and display?

    I tried the above and while I get no error, I get no data displayed to the page either.

    Raymond Gillespie
    Ranch Hand

    Joined: Oct 08, 2012
    Posts: 135
    Bear Bibeault wrote:I actually order the forEach tag slightly differently, which I find makes it more readable:Now it reads like: "for each item in flightList create a var named flight".

    The body of the forEach is repeated once for each time in the List. Each time, the current item (in your case, a Flight instance) is referenced by the scoped variable flight.

    So if the List had three items, the body would repeat three times, once for each flight.

    So far, so good?


    It looks like we were adding a post at about the same time. Yes, this makes sense so far.
    Bear Bibeault
    Author and ninkuma
    Marshal

    Joined: Jan 10, 2002
    Posts: 61764
        
      67

    Raymond Gillespie wrote:
    <td><c:out value="${flight.departure_city}"/></td>

    Here's we get into "bean theory".

    The EL operates on beans. And naming by convention is an important part of beans. So "departure_city" isn;t going to cut it. Your bean should have a getter such as "getDepartureCity()" defined -- and yes, this is mandatory. Not optional. Not maybe. Mandatory. Each property you want to access must have a getter. Must.

    Then the rule is that the property name represented by the getter is formed by dropping the "get" and lowercasing the first letter of what is left. In this case, the property name would be departureCity. Again, this is the rule. A hard and fast one. No getting around it.

    So, we end up with:

    Head explode yet?
    Raymond Gillespie
    Ranch Hand

    Joined: Oct 08, 2012
    Posts: 135
    Bear Bibeault wrote:
    Raymond Gillespie wrote:
    <td><c:out value="${flight.departure_city}"/></td>

    Here's we get into "bean theory".

    The EL operates on beans. And naming by convention is an important part of beans. So "departure_city" isn;t going to cut it. Your bean should have a getter such as "getDepartureCity()" defined -- and yes, this is mandatory. Not optional. Not maybe. Mandatory. Each property you want to access must have a getter. Must.

    Then the rule is that the property name represented by the getter is formed by dropping the "get" and lowercasing the first letter of what is left. In this case, the property name would be departureCity. Again, this is the rule. A hard and fast one. No getting around it.

    So, we end up with:

    Head explode yet?


    Not yet but close. That is the way I had it to start with and still get nothing. Cold something else be wrong with my Bean class?


    The code for the departure_city getter copied straight from the class


    copied straight from JSP file



    Bear Bibeault
    Author and ninkuma
    Marshal

    Joined: Jan 10, 2002
    Posts: 61764
        
      67

    I will repeat myself, and cannot stress this enough: you must, must, must, must follow naming conventions. No one, no one, should use underscores in method names. No one.

    So getDepartureCity(). No choices. No wiggle space. No room for artistic expression. Follow the conventions. Beans love convention. Beans thrive on convention. Beans fail in the absence of convention.

    Then: ${flight.departureCity}
    Bear Bibeault
    Author and ninkuma
    Marshal

    Joined: Jan 10, 2002
    Posts: 61764
        
      67

    P.S. Same for variable names, but it's less critical there. Java convention is to use camel case, not underscores. Your code becomes surprisingly unreadable when you fail to follow expected naming conventions. But, again, with beans, it's mandatory, not a simple matter of style.
    Raymond Gillespie
    Ranch Hand

    Joined: Oct 08, 2012
    Posts: 135
    Bear Bibeault wrote:P.S. Same for variable names, but it's less critical there. Java convention is to use camel case, not underscores. Your code becomes surprisingly unreadable when you fail to follow expected naming conventions. But, again, with beans, it's mandatory, not a simple matter of style.



    So are you saying that it is mandatory for variables to be camel case and not underscores for Beans also?

    I changed all variables, getters, and setters to camel case, but I am still getting the same result which is one empty table row. It's like the for loop isn't even running the two time it should run.
    Bear Bibeault
    Author and ninkuma
    Marshal

    Joined: Jan 10, 2002
    Posts: 61764
        
      67

    Raymond Gillespie wrote:So are you saying that it is mandatory for variables to be camel case and not underscores for Beans also?

    No. With beans it's all about the setters and getters. But, and this is a big but, there is no sane reason to not follow the conventions for all elements. None.

    one empty table row. It's like the for loop isn't even running the two time it should run.

    Time to post the relevant updated code.
    Raymond Gillespie
    Ranch Hand

    Joined: Oct 08, 2012
    Posts: 135
    So here is the JSP code

    The code from the servlet


    The bean class

    Bear Bibeault
    Author and ninkuma
    Marshal

    Joined: Jan 10, 2002
    Posts: 61764
        
      67

    Not seeing anything awry at first inspection...

    So can I assume that the logging output from the servlet shows the expected data is in the list? (Btw, you ought to investigate real logging with java.util.logging or Log4J).

    And you have looked at the HTML sent to the browser (View Source), not just what's being displayed?

    Another "by the way": your for-loop in the servlet should be using the more modern version of the for loop:

    It has much simpler (hence, easier to read) syntax, doesn't require a get() from the list, and note its resemblance to the JSTL forEach tag?

    Raymond Gillespie
    Ranch Hand

    Joined: Oct 08, 2012
    Posts: 135
    Bear Bibeault wrote:Not seeing anything awry at first inspection...

    So can I assume that the logging output from the servlet shows the expected data is in the list? (Btw, you ought to investigate real logging with java.util.logging or Log4J).

    And you have looked at the HTML sent to the browser (View Source), not just what's being displayed?

    Another "by the way": your for-loop in the servlet should be using the more modern version of the for loop:

    It has much simpler (hence, easier to read) syntax, doesn't require a get() from the list, and note its resemblance to the JSTL forEach tag?


    While I just noticed a bug concerning ID and date, data is getting to the arraylist from the database and back to the servlet.
    This if from viewing the page source. It looks like it is getting there also but something is not right.
    Bear Bibeault
    Author and ninkuma
    Marshal

    Joined: Jan 10, 2002
    Posts: 61764
        
      67

    Wait a minute! You are seeing the JSTL code in the browser?

    If so, that means that the JSTL isn't even being evaluated. Remember, all that JSP stuff happens on the server, and what is sent to the browser should be plain old HTML.

    You did include the directive in the JSP that imports the JSTL, right?

    And placed the JSTL jar files in WEB-INF/lib?
    Raymond Gillespie
    Ranch Hand

    Joined: Oct 08, 2012
    Posts: 135
    Bear Bibeault wrote:
    You did include the directive in the JSP that imports the JSTL, right?

    And placed the JSTL jar files in WEB-INF/lib?



    Not sure what to include to import those. I will dig that up.

    Where do I get the JSTL jar files?
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: How Do you pass data from the DataBase class back to the servlet?