user1888771
user1888771

Reputation: 107

Implementing CRUD services for JSP/Servlet Application - Problems with read operations

I am currently working on a website that incorporates JSP's, servlets and some CRUD database services. I am stuck on the read portion of the CRUD, as I am unable to get the desired effects.

I am connected to a database and am able to insert data from the website without any trouble. What I am trying to do now is to have a select/option box in the JSP call on a row from the database, and to have the corresponding columns of the row translate on the next page. However, I am unable to get more than one row from the option box to appear. The code is listed below.

Bean class:

public class ReadBean {
    protected String title;
    protected String author;
    protected String text;

    public String getTitle() {
        return title;
    }

    public void setTitle(String newTitle) {
        title = newTitle;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String newAuthor) {
        author = newAuthor;
    }

    public String getText() {
        return text;
    }

    public void setText(String newText) {
        text = newText;
    }
}

Controller:

@WebServlet(urlPatterns = { "/com/defaultValidate/ReadController" })
public class ReadController extends HttpServlet {

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        ReadBean reader = new ReadBean();
        String address;

        if (request.getParameter("ReadConfirm") != null) {
            try {
                Connection connect = ConnectionManager.getConnection();
                String SQL = "SELECT * FROM prayers ORDER BY prayerTitle DESC";
                PreparedStatement ps = connect.prepareStatement(SQL);

                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                    request.getSession().setAttribute("ref", reader);
                    reader.setTitle(rs.getString("prayerTitle"));
                }
            } catch (Exception e) {
            }
            address = "ReadConfirm.jsp";
        } else if (request.getParameter("ReadView") != null) {
            address = "ReadView.jsp";
        } else {
            address = null;
        }

        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }
}

And then the corresponding jsp page that the controller responds to:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@include file="MenuHeader.jsp"%>
</div>
    <div id="mainBorder"> </div>
        <div id="mainBody">
            <table id="mainTable">
                <tr>
                    <td id="sidebar">
                        <h2>Options</h2>  
                            <ul>

            </ul>
        </td>
        <td id="mainContent">
                        <h2 id="contentHeader">Select a prayer</h2>

                        <form action="ReadController">
                            <table border="1" width="1" cellspacing="5" cellpadding="5">
                                <thead>
                                    <tr>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td><select name="prayer_id">

                                                <c:forEach var="ReadController"       items="${ref.title}">
                                                    <option value="">${ref.title}</option>
                                                </c:forEach>

                                            </select>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td><input type="submit" name="ReadView" value="View">  </td>
                                    </tr>
                                </tbody>
                            </table>

                        </form>
    <td id="imageBar">

            </td>   
        </table>
    <%@ include file="../menuHeaderAndFooter/MenuFooter.jsp" %>

I am definitely not an expert, but I think I am missing something in between the connection from the controller to the for-each element in the JSP that I am simply stuck on. In case curious, the WEB-XML portion of this section is operational and the ConnectionManager is a simple call to set up the connection to the database. The Glassfish package is the utilized server.

If you have any questions about any other portion of the code, let me know as I am quite interested in getting this particular project completed and running as soon and efficiently as possible. I will be happy to provide any additional coding and reference requested.

Any assistance on this particular spot is most appreciated and very helpful. Thank you for looking this over.

Upvotes: 0

Views: 2682

Answers (2)

TheWhiteRabbit
TheWhiteRabbit

Reputation: 15768

Modify your code

List<ReadBean> readerList = new Arraylist<ReadBean>();


while(rs.next()){
// blah blah
reader.setTitle(rs.getString("prayerTitle"));
readerList.add(reader); // add this reader instance to list
}
// after while loop
request.getSession().setAttribute("ref", readerList);

Modify your JSP accordingly to iterate over readerList if necessary, i think it should work without jsp modification.

Upvotes: 1

Abubakkar
Abubakkar

Reputation: 15664

The problem is here with this part of your code

while(rs.next()){
   request.getSession().setAttribute("ref", reader);
   reader.setTitle(rs.getString("prayerTitle"));
}

You are overriding the "ref" attribute every time you are reading a new value and then putting that "ref" in the session. So you are putting a single value in the session and hence you are getting a single row.

So instead put all that values inside a collection like a list and then set that list inside the session:

List<ReadBean> myList = new Arraylist<ReadBean>();
while(rs.next()){
   ReadBean reader = new ReadBean();   
   reader.setTitle(rs.getString("prayerTitle"));
   myList.add(reader);
}
request.getSession().setAttribute("ref", myList);

Now you can use the for each inside your jsp as :

<c:forEach var="myReader" items="${ref}">
       <option value="">${myReader.title}</option>
</c:forEach>

Please note the changes that I have made in the for-each loop above.

First in items attribute you need a collection, so we set a collection named ref inside the session, so we can use it.

Now in the var attribute, we define a local variable whihc is similar to

for(Reader myReader : ref) //myReader will go in var and ref the list(collection) will go in items

And now you can access the properties using the myReader var in the for-each like ${myReader.title} or ${myReader['title']}

Upvotes: 2

Related Questions