Calling Spring web services from jQuery

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:

@Controller
public class BankController extends BaseJSONController implements BankControllerIntf {
	@Autowired
	ConfigurationDaoIntf dao;
	@Override
	@SessionRequired
	@RoleRequired(UserRole.user)
	@RequestMapping("/ebank/paymentList")
	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:

$(document).ready(function(){
		    $.getJSON("/appcontext/ebank/paymentList?callback=?",
					{ "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));
						});
						$("#imageLoading").hide();
						$("#portfolioId").fadeIn();
			        });
	    });

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

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.