Java – Spring: Controller @RequestMapping to jsp

javaspringspring-mvc

Using Spring 3.1.2

How do you reference the Annotated value of the CONTROLLER (not method) RequestMapping from a jsp so I can build URL's relative to the Controller. If the method level request mappings are referenced, it will cause my links to not work, so they cannot be part of the this in any way.

For example (Note that this controller's mapping is "/foo/test"):

@Controller
@RequestMapping("/foo/test")
public class FooController {

    @RequestMapping(value="/this", method=RequestMethod.GET)
    public String getThis() {
        return "test/this";
    }

    @RequestMapping(value="/that", method=RequestMethod.GET)
    public String getThat() {
        return "test/that";
    }

    @RequestMapping(value="/other", method=RequestMethod.GET)
    public String getOther() {
        return "test/other";
    }
}

…and from my this.jsp:

<%@ taglib uri="http://www.springframework.org/tags" prefix="s"%>
<s:url value="${controllerRequestMapping}" var="baseUrl"/>

<a href="${baseUrl}/that">That</a>
<a href="${baseUrl}/other">Other</a>

The reason I need to access the RequestMapping is because my views may be accessed from multiple Controllers. Note that this controller's mapping is "/bar/test"!

@Controller
@RequestMapping("/bar/test")
public class BarController {

    @RequestMapping(value="/this", method=RequestMethod.GET)
    public String getThis() {
        return "test/this";
    }

    @RequestMapping(value="/that", method=RequestMethod.GET)
    public String getThat() {
        return "test/that";
    }

    @RequestMapping(value="/other", method=RequestMethod.GET)
    public String getOther() {
        return "test/other";
    }
}

Some of my Controller level request mappings have path variables too, so getting just the string value of the request mapping will not work. It will have to be resolved:

@Controller
@RequestMapping("/something/{anything}/test/")
public class SomethingController {
...
}

Update

Maybe if there was a way to modify the context path by appending the Controller request mapping to it BEFORE the Spring URL tag, that would solve the problem.

contextPath = contextPath/controllerRequestMapping

Then, I could do something like this because I believe Spring will automatically retrieve the current context path:

<%@ taglib uri="http://www.springframework.org/tags" prefix="s"%>

<a href="<s:url value="/that"/>">That</a>
<a href="<s:url value="/other"/>">Other</a>

This, of course, would be optimal! Ideas? Thoughts…?

Thanks in advance!

Best Answer

You could get the URI using the Servlet API. There is no "Spring" way to do this as far as I know.

@RequestMapping(value="/this", method=RequestMethod.GET)
public String getThis(HttpServletRequest request, Model m) {
    m.addAttribute("path", request.getRequestURI());
    return "test/this";
}

Then in your JSP:

<a href="${path}">This</a>

For more information about HttpServletRequest, see the API here.