Awa*_*ani 9 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">
<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>
Run Code Online (Sandbox Code Playgroud)
的response.jsp:
<body>
<h1>Hello</h1>
<%= request.getParameter("user") %>
body>
Run Code Online (Sandbox Code Playgroud)
每次我执行它,消息
我知道了!你没有名字..好吧..你好,没有名字
即使我没有在文本框中输入任何内容,也会显示.但是,如果我在其中输入任何内容,则会显示response.jsp代码,但我不希望在执行时显示第一条消息.我该如何做到这一点?请修改我的代码.
PS我在一些问题中已经读过,而不是检查与null的相等性,必须检查它是否为等于,以便它不会抛出空指针异常.当我尝试同样的,即if(user != null && ..),我得到了NullPointerException.
sfe*_*dak 17
它几乎总是最好在你的JSP不使用小脚本.他们被认为是糟糕的形式.相反,尝试使用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" %>
<% } %>
Run Code Online (Sandbox Code Playgroud)
使用:
<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>
Run Code Online (Sandbox Code Playgroud)
此外,除非您计划在代码中的其他位置使用response.jsp,否则在您的其他语句中包含html可能更容易:
<c:otherwise>
<h1>Hello</h1>
${user}
</c:otherwise>
Run Code Online (Sandbox Code Playgroud)
另外值得注意.要使用核心标记,必须按如下方式导入它:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Run Code Online (Sandbox Code Playgroud)
您希望这样做,以便用户在用户提交用户名时收到消息.最简单的方法是在"用户"参数出现时根本不打印消息null.您可以进行一些验证,以在用户提交时给出错误消息null.这是解决问题的更标准方法.要做到这一点:
在scriptlet中:
<% String user = request.getParameter("user");
if( user != null && user.length() > 0 ) {
<%@ include file="response.jsp" %>
}
%>
Run Code Online (Sandbox Code Playgroud)
在jstl中:
<c:if test="${not empty user}">
<%@ include file="response.jsp" %>
</c:if>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
122871 次 |
| 最近记录: |