You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring/JSP中如何通过点击链接将数值传递至Controller类

实现JSP链接传递数值到Controller方法的方案

没问题,这是Web开发里很常见的参数传递需求,给你两种最常用的实现方式(适配Spring MVC框架,看你提到的MyController类,应该是用这个):

方法一:通过URL查询参数传递

这是最直观的方式,把数值作为URL的查询参数附加在链接后面:

1. 修改JSP中的链接

把原来的链接改成带参数的形式,比如要传递1,就把href改成/mycontroller?userId=1:

<li class="mix">
  <img src="resources/img-1.jpg" >
  <a href="/mycontroller?userId=1">David Pringle</a>
</li>

2. 在MyController中接收参数

用@RequestParam注解来获取URL里的参数:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class MyController {

    // 映射到你JSP链接里的路径/mycontroller
    @GetMapping("/mycontroller")
    public String handleUserRequest(@RequestParam("userId") int userId) {
        // 这里就能拿到传递过来的数值1了,执行你的业务逻辑
        System.out.println("收到的用户ID:" + userId);
        // 最后返回要跳转的页面(比如resultPage.jsp)
        return "resultPage";
    }
}

方法二:通过路径变量传递(REST风格)

这种方式的URL更简洁优雅,适合RESTful场景:

1. 修改JSP中的链接

把数值作为URL路径的一部分,比如/mycontroller/1:

<li class="mix">
  <img src="resources/img-1.jpg" >
  <a href="/mycontroller/1">David Pringle</a>
</li>

2. 在MyController中接收参数

用@PathVariable注解来获取路径中的数值:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Controller
public class MyController {

    // 用{userId}占位路径中的数值
    @GetMapping("/mycontroller/{userId}")
    public String handleUserRequest(@PathVariable("userId") int userId) {
        System.out.println("通过路径变量收到的用户ID:" + userId);
        return "resultPage";
    }
}

额外提示

如果你的JSP是循环生成的列表(比如展示多个用户),可以用JSP的EL表达式动态生成参数,比如:

<%-- 假设你在JSP中存了userList集合 --%>
<c:forEach items="${userList}" var="user">
  <li class="mix">
    <img src="resources/img-${user.id}.jpg" >
    <a href="/mycontroller/${user.id}">${user.name}</a>
  </li>
</c:forEach>

内容的提问来源于stack exchange,提问作者rajat kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:29:47