开发者

Do you take a big performance hit mixing JSP and Servlets?

From my understanding, JSPs are compiled anyway, so I would anticipate you'd get similar performance from both. I want to display a lot of data, and I'm thinking of using JSP for the basics and calling a servlet to generate the code for each row in the t开发者_如何学Cable. Unless there's a good way to generate the entire table with one call to the servlet, this would mean several hundred calls, which I imagine is not efficient. What's the "right" way here? Straight servlets would make for a ton of ugly println code, and straight JSP would make for a ton of ugly logic statements...


@Tony is entirely right. Just don't print HTML in the Servlet. This job is for JSP. Also don't write raw Java code in JSP. This job is for Servlet. Once you keep those two simple rules in mind, everything will go well.

Example of Servlet's job:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<Product> products = productDAO.list(); // Obtain all products.
    request.setAttribute("products", products); // Store products in request scope.
    request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response); // Forward to JSP page to display them in a HTML table.
}

Example of JSP's job with little help of JSTL:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
    <c:forEach items="${products}" var="product">
        <tr>
            <td>${product.name}</td>
            <td>${product.description}</td>
            <td>${product.price}</td>
        </tr>
    </c:forEach>
</table>

Simple as that :)

Related questions:

  • How to avoid Java code in JSP?
  • What is the difference between JSP/Servlet/JSF?


The servlet loads up a data structure like a map, puts it into the request, and forwards to a jsp. The jsp iterates and formats. It is very efficient when used for good, not evil.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜