Question

I am learning JSP and trying to make a Blog in it. What is the best method to display the posts ? I have stored the contents of the posts in mySql. So far my design has been as follows :

The client makes request to the url/Blog which is captured by the controller (Servlet). This then calls the Java Bean which fetches all the post content from the database and stores it in an ArrayList which is returned to the controller which then forwards this to the jsp page as request attribute. Inside the Jsp page, i have used custom tag which then takes the request attribute from the pageContext, iterates through the posts and prints them in html format using out.println (JspWriter).

Is there a better / faster method to bind the database or the arraylist result to the html code so that I won't have to print each html line from inside the tag ?

One option may be to return the arraylist in JSON format and bind it using JavaScript but i don't have much knowledge about JS.

Was it helpful?

Solution

Instead of using the custom tag you should have a loop in the jsp page, like this:

At the top:

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

In the body:

<c:forEach var="post" items="${posts}">
  <div class="post">
    <h2>${post.title}</h2>
    <p>${post.content}</p>
    <p>${post.time}</p>
  </div>
</c:forEach>

And then in the servlet you would have something like this:

request.setAttribute("posts", myPosts);

You would need the "jstl.jar" in your classpath for the taglib to work.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top