JSP表单如何仅当URL中存在对应参数时才将其添加到提交参数
解决方案
有两种实现思路,分别对应服务端渲染和前端动态处理场景:
方案1:JSP服务端动态渲染隐藏域(优先推荐)
直接在JSP中通过EL表达式判断参数是否存在/非空,只有符合条件时才输出对应的隐藏输入框,从根源上避免空参数被提交:
<form action="study.show" method="POST"> <c:if test="${not empty param.arg0}"> <input type="hidden" name="arg0" value="${param.arg0}" /> </c:if> <c:if test="${not empty param.arg}"> <input type="hidden" name="arg" value="${param.arg}" /> </c:if> ... </form>
注意:如果你的项目没有引入JSTL核心标签库,需要先在JSP顶部引入声明:<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
如果不想依赖JSTL,也可以用原生JSP脚本片段实现:
<form action="study.show" method="POST"> <% String arg0 = request.getParameter("arg0"); if(arg0 != null && !arg0.trim().isEmpty()) { %> <input type="hidden" name="arg0" value="<%= arg0 %>" /> <% } String arg = request.getParameter("arg"); if(arg != null && !arg.trim().isEmpty()) { %> <input type="hidden" name="arg" value="<%= arg %>" /> <% } %> ... </form>
方案2:前端JS动态处理提交(适配无法修改服务端代码的场景)
如果不方便修改JSP服务端逻辑,可以在表单提交前移除值为空的隐藏输入框:
// 给表单加id方便选择,比如id="studyForm" document.getElementById('studyForm').addEventListener('submit', function(e) { // 遍历所有隐藏输入框 this.querySelectorAll('input[type="hidden"]').forEach(input => { if(input.value.trim() === '') { input.remove(); } }); });
对应修改原表单添加id即可,同时注意补全原代码method="POST缺失的闭合双引号,避免浏览器解析异常:
<form action="study.show" method="POST" id="studyForm"> <input type="hidden" name="arg0" value="${param.arg0}" /> <input type="hidden" name="arg" value="${param.arg}" /> ... </form>
内容的提问来源于stack exchange,提问作者Jonathan Hagen
相关产品推荐
相关产品推荐

