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>