Ajax in the Java MVC world ? How hard can it be ?

It’s actually not that hard…..It’s just …… verbose and time consuming. Well, let’s dive in, shall we.

Context : A friend of mine asked : “How do I include a jsp inside a jsp ? When user clicks a button. It has gotta do with the AJAX things but how do I do that?”

“Yep. You fire AJax to the server and the server process requests and send back the content to the front end. But actually, how to do it in the Java world( Its a breeze with Flask/Python). Give me a minute, Im working on a proof of concept, will get back to you ” ….Actually give me one more day to mess with XML and all.

Eclipse: where you don’t know see sunlight at all.

Used to be de-facto standard IDE of choice of Java people, now I hear people’ve been swagging Jetbrains and Android Studio. Problem is my Mac does not even run it properly. Eclipse wins in this department( although I have not tried programming Android on Eclipse yet, probably hogging memory too).

One of the new changes I saw coming back to Eclipse is it being more user friendly. You are welcomed by this nice cartoon-ish looking customization messages first time you opened it. Auto sync. Checked. Line Number. Absolutely. Grammar. Right on. etc. etc. Last time I left Eclipse I don’t remember it being this cool

Eclipse.More user friendly
Eclipse.More user friendly

Gradle : your next friendly-not-friendly fiend

Believe it or not. Gradle is slowly taking shape to be the best build tool. They said it is fast and awesome. Achieved same job with less line than ant or whatever. The last company I worked at they loved Gradle, said they recode the whole build ant system in less than 100 lines. Last I checked they just run ant under Gradle( that is gradle task just run ant tasks — its beyond me why they call it refactor; this is just abstract one more layer), cheeky. Remember ant is scolded at because of errr xml.

So I need to quickly generate a sample java+eclipse+springmvc project. Googling around gives back this tutorial from spring people. Its called SpringBoot. I was skeptical at first but nah lets try it out. SpringBoot runs app through mvn , a tool from maven people and I dont want to download it. Hmm, last I recall I used spring mvc + tomcat the adhoc way(copying all the dependent jar) so there gotta be a way to do it in gradle as well. It is taking so hard to just google the single little piece of information you need.

Alas I figured it out, put these into your build.gradle file

apply plugin: 'eclipse-wtp'
apply plugin: 'jetty'

dependencies {
	compile 'org.springframework:spring-webmvc:4.1.6.RELEASE' //springmvc
	compile 'javax.servlet:jstl:1.2'    //jsp tag libs
	compile 'javax.servlet:servlet-api:2.5' //servelet to handle request
//port and default path to put in your browser address
//... http://localhost:8080/spring4
	contextPath = "spring4"
	httpPort = 8080

First, lets look at the front end first, and do the ajax things. Easy, enter jquery. Im gonna have an input field for user to type something and when the user click the button, a message underneath the field would say : “Hello, {typed_info}”, so here is the quick form:

<div class="row">

<div class="form-group">
     <input id="search_field" type="text" name="q" class="form-control" value="">

<div id="hello">

   <button id="ajaxButton" class="btn btn-default">Search</button>

And here is our ajax code, it takes the value of input and send it to the server at the path: hello/{name}


$('#ajaxButton').click(function() { 
	var data =$("#search_field").val();
	console.log("hello:" + data)
	//var data = {};
	//data["name"] = $("search_field").val();
	//console.log("button click: sending data:{" + JSON.stringify(data) + "}");
        url: 'hello/' + data,
        type: 'GET',
        //data: JSON.stringify(data),
        success: function (result) {
          console.log("success:data=" + result);


I ended up using PathVariable as a quick way to handle this ajax as the others such as RequestBody, RequestParam were giving error of Bad Request. From the server side:

@RequestMapping(value = "/hello/{name}", method = RequestMethod.GET)
	public @ResponseBody String hello(@PathVariable String name) {
		//String name = request.getParameter("name");
		return "hello + <b>" + name + "</b>";

And we run, not so fast



Before it can serve content, you have to wire servlet, Java server code that we annotate with controller( extends from JavaHttpServlet class )


<!--inside webapp -->


	<!-- For root context -->


And tell it where we store our view, which is our frontend codes


<context:component-scan base-package="hello" />
        <!-- jsp files -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
		<property name="prefix" value="/WEB-INF/views/jsp/" />
		<property name="suffix" value=".jsp" />
        <!-- resources -->
	<mvc:resources mapping="/resources/**" location="/resources/" />
	<!-- annnotation files -->
	<mvc:annotation-driven />

Then we run the server with gradle jettyRun and voila

Hello abc
Hello abc

That, tobe honest was quite an effort just to set things up but performance wise I think it is more scalable.


Check the project at : https://github.com/hoduc/SpringMVCJSP




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 )

Google+ photo

You are commenting using your Google+ 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