将servlet链接到jsp。

时间:2012-03-29 04:20:37

标签: java jsp servlets

是否有一种方法可以在不使用物理URL链接的情况下将servlet链接到JSP。所以我希望servlet运行,然后servlet将我带到JSP。 有任何想法吗。

4 个答案:

答案 0 :(得分:2)

只需调用servlet的URL而不是JSP的URL,然后在servlet的doGet()方法中执行预处理作业。

E.g。一个servlet,它在JSP提供产品之前加载产品列表:

@WebServlet("/products")
public class ProductServlet extends HttpServlet {

    @EJB
    private ProductService productService;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Preprocess request: load list of products for display in JSP.
        List<Product> products = productService.list();
        request.setAttribute("products", products);
        request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
    }

}

JSP看起来像这样:

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

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Our Products</title>
    </head>
    <body>
        <h1>Products</h1>
        <table>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Description</th>
                <th>Price</th>
            </tr>
            <c:forEach items="${products}" var="product">
                <tr>
                    <td>${product.id}</td>
                    <td><c:out value="${product.name}" /></td>
                    <td><c:out value="${product.description}" /></td>
                    <td><fmt:formatNumber value="${product.price}" type="currency" /></td>
                </tr>
            </c:forEach>
       </table>
    </body>
</html>

如果直接转到http://localhost:8080/contextname/products,则将调用servlet的doGet(),并从DB加载产品并将其存储在请求范围中,并将控件转发给JSP。反过来在一些漂亮的HTML标记中显示结果。

另见:

答案 1 :(得分:0)

是的,使用框架。 Servlets和JPS就像水和石头一样 - 你可以用它们建造道路,但是你不能要求它们单独完成。你必须出汗,或者为你做一些框架;)

如果您熟悉Java,我建议http://www.playframework.org/(1.2.4 ... 2.0不那么娇小,更像Scalish)

答案 2 :(得分:0)

是的,在servlet中你可以添加html代码,然后将重定向发送到JSP页面。

答案 3 :(得分:0)

我认为你想要的是一个前锋。浏览器URL将维护servlet的URL,并且请求中的属性将可供jsp使用。

RequestDispatcher r = getServletContext()。getRequestDispatcher(“foo.jsp”);

r.forward(请求,回复);