Java Spring MVC:将多个 URL 映射到同一个控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3898442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 06:30:14  来源:igfitidea点击:

Spring MVC: Mapping Multiple URLs to Same Controller

javaspringspring-mvc

提问by Tom Tucker

I have like 20+ forms which are linked from the same page. Some forms share the same controller, while others use their own. For example, form A, B, and Cuse DefaultController, while form Duses ControllerD.

我有 20 多个从同一页面链接的表单。一些表单共享同一个控制器,而另一些则使用自己的控制器。例如, form ABCuse DefaultController,而 formD使用ControllerD.

What I would like to achieve is to map the URL to each form in a consistent way.

我想要实现的是以一致的方式将 URL 映射到每个表单。

So, ideally, the link page would look like :

因此,理想情况下,链接页面应如下所示:

  • either this

    <a href="/formA.html">Form A</a>
    <a href="/formB.html">Form B</a>
    <a href="/formC.html">Form C</a>
    <a href="/formD.html">Form D</a>
    
  • or this:

    <a href="/form.html?name=A">Form A</a>
    <a href="/form.html?name=B">Form B</a>
    <a href="/form.html?name=C">Form C</a>
    <a href="/form.html?name=D">Form D</a>
    
  • 要么这个

    <a href="/formA.html">Form A</a>
    <a href="/formB.html">Form B</a>
    <a href="/formC.html">Form C</a>
    <a href="/formD.html">Form D</a>
    
  • 或这个:

    <a href="/form.html?name=A">Form A</a>
    <a href="/form.html?name=B">Form B</a>
    <a href="/form.html?name=C">Form C</a>
    <a href="/form.html?name=D">Form D</a>
    

The question is how to map each URL to the appropriate controller. With the first URL pattern, you would map formD.htmlto ControllerD, but not sure how to map form[A|B|C].htmlto DefaultController. With the second URL pattern, I don't even know where to begin...

问题是如何将每个 URL 映射到适当的控制器。使用第一个 URL 模式,您将映射formD.htmlControllerD,但不确定如何映射form[A|B|C].htmlDefaultController。使用第二个 URL 模式,我什至不知道从哪里开始......

Has anyone done something like this?

有没有人做过这样的事情?

回答by jricher

Since nobody seems to have put the full answer on here yet:

由于似乎没有人在这里给出完整的答案:

The @RequestMappingannotation can take an array for its "value" parameter. To map this at the controller level using the first pattern, you would use:

所述@RequestMapping注释可以采取为它的“value”参数的阵列。要使用第一种模式将其映射到控制器级别,您可以使用:

@Controller
@RequestMapping(value={"/formA.html", "/formB.html", "/formC.html"})
public class ControllerA {

}

And then:

进而:

@Controller
@RequestMapping(value="/formD.html")
public class ControllerD {

}