使用JSTL进行页面服务器端校验

本文介绍了一个使用JSP实现的简单表单验证案例。该案例确保用户输入的姓名和年龄字段不为空,并且年龄必须大于18岁。通过JSTL标签库实现了条件判断和错误提示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

验证JSP(包含用户输入)

验证条件为,姓名和年龄均为必填字段,并且年龄必须大于18岁

<%@ page contentType="text/html; charset=gb2312" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<html>
<head>

<title>Currency Formatting</title>
</head>
<body>

<c:if test="${param.submitted}">
 
<c:if test="${empty param.name}" var="noName"/>
 
<c:if test="${empty param.age}" var="noAge"/>
 
<c:catch var="errorAge">
   
<fmt:parseNumber var="paraseAge" value="${param.age}"/>
   
<c:if test="${paraseAge < 18}" var="youngAge"/>
 
</c:catch> 

 
<c:if test="${not(noName or noAge or youngAge)}">
 
  
<c:set value="${param.name}" var="name" scope="request"></c:set>
  
<c:set value="${param.age}" var="age" scope="request"></c:set>
  
<jsp:forward page="result.jsp"></jsp:forward>
</c:if>
</c:if>



<form action="validate.jsp">
<input type="hidden" name="submitted" value="true"/>
输入姓名(必填):
<input type="text" name="name"/><br>
<c:if test="${noName}">请输入姓名<br></c:if>
输入年龄(必填,大于18岁)
<input type="text" name="age"/><br>
<c:if test="${noAge}">请输入年龄<br></c:if>
<c:if test="${youngAge}">年龄必须大于18<br></c:if>
<input type="submit" value="submit"/>
</form>

</body>
</html>

验证通过后的页面为result.jsp,如果验证不通过,则跳转会原输入页面

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值