Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC: Mapping Multiple URLs to Same Controller

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 C use DefaultController, while form D uses ControllerD.

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

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>
    

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

Has anyone done something like this?

like image 237
Tom Tucker Avatar asked Oct 10 '10 00:10

Tom Tucker


People also ask

Can we map multiple URL to a single endpoint?

Note: So, the point that you need to remember is, each resource must have a unique URL, and also it is possible that a resource can be accessed using multiple URLs as long as all the URLs are unique. But it is not possible to access two or more different resources using a single URL in ASP.NET Core Web API Application.

What is difference between @GetMapping and @RequestMapping?

@RequestMapping is used at the class level while @GetMapping is used to connect the methods. This is also an important Spring MVC interview question to knowing how and when to use both RequestMapping and GetMapping is crucial for Java developers.

Can two classes have same request mapping?

You cannot. A URL can only be mapped to a single controller. It has to be unique.

Can we have more than one controller in Spring MVC?

In Spring MVC, we can create multiple controllers at a time. It is required to map each controller class with @Controller annotation.


1 Answers

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

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

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

And then:

@Controller @RequestMapping(value="/formD.html") public class ControllerD {  } 
like image 62
jricher Avatar answered Sep 24 '22 02:09

jricher