2
votes

What are the approaches to map i18n translated url paths?

For example lets say we talk about the follwing url (for locale en):

www.foo.tld/car/manufacturer

In german (de) this url would be

www.foo.tld/auto/hersteller

What i know about Controller RequestMapping i could use severel values to map these url's for one method like

@GetMapping(value={"/car/manufacturer/", "/auto/hersteller/"})

More seo optimized would be probably something with the current locale in the path like

@GetMapping(value={"/en/car/manufacturer/", "/de/auto/hersteller/"})

...but i dont want to start a discussion what would be the best uri seo wise.

This isn't so bad if to use only a few Locales/Languages but i would like to make this somehow dynamic. Currently im using messages_xx.properties to map url path parts for generating urls in my application, like:

messages.properties

uri.car=car
uri.manufacturer=manufacturer

messages_de.properties

uri.car=auto
uri.manufacturer=hersteller

Im using them already for building links repecting the user locale which works fine.

What im searching now for is a elegant, less error prune way to map these urls in my controller. If i would change for example a value for the key uri.car and would have a static RequestMapping in my controller like in the example above i also need to change it there (if i dont forget!). Also if i would like to add support for another language i would need to search in all controller and check if i need to add another value mapping.

Is there a smarter way how to map i18n path parts in Spring controllers, ideally respecting a request locale and resolve the path string with the help of messages_xx.properties? Or would be a filter the way to go extracting path parts according to the requested locale and use internally only one language for mapping urls?

1

1 Answers

0
votes

Supose that you have an EN message.properties and a DE message.properties with the following property:

url.car=/car/manufacturer/ in the EN

url.car=/auto/hersteller/ in the DE

In your @Controller you can get easily this properties configuring your messageSource and using it to get the properties:

Inject your configured MessageSource to allow Spring resolve the messages:

 @Autowired
 private MessageSource messageSource;

Then you can get all the properties from your message.properties file:

String url= messageSource.getMessage("url.car", put_here_your_locale);