Home > Ajax, J2EE, MVC, Spring Framework, Spring MVC 3 > Spring MVC Tutorial – Passing Request Parameters via JavaScript | JQuery Example

Spring MVC Tutorial – Passing Request Parameters via JavaScript | JQuery Example

February 10th, 2013 Leave a comment Go to comments

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.

  1. Eugene
    February 13th, 2013 at 11:46 | #1

    Am I miss something? The Controller serve only GET requests, but the JS POST request.

    • February 15th, 2013 at 03:37 | #2

      Thanks. I corrected the example. Both the controller and the js (type) should be consistent, GET or POST.

  1. No trackbacks yet.
You must be logged in to post a comment.