在jsp中为a标签的href属性拼接动态变量的方法

发布时间 2023-05-27 14:45:27作者: mdyyyds_blog

在做web项目练习时遇到了一个需要为href拼接动态变量的问题,在jsp中有这么一段代码实现用户的删改功能。

首先摆出我一开始错误的代码来说明问题。

<html>
<head>
<title>人员管理</title>
</head>
<body>
<%
//从后端Servlrt获取的一个储存我自定义的Persion对象的List
List<Persion> list = (List<Persion>) request.getAttribute("persionlist");
%>
<%--下面设置了一个表格来展示List中的数据并提供修改的功能--%>
<table border="2px">
<caption>用户管理</caption>
<thead>
<tr>
<th>用户名</th>
<th>年龄</th>
<th>性别</th>
<th>住址</th>
<th>编辑</th>
</tr>
</thead>
<tbody>
<%
for(Persion p : list){
%>
<tr>
<td><%=p.getName()%></td>
<td><%=p.getAge()%></td>
<td><%=p.getSex()%></td>
<td><%=p.getAddress()%></td>
<td>
<a href="/persion.do?method=delete&name=p.getName()&age=p.getAge()">删除</a>
<a>&</a>
<a href="/persion.do?method=update&name=p.getName()&age=p.getAge()">修改</a>
</td>
</tr>
<%
}
%>
</tbody>
</table>
</body>
</html>

 


网页中的效果如下

在上面的代码中,为了实现删除和修改,向后端的Servlet发送这张表格中每行的对应的值,就需要在href中拼接相应行的数据,所以需要在每一次循环中使用当前循环中的p变量。但是上面的那样直接在href中拼接时不被允许的。
经查阅资料我得知

你可以先设置一个字符串
String str="************************";
然后按照下面的格式传给href就可以了
<a href="<%=str %>" >删除</a>

因此实际上是在定义String的时候进行拼接再传给href就行了;

下面是 正确 的代码

<html>
<head>
<title>人员管理</title>
</head>
<body>
<%
List<Persion> list = (List<Persion>) request.getAttribute("persionlist");
%>
<%----%>
<table border="2px">
<caption>用户管理</caption>
<thead>
<tr>
<th>用户名</th>
<th>年龄</th>
<th>性别</th>
<th>住址</th>
<th>编辑</th>
</tr>
</thead>
<tbody>
<%
for(Persion p : list){
%>
<tr>
<%
String del = "/persion.do?method=delete&name=" + p.getName() + "&age=" + p.getAge();
String up = "/persion.do?method=delete&name=" + p.getName() + "&age=" + p.getAge() +
"&sex=" + p.getSex() + "&address=" + p.getAddress();
%>
<td><%=p.getName()%></td>
<td><%=p.getAge()%></td>
<td><%=p.getSex()%></td>
<td><%=p.getAddress()%></td>
<td>
<a href="<%=del%>">删除</a>
<a>&</a>
<a href="<%=up%>">修改</a>
</td>
</tr>
<%
}
%>
</tbody>
</table>
</body>
</html>

 


————————————————
版权声明:本文为CSDN博主「ashenvan」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/ashenvan/article/details/104327630