1

我将 Java 与 Servlet 和 JSP 一起使用来创建一个基本应用程序。

我有这个基本的 html 文件,我称之为基本布局,它具有基本的页面结构,带有导航菜单、页眉和页脚。

我还有一个register.jsp页面,用户可以在其中注册。

当用户点击url时,如何将其包含register.jsp到基本布局中?/register

目前,我使用该对象从 Servlet 转储注册页面的 html 内容,PrintWriter并使用 ajax 动态呈现基本页面上的内容。但这确实是一个不好的做法。

4

2 回答 2

1

是的,这确实是不好的做法。

可以轻松完成的更简单的选择是将您的 html 文件转换为 jsp。然后在 jsp 中,您可以包含您想要的任何其他资源。考虑这个例子:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <jsp:include  flush="true" page="/templates/css.jsp"/>
        <jsp:include  flush="true" page="/templates/scripts.jsp"/>
    </head>
    <body>
        <div id="container">
            <div id="header">
                <jsp:include  flush="true" page="/templates/header.jsp"/>
                <jsp:include  flush="true" page="/templates/top_menu_visitor.jsp"/>
            </div>
            <div id="wrapper">
                <jsp:include  flush="true" page="/templates/top_content_visitors.jsp"/>
            </div>
            <div id="footer">
                <jsp:include  flush="true" page="/templates/footer_credits.jsp"/>
            </div>
        </div>
    </body>
</html>

在此示例中,您有一个包含许多组件的模板页面,其中大部分在不同页面之间是通用的。这很可能是您的 index.jsp。对于注册 jsp,您只需像这样创建一个新的 jsp 页面并更改几个部分。

这是一种方法。在 Java EE 中,有许多框架可以自动执行此过程。

于 2013-06-26T22:46:39.687 回答
0

您可以<jsp:include>结合使用<c:if>检查当前 URL 的条件块。

可以使用获取当前请求 URL${pageContext.request.requestURI}

还有Apache Tiles 库可以帮助克服 JSP 缺乏可重用性

有关<jsp:include>Java EE5 教程的更多信息:http: //docs.oracle.com/javaee/5/tutorial/doc/bnajb.html

于 2013-06-26T22:43:56.993 回答