3

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>
4

1 回答 1

2

您应该通过使用 JSP EL 在您的脚本中检索上下文根来让客户端知道正确的 URL。

在 JSP 中

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

然后,您可以将其ctx用作通过 Javascript 构建的 URL 的前缀。

var url = ctx + "/rest_of_url"

在服务器端,您可以使用:

${pageContext.request.contextPath}或者 JSTL 有一个标签,<c:url>它将附加您的上下文根。

于 2013-04-30T14:12:29.550 回答