I've a request mapping that handles any string after the context e.g. www.example.com/anystring
I'm handling it as follows:
@RequestMapping(value="/{str}", method = RequestMethod.GET)
public String getApp(@PathVariable("str") String anyString, ModelMap model) {
//Do something
}
The problem is I've 2-3 URLs in my app where the URL is as follows: www.example.com/about, www.example.com/contact etc.
I wrote Request Mappings for them as follows:
@RequestMapping("/about")
public String getAboutPage() {
return "about";
}
But obviously, since I've already declared that any string should be handled by the getApp()
, the getAboutPage()
never gets executed.
How can I exclude /about
, /contact
etc from getApp()
mapping.
We can obviously add another keyword to the URL string, but that's not possible in my app use case.
Kindly help. :(
EDIT:
Should I just handle /about
, /contact
inside getApp()
like:
@RequestMapping(value="/{str}", method = RequestMethod.GET)
public String getApp(@PathVariable("str") String anyString, ModelMap model) {
if(anyString.equals("about")){
//do about related stuff
}
if(anyString.equals("contact")){
//do contact related stuff
}
//Do something
}
Is there a better way?
@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.
The @RequestMapping annotation can be applied to class-level and/or method-level in a controller. The class-level annotation maps a specific request path or pattern onto a controller. You can then apply additional method-level annotations to make mappings more specific to handler methods.
The HTTP request methods to map to, narrowing the primary mapping: GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE. Assign a name to this mapping. The parameters of the mapped request, narrowing the primary mapping.
Specifying the HTTP request method in the "catch-all" mapping is probably making the path matcher consider it to be more specific than the absolute path mappings.
Specify the request method on the absolute paths, and the mapping comparator should order the absolute matches before the one containing the path variable.
eg.
@RequestMapping("/about", method = RequestMethod.GET)
Alternatively, you could remove the method specification on the catch-all:
@RequestMapping("/{str}")
It is entirely dependent upon your url structure and whether or not any of those paths will accept different http request methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With