Spring MVC Tutorial – Passing Request Parameters via JavaScript | JQuery Example
In this post I will show how to pass parameters into a controller via a java script ajax. The parameters will be passed into the Spring MVC controller with Jquery javascript example:
MyController.java
@RequestMapping(value = "/processmyvals", method = RequestMethod.GET)
public void process(@RequestParam(value = "myVal1", required = true) String myVal1, @RequestParam(value = "myVal2", required = true) String myVal2, HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println(myVal1);
System.out.println(myVal2);
//...
//writeResponse tha will be injected into as result in the ajax js below
}
myvals.html
... My Val1: My Val2: ...
myjavascript.js
function processMyVals(){
$.ajax({
type : 'GET',
url : "myapp/app/processvals",
data : { "myVal1":$("#myVal1").val(), "myVal2":$("#myVal2").val()},
success : function(result) {
$("#displayArea").html(result);
}
});
}
Conclusion
As we constantly see using Spring MVC controllers is very simple and straight forward. creating these kind of Spring MVC Controller | Jquery | Javascript come very handy and I use it a lot.
Am I miss something? The Controller serve only GET requests, but the JS POST request.
Thanks. I corrected the example. Both the controller and the js (type) should be consistent, GET or POST.