根据我的理解,无论如何都会编译JSP,所以我预计你会从两者中获得类似的性能。我想显示大量数据,我正在考虑使用JSP作为基础知识并调用servlet来为表中的每一行生成代码。除非有一个很好的方法来通过一次调用servlet来生成整个表,否则这将意味着几百个调用,我认为这些调用效率不高。这里的“正确”方式是什么?直接的servlet会产生大量丑陋的println代码,直接的JSP会产生大量丑陋的逻辑陈述......
答案 0 :(得分:6)
@Tony是完全正确的。只是不要在Servlet中打印HTML。这项工作是针对JSP的。也不要在JSP中编写原始Java代码。这项工作是为Servlet。一旦你记住这两个简单的规则,一切都会顺利进行。
Servlet的工作示例:
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.
}
在JSTL的帮助下,JSP的工作示例:
<%@ 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>
简单如下:)
答案 1 :(得分:5)
servlet加载数据结构,如map,将其放入请求,然后转发到jsp。 jsp迭代并格式化。当用于善,而不是邪恶时,它是非常有效的。