简体   繁体   中英

Passing resultSet from servlet to JSP file. Attribute of ArrayList type is always null

I am new to creating dynamic web projects and I am not sure if I grasp the idea of the whole thing correctly.

I am trying to create a simple web app for browsing books from mySQL database, which contains only one table: Books(id_book, title, author, isbn, description).

I've prepared Driver class, which I use to retrieve data from database and convert it from ResultSet to ArrayList<.Book>, BookSelect servlet, which is supposed to pass the created list to JSP file, and finally bookselectJSP file which I wish would present results on the website.

Driver:

public class Driver {

private ResultSet resultSet;
public ArrayList<Book> resultList;
private Connection myCon;
private Statement myStatement;

public Driver() {
    try {
        this.resultList = new ArrayList<Book>();
        myCon = DriverManager.getConnection("jdbc:mysql://localhost:3306/firstbase","root","myPassword");
        myStatement = myCon.createStatement();
        resultSet = myStatement.executeQuery("select * from books");
        while(resultSet.next()){
            resultList.add(new Book(Integer.parseInt(resultSet.getString(1)),resultSet.getString(2),resultSet.getString(3),resultSet.getString(4),resultSet.getString(5)));
        }

        resultSet.close();
        myStatement.close();
        myCon.close();

    } catch (SQLException e) {
        e.printStackTrace();
    }
}

public ArrayList<Book> getResultList(){
    resultList.forEach(e -> System.out.println("here->" + e + "<-" ));
    return resultList;
}

public ResultSet getResultSet(){
    return this.resultSet;
}

BookSelect

    protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    RequestDispatcher rd = getServletContext().getRequestDispatcher("/bookselectJSP.jsp");
    Driver myDriver = new Driver();
    //myDriver.getResultList().add(new Book(1, "aa", "aa", "aa", "aa"));
    request.setAttribute("resultList", myDriver.getResultList());
    rd.forward(request, response);

}

bookselectJSP: (right now I am just trying to display even one row with label)

<h1 id="titleBar">List of your books</h1>

<% 
 ArrayList<Book> rows = (ArrayList<Book>) request.getAttribute("resultList");
%>

<label><%=rows.get(0).toString()%></label>

The whole problem is that when I add main method in Driver class and run it, everything seems to be working splendidly. I get the data, convert it to ArrayList and then I am able to print results from that list. But as soon as I try to access it from servlet class, it is ALWAYS null.

Error message: This is an error message

Weird thing is that when I add something to the list in servlet (commented code in servlet service method), it is being passed. I have absolutely no idea how to proceed from now on, I am completely lost, please help.

************************************SOLVED**************************************

The problem was that tomcat couldn't find the suitable driver, I thought its weird beacause I've put it not only in WEB-INF/lib but also in $CATALINA_HOME/lib, everythig was configured properly. Anyway, what helped was adding the following line just before starting the connection:

DriverManager.registerDriver(new com.mysql.jdbc.Driver ());

As I was told that should not be necessary, but what do you know, as it turns out - it is :)


What i suggest you is create a bean class for Book something like this.

Class BookBean{
private int bookId;
private String title;
//and so on for all the properties
//add getters and setters
}

Now in your Driver class convert ResultSet to ArrayList as below

ResultSet re=daoclass.getdata();//used to get result set from DB
List<BookBean> booklist=new ArrayList<BookBean>
while(re.next()){
int id=re.getInt("book_id");
String name=re.getString("name");
//extract all the parameters as above
BookBean bb=new BookBean();
bb.setId(id);
bb.setName(name);
//assign all the parameters to the bean

booklist.add(bb);//adding bean to the list

}

Now in your Servlet forward this list to the jsp as below

public void doGet(HttpServletRequest request, HttpServletResponse response)
{
request.setAttribute("booklist",booklist);
//forward the request to jsp using Request Dispatcher
}

Now in your JSP you can access the data of each book using JSTL foreach attribute as below

<c:forEach var="blist" items="${booklist}">
    <p>${blist.id}</p>
    <p>${blist.name}</p>        
</c:forEach>

Please comment if you have any doubts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM