user1915570
user1915570

Reputation: 386

multiple post ajax to different methods in the same controller

I am newbie for jquery, js, java, etc all this world. I am using spring mvc maven.

I have a jsp file with two post functions with different url which is matching with two different methods in same controller.

so I expected =>

but both caseAsendand caseBsend ends up to the same handler in myController.java

[note] caseAsend, caseBsend are called by different behaviors in jsp file and also need to process differently in controller. so it should be handled seperately

[Q] How can I make 1:1 mapping between post ajax and handling method in myController.java. why both posts goes to the same method even with different url?

[My code is like this] :

1) myTest.jsp

function caseAsend(title, id){     
    $.ajax({
            url:'/test/{caseA}.html',
            data: 'title='+title+'&id='+id+'&something'+something,
            type:"POST",
            success: function(response){
                    alert('caseA done');
            }   
  });
}

function caseBsend(title, id){     //something wrong
     $.ajax({
                  url:'/test/{caseB}.html',
                  data: 'title='+title+'&id='+id+'&somethingelse='+somethingelse,
                  type:"POST",
                  success: function(response){
                                alert('caseB done!');
            }   
     });
}

2) myController.java

@RequestMapping(value="/test/{caseA}", method = RequestMethod.POST)
public @ResponseBody String caseAHandler(@RequestBody String  response) {
      …
      ...
}

@RequestMapping(value="/test/{caseB}", method = RequestMethod.POST)
public @ResponseBody String caseBHandler(@RequestBody String  response) {
{
    ….
    …
}

I have looked other answers something similar for a few days but I couldn't really cleared it out. what I am doing incorrect here?

maybe it is so obvious or simple to someone knows well about this world. but I can't clear it out why both posts goes to the same method even with different url. I am really appreciated if someone clear this out.

Upvotes: 0

Views: 832

Answers (1)

Stan
Stan

Reputation: 1430

Value in {} is a URL placeholder. So your caseAHandler will react on any /test/a, /test/bb, etc. URLs.

If you need separate handlers react on separate URL try to remove {}.

@RequestMapping(value="/test/caseA", method = RequestMethod.POST)
@RequestMapping(value="/test/caseB", method = RequestMethod.POST)

And same in your JSP

Upvotes: 1

Related Questions