我使用以下代码在浏览器上打印用户的名字:
<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代码,但我不希望在执行时显示第一条信息。我怎样才能做到这一点呢?请对我的代码提出修改建议。
P.S.我在一些问题中读到,不检查与null相等,而是检查不相等,这样就不会抛出空指针异常。当我尝试同样的方法,即if(user != null && ...)
,我得到了NullPointerException
。
几乎总是建议不要在你的JSP中使用小脚本。 它们被认为是不好的形式。 相反,可以尝试使用[JSTL][1](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" %>
<% } %>
使用:
<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可能会更容易:
<c:otherwise>
<h1>Hello</h1>
${user}
</c:otherwise>
还需要注意的是。 要使用核心标签,你必须按以下方式导入它:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
你想让用户在提交用户名时能收到一条信息。 最简单的方法是,当"user"参数为null'时,根本不打印消息。 你可以做一些验证,在用户提交
null'时给出一个错误信息。 这是解决你的问题的一个比较标准的方法。 为了达到这个目的:
在scriptlet中:
<% String user = request.getParameter("user");
if( user != null && user.length() > 0 ) {
<%@ include file="response.jsp" %>
}
%>
在jstl:
<c:if test="${not empty user}">
<%@ include file="response.jsp" %>
</c:if>
[1]: https://docs.oracle.com/javaee/5/tutorial/doc/bnakc.html "JSTL";