How to create a default method in SpringMVC using annotations?

夙愿已清 提交于 2019-12-05 03:28:33
Leniel Maccaferri

Take a look at this answer:

Spring MVC and annotated controllers issue

What if you annotate a method with:

@RequestMapping(method = RequestMethod.GET)

You can see an example here:

Spring 3.0 MVC + Hibernate : Simplified with Annotations – Tutorial

The same behavior can be seen here:

Spring Framework 3.0 MVC by Aaron Schram (look at page 21)

Short answer: I do not know how to simply specify one method as default with a simple tag.

But there is this ...

I do not know in which version of Spring this was implemented, but you can provide multiple values to @RequestMapping in 3.1.2. So I do this:

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping(value = {"", "/", "/list"}, method = RequestMethod.GET)
    public String listUsers(ModelMap model) { }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ModelAndView add(HttpServletRequest request, ModelMap model) { }

}

The following URLs then map to listUsers():

I would create one default method without RequestMapping's value in there. Please see method defaultCall() below. You can then simply call them with URL: [yourhostname]/user

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping(method = RequestMethod.GET)
    public String defaultCall( MapModel model ) {
        //Call the default method directly, or use the 'forward' String. Example:
        return authenticate( model );
    }

    @RequestMapping("login")
    public String login( MapModel model ) {}

    @RequestMapping("logout")
    public String logout( MapModel model ) {}

    @RequestMapping("authenticate")
    public String authenticate( MapModel model ) {}
}

Ref: Spring Framework Request Mapping

Simply using @RequestMapping("**") on your default method should work. Any more specific mappings should still pick up their requests. I use this method for setting up default methods sometimes. Currently using Spring v4.3.8.RELEASE.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!