JSP - 将 Java 与 HTML 分离
如果我有这样的事情:
<%
String name = (String)session.getAttribute("username");
if(name!=null)
{%>
<div id="navBar">
<h2><a href="blah.jsp">Home</a> |
<a href="blah1.jsp">SomewhereElse</a> |
</div>
<%}%>
基本上,如果变量名称为空,则不显示导航栏,但由于应该避免混合 Java 和 HTML - 我看不出如何重写它来分离这两种语言???
If I had something like this:
<%
String name = (String)session.getAttribute("username");
if(name!=null)
{%>
<div id="navBar">
<h2><a href="blah.jsp">Home</a> |
<a href="blah1.jsp">SomewhereElse</a> |
</div>
<%}%>
Basically, if variable name is null, don't display navigation bar, but since mixing Java and HTML should be avoided - I can't see how you can rewrite this to separate the 2 languages???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用标签库/EL。您的特定示例可以在 JSTL
:仅当页面、请求、请求中不存在名为
username
的属性时,才会打印给定的 HTML会话或应用程序范围。另请参阅:
Use taglibs/EL. Your particular example can be solved as follows with help of JSTL
<c:if>
:The given HTML will only be printed when there's no attribute with the name
username
in any of the page, request, session or application scopes.See also:
您应该有一个控制器(它可以是简单的东西,如普通的 Java
servlet
)。在一种情况或另一种情况下,您可以将其发送到不同的 JSP 页面。JSP 不像 PHP 那样直接“调用文件”。相反,您应该将 URL 映射到 Servlet(控制器),然后让该 Servlet 在内部处理 JSP 部分。请记住将 JSP 文件放在
WEB-INF
目录中,这样用户就无法直接访问它。You should have a controller (it could be something simple as a plain Java
servlet
). You would send it to different JSP pages in one case or the other.JSP is not like PHP where you "invoke the file" directly. Instead, you should map a URL to a Servlet (controller) and then let that servlet handle internally the JSP part. Do remember to put JSP files in
WEB-INF
directory so user won't have direct access to it.我同意 BalusC 的观点。
不要忘记添加以下 taglib 指令:
这允许您引用 JSTL 核心标记库标记
这为您提供了很多或有用的功能,如 if、choose、foreach 等
请注意,taglib 指令可以通过另一个 jsp 间接添加它包含在当前文件中。
例如使用:
I agree with BalusC.
Don't forget to add the following taglib directive:
This allows you to reference the JSTL core tag library tags
This gives you a lot or useful features like if, choose, foreach, etc
Note that the taglib directive can be added indirectly through another jsp which is included by the current file.
E.g using: