11

我有一个没有框架的 java 应用程序。它由用于视图的 jsp 文件和用于业务逻辑的 servlet 组成。我必须将用户会话设置为带有 firstName 参数的 servlet。在 jsp 文件中,我需要检查我的 firstName 参数是否有值。如果设置了firstName参数,我需要在jsp文件中显示一些html。如果没有设置,我需要在jsp文件中显示不同的html。

Servlet.java:

HttpSession session = request.getSession();
session.setAttribute("firstName", customer.getFristName());
String url = "/index.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);

header.jsp:

// Between the <p> tags bellow I need to put some HTML with the following rules
// If firstName exist: Hello ${firstName} <a href="logout.jsp">Log out</a>
// Else: <a href="login.jsp">Login</a> or <a href="register.jsp">Register</a>

<p class="credentials" id="cr"></p>

最好的方法是什么?

更新:

这是我在 JSTL 上找到的一个很棒的教程,以防万一有人需要它: http ://www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm

4

3 回答 3

10
<% if (session.getAttribute("firstName") == null) { %>
    <p> some content </p>
<% } else {%>
    <p> other content </p>
<% } %>
于 2012-11-30T03:16:00.337 回答
4

我认为最好的方法是使用 jstl 标签。因为对于简单的 jsp 应用程序,将所有 java 代码添加到 html 可能是个好主意,但更重的应用程序最好在 html 上使用最少的 java 代码。(从逻辑中分离视图层)(阅读更多https://stackoverflow。 com/a/3180202/2940265
为了您的期望,您可以轻松使用如下代码

<c:if test="${not empty firstName}">
    <%--If you want to print content from session--%>
    <p>${firstName}</p>

    <%--If you want to include html--%>
<%@include file="/your/path/to/include/file.jsp" %>

    <%--include only get wrong if you give the incorrect file path --%>
</c:if>
<c:if test="${empty firstName}">
    <p>Jaathi mcn Jaathi</p>
</c:if>

如果您没有正确包含 jstl,您将无法获得预期的输出。请参阅此事件以了解此类事件https://menukablog.wordpress.com/2016/05/10/add-jstl-tab-library-to-you-project-correctly/

于 2016-10-26T05:03:40.037 回答
1

在servlet中你可以写如下

        HttpSession session = request.getSession(true);
        session.setAttribute("firstName", customer.getFristName())
        response.sendRedirect("index.jsp");

request.getSession(true)如果它不存在任何会话,则返回一个新会话,否则它将返回当前会话。并且,在index.jsp页面中您可以执行以下操作:

<%
if(session.getAttribute("firstName")==null) {
%>
<jsp:include page="firstPage.html"></jsp:include>
<%
} else {
%>
<jsp:include page="secondPage.html"></jsp:include>
<%
}%>

在这里,如果firstName为 null 那么firstPage.html将被包含在页面中,否则secondPage.html

于 2012-11-30T05:01:55.467 回答