How to do multiple URL mappings (aliases) in Spring

In specific

I want to do multiple URL mapping (in other words, aliases) in spring boot

In detail

In my spring boot application, the Customer Controller class is mapped primarily to the URL /customer , as shown below. I want to create easily modifiable aliases

 @Controller @RequestMapping(value = "/customer") public class CustomerController{ 

In my regular spring application, where I am doing the mapping in XML, I can do the URL mapping as shown below.

 <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/customer.htm">customerController</prop> <prop key="/tester.htm">customerController</prop> </props> </property> </bean> <bean id="customerController" class="com. ... .controller.CustomerController" /> 

Spring boot, property file configurations are useful in most cases, since autoconfig works under the roof.

  • Is there a way to do the same using property files.
  • What is the best practice when doing URL mappings in spring boot, which I can easily change after compilation.

I am tired to find it. But in the end, it helped SO. Please help me with this.

+6
source share
2 answers

If you want to control the display from the prop file, you can do this as shown below

In your application.properties application add a pair of key values

 url.mapping : /test/sample 

On the controller, you can do the following:

 @Controller @RequestMapping(value = { "${url.mapping}" }) public class CustomerController{ 

Instead of providing the prop in the file, if you provide url.mapping as jvm arg , then you do not need to recompile, if you change the value, just restart (which I hope you can do, you haven’t tried it yourself) should do the trick.

For multiple mappings, you need to add one for each mapping and display it in the controller, as shown below.

 @Controller @RequestMapping(value = { "${url.mapping}","${url.mapping.two}" }) public class CustomerController{ 
+12
source

Take a look at this example.

The best way to map url is to do this in a controller with annotations.

Basically:

 @RestController public class HelloController { @RequestMapping("/") public String index() { return "Greetings from Spring Boot!"; } } 

IMHO It is best to use one mapping for the controller and one for each method:

  @RestController @RequestMapping("/Hello") public class HelloController { @RequestMapping("/") public String index() { return "Greetings from Spring Boot!"; } @RequestMapping("/otherMapping") public String otherMapping() { return "Greetings from Spring Boot!"; } } 

So the URLs will look like this: localhost:8080/Hello and localhost:8080/Hello/otherMapping

Edit:

For multiple comparisons you can use:

 @RequestMapping({ "/home", "/contact" }) 
+8
source

Source: https://habr.com/ru/post/985134/


All Articles