开发者

view data form database table to table tag in jsp page

开发者 https://www.devze.com 2023-01-15 20:17 出处:网络
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.

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 an开发者_开发百科d 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?


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:

  • How to avoid Java code in JSP files
  • Hidden features of JSP/Servlet
  • (Advanced) design patterns in JSP/Servlet

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" %>
    
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号