在 JSP 中使用 if-else

2023-11-23

我使用以下代码在浏览器上打印用户名:

<body>
  <form>
    <h1>Hello! I'm duke! What's you name?</h1>
    <input type="text" name="user"><br><br>
    <input type="submit" value="submit">&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="reset">
  </form>
  <%String user=request.getParameter("user"); %>
  <%if(user == null || user.length() == 0){
    out.print("I see! You don't have a name.. well.. Hello no name");   
   }
   else {%>
      <%@ include file="response.jsp" %>
   <% } %>  
</body>

响应.jsp:

<body>
    <h1>Hello</h1>
    <%= request.getParameter("user") %>
 body>

每次我执行它时,都会出现消息

我懂了!你没有名字..好吧..你好,没有名字

即使我没有在文本框中输入任何内容,也会显示。但是,如果我在其中输入任何内容,则会显示 response.jsp 代码,但我不希望在执行时显示第一条消息。我怎样才能做到这一点?请建议更改我的代码。

附:我在一些问题中读到,不是检查是否与 null 相等,而是必须检查它是否不等于,这样它就不会抛出空指针异常。当我尝试同样的操作时,即if(user != null && ..), I got NullPointerException.


It's 几乎总是建议不要在 JSP 中使用 scriptlet。他们被认为是不好的形式。相反,尝试使用JSTL(JSP 标准标记库)与 EL(表达式语言)相结合来运行您想要执行的条件逻辑。作为一个额外的好处,JSTL 还包括其他重要的功能,例如循环。

代替:

<%String user=request.getParameter("user"); %>
<%if(user == null || user.length() == 0){
    out.print("I see! You don't have a name.. well.. Hello no name");   
}
else {%>
    <%@ include file="response.jsp" %>
<% } %>

Use:

<c:choose>
    <c:when test="${empty user}">
        I see!  You don't have a name.. well.. Hello no name
    </c:when>
    <c:otherwise>
        <%@ include file="response.jsp" %>
    </c:otherwise>
</c:choose>

另外,除非您计划在代码中的其他地方使用response.jsp,否则将html包含在您的otherwise语句中可能会更容易:

<c:otherwise>
    <h1>Hello</h1>
    ${user}
</c:otherwise>

还值得注意。要使用 core 标签,您必须按如下方式导入它:

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

您希望用户在提交用户名时收到一条消息。最简单的方法是当“user”参数为null。您可以进行一些验证,以便在用户提交时给出错误消息null。这是解决您的问题的更标准的方法。为了实现这一点:

在脚本中:

<% String user = request.getParameter("user");
   if( user != null && user.length() > 0 ) {
       <%@ include file="response.jsp" %>
   }
%>

In jstl:

<c:if test="${not empty user}">
    <%@ include file="response.jsp" %>
</c:if>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 JSP 中使用 if-else 的相关文章

随机推荐