Archive for November, 2011

Calling Spring web services from jQuery

November 11, 2011

I love both frameworks because they are awesome. So here is how you can make Spring 3.0 and jQuery 1.5 work smoothly together, letting you forget about integration pain and concentrate on actual functionality.

Annotate your Spring service like:

public class BankController extends BaseJSONController implements BankControllerIntf {
	ConfigurationDaoIntf dao;
	public @ResponseBody Map<String, String> getList(Session session,
			@RequestParam("type") String type,
			@RequestParam(value="report", required = false) String report,
			HttpServletResponse response) {
               // backend functionality here

BTW don’t forget to instruct Spring to resolve the @Controller-annotatated services in the applicationContext.xml:

<context:component-scan ....>
    <context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>

and include Jsonp filter to the server configuration, just next to the Hibernate Open Session In View Filter.

Then make jQuery call it:

					{ "type": $("input[name=type]").val(),
					  "report": $("input[name=report]").val()
				    function(data) {
						// UI manipulation here
						var options = $("#portfolioId");
						$.each(data, function(i, object) {
							options.append($("<option />").val(i).text(object));

and it will deliver the data straight to your web page. That’s it!