Mahesha M
Mahesha M

Reputation: 135

Spring mvc controller - how to do url restrictions

This is spring mvc controller /city/{cityName}

@RequestMapping(value = "/city/{cityName}")
     public String getCity (@PathVariable("cityName") String cityName, Model uiModel) {

}

www.example.com/city/{cityName}

Here cityName is dynamically loaded from url, my website can't support some of cityName, it supports only Bengaluru, Kochin, Hyderabad and Chennai, due to dynamic things it supports other cities or whatever in the place of cityName, it gives error, how to restrict cityName for only 4 cities mentioned above.

Is there any way in controller itself or we have to maintain table(hard coded hashtable)

Suggest which is the best way to do

Upvotes: 0

Views: 510

Answers (3)

Mahesha M
Mahesha M

Reputation: 135

We can do at controller level statically @RequestMapping(value = "/city/{cityname:bengaluru|chennai|kochin|hyderabad}") OR we can create tables, query and put it in hashtable at application start up time.

Upvotes: 0

Bohuslav Burghardt
Bohuslav Burghardt

Reputation: 34776

If you just want to have the four cities hardcoded in your code, you can also specify them using regular expression in @RequestMapping.

@RequestMapping("/cities/{cityName:Bengaluru|Kochin|Hyderabad|Chennai}")
public String getCity(@PathVariable("cityName") String cityName) {

}

That way if you specify a city which does not match the allowed values your controller will automatically return HTTP 404.

Update: Fixed the sample, the regex should go in @RequestMapping, not @PathVariable, sorry for the mistake

Upvotes: 1

You'll either need separate controller mappings or to look up the cityName somewhere. That doesn't have to be hard-coded; you could instead use a YAML or properties file to initialize a Set or look it up in a database.

Upvotes: 0

Related Questions