在JSP中使用if-else
我正在使用以下代码在浏览器上打印用户名:在JSP中使用if-else,jsp,if-statement,scriptlet,Jsp,If Statement,Scriptlet,我正在使用以下代码在浏览器上打印用户名: <body> <form> <h1>Hello! I'm duke! What's you name?</h1> <input type="text" name="user"><br><br> <input type="submit" value="submit"> &
<body>
<form>
<h1>Hello! I'm duke! What's you name?</h1>
<input type="text" name="user"><br><br>
<input type="submit" value="submit">
<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>
你好我是杜克!你叫什么名字?
response.jsp:
<body>
<h1>Hello</h1>
<%= request.getParameter("user") %>
body>
你好
正文>
每次我执行它,消息
我明白了!你没有名字。。好。。你好,没有名字
即使我没有在文本框中输入任何内容,也会显示。但是,如果我在其中输入任何内容,则会显示response.jsp代码,但我不希望在执行时显示第一条消息。我如何做到这一点?请建议修改我的代码
顺便说一下,我在一些问题中读到,与其用null检查相等性,还不如检查它是否不相等,这样它就不会抛出null指针异常。当我尝试同样的方法时,例如,if(user!=null&&..
,我得到了NullPointerException
在JSP中几乎总是建议不要使用scriptlet。他们被认为是不好的形式。相反,尝试使用(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" %>
<% } %>
在jstl中:
<c:if test="${not empty user}">
<%@ include file="response.jsp" %>
</c:if>
您可以尝试以下示例:
你好我是杜克!你叫什么名字?
你好${param.user}
在两种情况下都使用if,而不是if-else条件。它会这样工作,但不知道为什么。这很有效,非常感谢:)但您能告诉我使用的解决方案吗scriplets@user2195963不显示文本的最简单的解决方案是将“user”设置为null或空。您需要的是一种使页面足够智能的方法,以知道“user”为空,因为这是第一次访问页面。请参阅我针对此问题所做的编辑。
<c:otherwise>
<h1>Hello</h1>
${user}
</c:otherwise>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<% String user = request.getParameter("user");
if( user != null && user.length() > 0 ) {
<%@ include file="response.jsp" %>
}
%>
<c:if test="${not empty user}">
<%@ include file="response.jsp" %>
</c:if>