Spring MVC中JSTL <c:url>无法解析控制器URL及script标签问题求助
Hey there! Let's break down and fix these two Spring MVC issues you're running into one by one:
<c:url> failing to resolve controller URLs First, let's make sure you have the basics covered, then dive into common fixes:
Ensure JSTL core taglib is imported at the top of your JSP file—this is non-negotiable for using
<c:url>:<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>Verify your controller's
@RequestMappingmapping matches the<c:url>value
Suppose your controller looks like this:@Controller @RequestMapping("/cart") public class CartController { @GetMapping("/viewProduct") public String viewProduct() { // Your business logic here return "productView"; } }Your
<c:url>should reference the full mapped path:<c:url value="/cart/viewProduct" var="viewProductUrl" /> <a href="${viewProductUrl}">View Product</a>Check Spring MVC configuration
- If using XML config, make sure
<mvc:annotation-driven/>is added to your dispatcher-servlet.xml—this enables annotation-based mapping. - If using Java config, ensure your config class has
@EnableWebMvc. - Confirm your DispatcherServlet is mapped to
/in web.xml (or via Spring Boot auto-config) so all requests are routed through Spring:<servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
- If using XML config, make sure
Spring Boot specific check: Ensure your controller class is in a subpackage of your main
@SpringBootApplicationclass—Spring's component scan needs to pick it up.
This usually boils down to unescaped special characters or quote nesting conflicts. Here's how to fix it:
Fix quote nesting errors
A common mistake is mixing double quotes inside a script tag that already uses double quotes:<!-- ❌ Bad: Quote conflict breaks parsing --> <script> var url = "<c:url value="/cart/viewProduct" />"; </script> <!-- ✅ Good: Use single quotes to wrap the JSTL output --> <script> var url = '<c:url value="/cart/viewProduct" />'; </script>Escape special characters with
<c:out>
Use JSTL's<c:out>tag to automatically escape XML/HTML special characters, which prevents parsing issues in JavaScript:<script> var viewProductUrl = "<c:out value='${viewProductUrl}' />"; </script>Use JSTL functions for escaping
If you prefer EL functions, import the functions taglib and usefn:escapeXml:<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <script> var viewProductUrl = "${fn:escapeXml(viewProductUrl)}"; </script>For dynamic HTML generation
If you're building HTML elements in JavaScript, use template literals (ES6+) to avoid quote mess:var linkElement = `<a href="${viewProductUrl}">View Product</a>`; document.body.innerHTML += linkElement;
内容的提问来源于stack exchange,提问作者Bogdan Andrei

