palAlaa
palAlaa

Reputation: 9858

view data form database table to table tag in jsp page

I want to apply MVC2 J2EE approach in my work with JSP pages. I want to separate the code in Servlet and design in JSP. The problem I am facing is that I want to display all users and their data from DB table to HTML table in JSP page Now How should I call the servlet from JSP page, since there is no form in display page and I don't know whether I could use dispatcher since the admin will click on <a href>display users and JSP pages should display all uesrs. How can i make that?

Upvotes: 1

Views: 4849

Answers (1)

BalusC
BalusC

Reputation: 1108692

Just use the doGet() method of the Servlet and call the URL of the servlet instead.

E.g.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<User> users = userDAO.list();
    request.setAttribute("users", users);
    request.getRequestDispatcher("/WEB-INF/users.jsp").forward(request, response);
}

Map this servlet in web.xml as follows:

<servlet>
    <servlet-name>users</servlet-name>
    <servlet-class>com.example.UsersServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>users</servlet-name>
    <url-pattern>/users</url-pattern>
</servlet-mapping>

Now the servlet is accessible by http://example.com/context/users.

In the /WEB-INF/users.jsp file use JSTL c:forEach to display users in a table.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
    <c:forEach items="${users}" var="user">
        <tr>
            <td>${user.name}</td>
            <td>${user.email}</td>
            <td>${user.age}</td>
        </tr>
    </c:forEach>
</table>

The JSP file is to be placed in /WEB-INF folder to avoid that it's accessible without calling the servlet first.

See also:


Update: to install JSTL, take the following steps:

  1. Download jstl-1.2.jar.

  2. Drop it in /WEB-INF/lib folder. Do NOT extract it! Do NOT change web.xml! Some poor online tutorials will suggest this. They're all wrong.

  3. Declare the taglib of interest in top of JSP page as per the JSTL TLD documentation. For example, JSTL core:

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

Upvotes: 5

Related Questions