简体   繁体   English

Spring MVC - 请求映射,具有两个不同参数的两个 url

[英]Spring MVC - Request mapping, two urls with two different parameters

Is it possible in Spring to have one method with two different urls with different params for each method?在 Spring 中是否有可能使用一种方法,该方法具有两个不同的 URL,每种方法具有不同的参数?

Below is pseudo code下面是伪代码

@RequestMethod(URL1-param1, URL2-param2)
public void handleAction(@ModelAttribute("A") A a, ...) {
}

At the same time ULR1 is mapped in some other Controller as同时 ULR1 映射到其他一些 Controller 为

@RequestMethod(URL1)
public void handleAction1(@ModelAttribute("A") A a, ...) {
}

Update: It appears your question is completely different.更新:看来您的问题完全不同。

No, you can't have the same url with different parameters in different controllers.不,您不能在不同的控制器中拥有具有不同参数的相同 url。 And it doesn't make much sense - the url specifies a resource or action, and it cannot be named exactly the same way in two controllers (which denote different behaviours).而且它没有多大意义 - url 指定资源或操作,并且在两个控制器中不能以完全相同的方式命名(表示不同的行为)。

You have two options:你有两个选择:

  • use different URLs使用不同的 URL
  • use one method in a misc controller that dispatches to the different controllers (which are injected) depending on the request param.在杂项 controller 中使用一种方法,该方法根据请求参数分派到不同的控制器(注入的控制器)。

Original answer:原答案:

No. But you can have two methods that do the same thing:不,但是您可以使用两种方法来做同样的事情:

@RequestMethod("/foo")
public void foo(@ModelAttribute("A") A a) {
    foobar(a, null);
}

@RequestMethod("/bar")
public void bar(@ModelAttribute("B") B b) {
    foobar(null, b);
}

If I haven't understood correctly, and you want the same ModelAttribute, then simply:如果我没有正确理解,并且您想要相同的 ModelAttribute,那么只需:

@RequestMapping(value={"/foo", "/bar"})

And finally - if you need different request parameters, you can use @RequestParam(required=false) to list all possible params.最后 - 如果您需要不同的请求参数,您可以使用@RequestParam(required=false)列出所有可能的参数。

you can supply multiple mappings for your handler like this您可以像这样为您的处理程序提供多个映射

@RequestMapping(value={"", "/", "welcome"})
public void handleAction(@ModelAttribute("A") A a, ...) { }

But if you want to use different parameters for each mapping, then you have to extract your method.但是如果你想为每个映射使用不同的参数,那么你必须提取你的方法。

Something like this像这样的东西

@RequestMapping(value={"URL1"}, method=RequestMethod.POST)
public String handleSubmit(@ModelAttribute("A") A command, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    return helperSubmit();
}

@RequestMapping(value={"URL2"}, method=RequestMethod.POST)
public String handleSubmit(@ModelAttribute("A") A command, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    return helperSubmit();
}

private helperSubmit() {
  return "redirect:" + someUrl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM