Spring MVC multiple requestmapping , missing requestparam

1.4k views Asked by At

I need to handle two @RequestMapping values by one method.For example /create and create/{id}

@RequestMapping(value = {"create","create/{id}"}, method = RequestMethod.GET)
public String create_form(@PathVariable(value = "id") Long id,Model model, @ModelAttribute("channelNode") ChannelNode channelNode,
        BindingResult result) {

      if(id>0){ //or if id exsist 

      //do something

      }

    return CHANNELNODE_ADD_VIEW;
}

But it doesn work when I run simple "create" url, without any param/

It shows me following Error:

HTTP Status 500 - Missing URI template variable 'id' for method parameter of type Long

type Status report

message Missing URI template variable 'id' for method parameter of type Long

description The server encountered an internal error that prevented it from fulfilling this request.

1

There are 1 answers

2
ScanQR On BEST ANSWER

Unfortunately there is not way you could do this with @PathVariable.

You need to do it by defining 2 separate handler methods,

  1. One without path variable

     @RequestMapping(value = "create", method = RequestMethod.GET)
     public String create_form(Model model, @ModelAttribute("channelNode") ChannelNode channelNode,
        BindingResult result) {
    
        return CHANNELNODE_ADD_VIEW;
     }
    
  2. One with path variable

    @RequestMapping(value = "create/{id}", method = RequestMethod.GET)
    public String create_form(@PathVariable(value = "id") Long id,Model model, @ModelAttribute("channelNode") ChannelNode channelNode,
        BindingResult result) {
    
        return CHANNELNODE_ADD_VIEW;
    }