carcaret
carcaret

Reputation: 3368

Spring MVC request mapping conflict

I'm having an issue regarding @RequestMapping on classes. Say I have these two controllers:

@Controller
@RequestMapping(value="/controller1")
public class Controller1 {

    @RequestMapping(value="/method11.do")
    public @ResponseBody method11(){
            //...
    }

    @RequestMapping(value="/method12.do")
    public ModelAndView method12(){
            //This method redirects me to another jsp where I'll call Controller2 methods
            return new ModelAndView("test");

    }
}

@Controller
@RequestMapping(value="/controller2")
public class Controller2 {

    @RequestMapping(value="/method21.do")
    public @ResponseBody method21(){
            //...
    }

}

When I first call via AJAX method11, it works fine, the url generated is http://mydomain/myapp/controller1/method11.do

Then, I call method12 and get redirected to test.jsp, and from there, I call to method21, and here is the problem, the url generated is not the expected http://mydomain/myapp/controller2/method21.do, but something else, depending on how I make the AJAX call:

url:'controller2/method21' --> http://mydomain/myapp/controller1/controller2/method21.do
url:'/controller2/method21' --> http://mydomain/controller2/method21.do

So, in what way should I make the calls so that they always start at http://mydomain/myapp/...?

I believe I could just use url:'/myapp/controller2/method21.do', but I guess there should be a more generic way in which I don't have to use 'myapp' on every call.

This is my web.xml:

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

<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

Upvotes: 3

Views: 1610

Answers (1)

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

You should make the client aware of the proper URL by retrieving the context root within your script using JSP EL.

In JSP

<script>var ctx = "${pageContext.request.contextPath}"</script>

You can then use ctx as a prefix to the URLs constructed via Javascript.

var url = ctx + "/rest_of_url"

On the server side, you can use:

${pageContext.request.contextPath} or JSTL has a tag, <c:url> which will append your context root.

Upvotes: 2

Related Questions