What are the recommended approaches for generating routes in Spring MVC?

What are the recommended approaches to generating routes in the java-based Spring MVC webapp? I would like to avoid hard coding paths throughout the application.

+6
source share
2 answers

Assuming we're talking about RequestMappings paths, etc. In my application, I have one class with public static final constant binding, which I refer to in the @RequestMapping annotation.

So constants might look like this:

 public class Pages { public static final String FOO_URL "foo/foo.action" public static final String FOO_VIEW "test/foo" public static final String BAR_URL "bar/bar.action" public static final String BAR_VIEW "test/bar" } 

then inside your controller you will refer to them as follows:

 @RequestMapping(value=Pages.FOO_URL, method=RequestMethod.GET) public String handleFoo(Model model) { return Pages.FOO_VIEW; } 

They are easy to change because they are all in one place.

+2
source

You say you want to avoid hard-coding paths throughout the application, but usually all controllers (and therefore all url mappings) are in the same directory. For example, if you have a maven structure, they will be somewhere like src / main / java / com / mycompany / myapp / web / controller /. Do you imagine a task to the question: "Where did I place the URL for the / myapp / v1 / search endpoint?" And could not understand what is it in / src / main / java / com / mycompany / myapp / web / controllers / V 1SearchController.java?

Also, as soon as you select the URLs, they are pretty fixed because they are an interface with clients, and changing them probably means backward compatibility.

Not that I thought that a class with a bunch of static final lines is all bad, I just think that it’s basically not necessary.

-1
source

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


All Articles