如何解决为什么即使 <c:if> 标记的计算结果为 false 也会显示所有表单?
我想使用单个 jsp 文件进行客户、供应商和托运人注册,但是当我运行带有
我该怎么做才能解决这个问题?
下面我展示了 supplier.jsp 和 Sign_in.jsp 的代码。对于客户和托运人的注册,一个jsp 的实现方式与supplier.jsp 相同,只是通过字符串“customer”和“shipper”修改类型变量的值。这些页面将为每个 Customer、Shipper 和 supplier 类显示更具体的值。
supplier.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<Meta charset="ISO-8859-1">
<title>Bienvenido!</title>
</head>
<body>
<h2>Sign in</h2>
<a href="Sign_in.jsp">No account yet? Sign in</a>
<% request.getSession().setAttribute("type","supplier"); %>
</body>
</html>
注册.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<Meta charset="ISO-8859-1">
<title>Sign in</title>
</head>
<body>
<h1>Sign in</h1>
<% String type = (String) request.getSession().getAttribute("type");
String supplier = "supplier";
String shipper = "shipper";
String client = "client";
%>
<% System.out.println(type.equals(supplier)); %>
<c:if test="${type == supplier}">
<h2>I'm a supplier</h2>
<form action="RegisterServlet" method="post">
<input type="email" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button type="submit">Register</button>
</form>
</c:if>
<c:if test="${type == shipper}">
<h2>I'm a shipper</h2>
<form action="RegisterServlet" method="post">
<input type="email" name="email" placeholder="Email">
<input type="text" name="user" placeholder="User">
<input type="password" name="password" placeholder="Password">
<button type="submit">Register</button>
</form>
</c:if>
<c:if test="${type == client}">
<h2>I'm a client</h2>
<form action="RegisterServlet" method="post">
<input type="email" name="email" placeholder="Email">
<input type="text" name="user" placeholder="User">
<input type="password" name="password" placeholder="Password">
<input type="text" name="city" placeholder="City">
<input type="text" name="address" placeholder="Address">
<input type="text" name="country" placeholder="Country">
<button type="submit">Register</button>
</form>
</c:if>
</body>
</html>
解决方法
您需要更改 test
条件以将常量用作
<c:if test="${type == 'supplier'}">
<c:if test="${type == 'shipper'}">
<c:if test="${type == 'client'}">
因为 supplier
、shipper
和 client
是局部变量而不是范围属性。
如果在此更改后没有呈现任何表单,则您的 type
属性设置不正确。检查您的 href
以查看您是否导航到正确的 JSP 页面。您正在调试 Register.jsp,但您的链接指向 Sign_in.jsp,因此这也可能是另一个问题。
@MauricePerry 提出了一个很好的观点,即您应该避免使用 ,因为您已经在使用 JSTL 标记。例如,添加 session 属性
的代码<% request.getSession().setAttribute("type","supplier"); %>
可以替换为 <c:set>
JSTL 标记。
<c:set var="type" value="supplier" scope="session" />
在 view 层的使用是非常不受欢迎的,因此,请尽量将它们的使用限制为仅用于快速调试。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。