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

如何在JSP中使用c:url创建含路径变量的链接(不修改路由)?

Solution for Using <c:url> with Path Variables Without Modifying Routes

Hey Rafael! Let's get this sorted out for you. The issue you're running into is that <c:url> doesn't natively handle path variable placeholders like {id} out of the box, but there's a straightforward way to generate the correct URL without touching your existing controller route.

First, Fix the Syntax Issue

Looking at your code snippet, you missed quotes around the var attribute value, which might be causing immediate problems. Always wrap JSP tag attributes in quotes:

<!-- Wrong syntax -->
<c:url value="/movie/${session.id}/details" var=myURL>

<!-- Correct syntax -->
<c:url value="/movie/${session.id}/details" var="myURL">

Method 1: Direct EL String Concatenation with <c:url>

Since your controller expects a path variable /movie/{id}/details, you can directly inject the session.id value into the URL path before passing it to <c:url>. The <c:url> tag will automatically handle adding your application's context path (if deployed under a subpath), which is the main benefit of using it over a raw anchor tag.

Here's the working code:

<c:url value="/movie/${session.id}/details" var="myURL" />
<a href="${myURL}">View Movie Details</a>

Method 2: Use JSTL Functions for Cleaner Template Replacement

If you prefer a more structured approach (especially useful if you reuse the URL template elsewhere), you can use the JSTL Functions taglib to replace a placeholder in a base URL template.

First, add the functions taglib to your JSP:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

Then use fn:replace to swap the placeholder with your session.id value:

<c:set var="baseMovieUrl" value="/movie/{id}/details" />
<c:set var="movieDetailsUrl" value="${fn:replace(baseMovieUrl, '{id}', session.id)}" />
<c:url value="${movieDetailsUrl}" var="myURL" />
<a href="${myURL}">View Movie Details</a>

Why Your Original Attempt Might Have Failed

  • Missing quotes on attributes: As mentioned, var=myURL should be var="myURL" to be valid JSP syntax.
  • Empty session.id value: Double-check that session.id is actually populated with a valid integer when this JSP renders. If it's null or empty, the generated URL will be /movie//details, which won't match your controller route.

Both methods above will generate the exact URL your controller expects (/movie/{actual-id}/details) while leveraging <c:url> for context path handling, and you won't need to modify your existing @GetMapping("/movie/{id}/details") route at all.

内容的提问来源于stack exchange,提问作者Rafael Perracini

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:34:48