Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hard-coded @RequestMapping URL in Spring MVC Controller

I'm studying Spring 3 and I'm using it in a simple web-application.

Now I'm implementing a Spring MVC Controller using annotations, and I'm wondering: Is there any best practice using @RequestMapping annotation?

I mean: I've seen that usually the URL mapped in this annotation is hardcoded in the class...
Is there a way to pass the URL in a 'loosely coupled way' (to obtain a more reusable class)?

I know that there are some wild cards that can be used, but I think that isn't the solution... Am I wrong?

EDIT:

I add an example to better explain my doubt.

Suppose I want my controller to be triggered by a request to /foo/bar/baz/mypage.htm, in my controller the handler method will be annotated with @RequestMapping("/foo/bar/baz/mypage").

Now I decide to change the URL triggering my controller into /foo/bar/otherpage.htm, so i need to edit my class, put @RequestMapping("/foo/bar/otherpage") on my handler method, recompile the project and deploy it again.

It seems to me not so practical...

like image 941
davioooh Avatar asked Dec 01 '11 09:12

davioooh


1 Answers

Currently annotated controllers aren't very configurable.

As far as I know, the only possible approach to this problem is to use alternative HandlerMappings in order to configure "base URLs" of controllers. For example, as follows:

// Note the absense of @Controller to prevent this controller
// from being discovered by DefaultAnnotationHandlerMapping
public class FooController {
    @RequestMapping("/list") public String list(...) { ... }
    @ReqeustMapping("/save") public String save(...) { ... }
}

.

<bean 
    class = "org.springframework.web.servlet.mvc.support.ControllerBeanNameHandlerMapping" />

<bean name = "/foo" class = "FooController" />
<bean name = "/bar" class = "FooController" />

In this example two instances of FooController handle /foo/list, /foo/save, /bar/list and /bar/save respectively.

The upcoming Spring 3.1 will have an improved Spring 3.1 architecture (Spring 3.1 M2: Spring MVC Enhancements) that seems to be more flexible, though I haven't checked it yet.

like image 151
axtavt Avatar answered Oct 17 '22 20:10

axtavt