2

I have a Spring MVC app.

This is the web.xml

    <xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Spring Web MVC Application</display-name>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>

</web-app>

I have a sample page Controller (TestController). with request mapping

@RequestMapping("/Test")
class TestController{
}

Am calling the controller using Test

When I click the link first time, its working fine

http://localhost:8008/App/Test

If i click the link, once again, it is appending Test once again

http://localhost:8008/App/Test/Test

and it keeps adding.

What could be the issue!

madhairsilence
  • 3,787
  • 2
  • 35
  • 76

2 Answers2

2

Instead of having

<a href="Test">link</a>

in your JSP, you should have

<a href="<c:url value='/Test'/>">link</a>

(and of course add the JSTL core taglib definition to the head of the JSP).

This will make use of an absolute URL (/App/Test) rather than a relative one (Test), and will automatically prepend the context path of the application (/App in your case) to the URL. This link can be used from anywhere in the application, and will always poit to your controller, whatever the URL of the current page is.

Another way is to use

<a href="${pageContext.request.contextPath}/Test">link</a>

but it's longer, less clean, and doesn't allow adding parameters to the URL like c:url does. Note that Spring also has an s:url tag that does the same thing, and more.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

An addition to @JB Nizet's answer, since it is not clear which viewResolver you are using and there might be other people looking for an answer to that question:

if you are using freemarker as a template engine, you can do that:

<a href="<@spring.url '/Test' />">link</a>

in your templates. This will let spring create the correct context path for you. url is the name of the macro here, and spring the reference name of the template.

Note: you have to import the spring.ftl-template for that beforehand, like so

<#import "spring.ftl" as spring/>

before you can use the macro.

matthaeus
  • 797
  • 2
  • 7
  • 17