I’m playing around with some web frameworks lately and to see what’s in store with Spring 3 MVC (never did too much with it) I gave it a try to see how it handles Ajax. According to ajax simplification announcement it should be possible to get up and running in (almost) no time.
We will do a simple web application which will show the current time via Ajax.
The directory layout (using maven) should look like this:

Directory Layout
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Spring3MVC</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>spring</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> </web-app>
The web.xml holds no secrets. The Dispatcher servlet is defined and it should react on everything *.html.
Since we named our Servlet ‘spring’ we need to add a servlet configuration for that. It goes in WEB-INF as well.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.maxheapsize.springmvc3.controller" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
It uses the component scanning feature of spring and instructs spring to check the package ‘com.maxheapsize.springmvc3.controller’ for controllers. Furthermore a url based view resolver is defined which uses Jstl and looks into /WEB-INF/jsp for jsp with the ending ‘.jsp’.
In WEB-INF/jsp/hello.jsp we define a jQuery snippet for the Ajax request and provide a button which we should push if we want to know the time.
<jsp:useBean id="message" scope="request" type="java.lang.String"/>
<html>
<head>
<title>Spring MVC Ajax Demo</title>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script type="text/javascript">
function doAjax() {
$.ajax({
url: 'time.html',
data: ({name : "me"}),
success: function(data) {
$('#time').html(data);
}
});
}
</script>
</head>
<body>
${message}
<button id="demo" onclick="doAjax()" title="Button">Get the time!</button>
<div id="time">
</div>
</body>
</html>
How does Spring now know which classes or methods to call? Here comes the nice part about it.
package com.maxheapsize.springmvc3.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.Date;
@Controller
public class HelloWorldController {
@RequestMapping("/hello")
public ModelAndView helloWorld() {
return new ModelAndView("hello", "message", "Spring MVC Demo");
}
@RequestMapping(value = "/time", method = RequestMethod.GET)
public @ResponseBody String getTime(@RequestParam String name) {
String result = "Time for " + name + " is " + new Date().toString();
return result;
}
}
The RequestMappings define the Url’s which can be called to reach that code. So the helloWorld method is available with ‘hello.html’ in the web app. Why hello.html and not just hello ? Because we said so in the web.xml. I included a sample message which will be shown at the web page when this method is called.
If you now push the button on the webpage, ‘time.html’ with a parameter ‘name’ is called. This will go directly to the second method. Spring will also check if a string parameter ‘name’ (@RequestParam) is present in the original request. The @ResponseBody annotation indicates that a method return value should be bound to the web response body.
The result will be returned and shown in the webpage.

Ajax Result
Overall this is a pretty nice integration. I tend to use Spring for many projects and this makes it even easier to write some nice web apps in it. If you have a single page application and all you do is sending ajax request back and forth this might be a solution.
JSON response Update
To get a JSON response from your Controller you need to:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.5.3</version>
</dependency>
in their pom.xml.
@RequestMapping(value = "/demo", method= RequestMethod.GET) public @ResponseBody MySimpleDataObject doSomething(@RequestParam name, @RequestParam email)
jQuery.getJSON("demo.html", {name: name, email: email}, function (data) {
alert(data.someValueInMySimpleDataObject);
});
See also Ralf’s post about Json and Spring MVC.
If you developed an ajax rich web application, maybe even a single page interface, you want to make sure that the user gets notified if the server is not reachable anymore. This happens either if the it goes down or the client loses its network connection.
Depending on your code the application can run for a while and the user is confused about missing interactivity.
So how do you detect this? jQuery offers an error callback if something with the call goes wrong.
window.setInterval(function() {
$.ajax({
type: 'GET',
  url: 'http://www.myapp.com/heartbeat',
  success: function(data, textStatus, XMLHttpRequest) {},
error: function(XMLHttpRequest, textStatus, errorThrown) {
  alert('Failure');
  }
 });
}, 2000);
Unfortunately this does not work for a server which is down and if you are using a debugger like Firebug you will see that these calls have the status aborted. It turns out that if the server goes away jQuery will still execute the success callback. So how do you know that the server died?
I changed the response of the heartbeat query to contain some simple string like ‘alive’. In the success callback I just check if the data contains this string. If it does not, I know that I do have a problem and I need to make sure that the user can’t do anything anymore.
I use the jQuery plugin uiBlock to block every interaction and show a nice little message. Check out the uiBlock demos.
var uiBlocked = false;
window.setInterval(function() {
$.ajax({
cache: false,
type: 'GET',
url: '/mywebapp/alive.txt',
timeout: 1000,
success: function(data, textStatus, XMLHttpRequest) {
if (data != 'alive') {
if (uiBlocked == false) {
uiBlocked = true;
$.blockUI({
message: "I'm trying to connect to the server.",
css: {
border: 'none',
padding: '15px',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
opacity: .5,
color: '#fff'
} });
}
} else {
if (uiBlocked == true) {
uiBlocked = false;
$.unblockUI();
}
}
}
})
}, 2000);
This code will check the server every 2 seconds and will block the UI when the server is not reachable and will come back up if the connection is alive again. Depending on your scenario (intranet/internet) you can change the interval for checking the connection.
This took me a couple of hours to get to this point and I thought it might be worth sharing. It seems a bit hacky but it works. What do you think?
I use Apache Trinidad at work and since JSF 2 is now final I decided to play with it a bit.
Of course this is going to be the classic Hello World example (as there are many other like this around the web).
First you need to setup a simple Maven project.
The file layout should be something like that.

Directory Layout for JSF 2 Ajax Demo
After that change your pom.xml to include the servlet and jsf2 libs.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.maxheapsize</groupId>
<artifactId>jsf2demo</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>jsf2demo Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.0.0-b13</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.0.0-b13</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<build>
<finalName>jsf2demo</finalName>
</build>
<repositories>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2</url>
</repository>
</repositories>
</project>
First we are going to create the managed bean to hold the name we are going to enter.
package com.maxheapsize.jsf2demo;
import javax.faces.bean.*;
import java.io.Serializable;
@ManagedBean
@SessionScoped
public class HelloWorldBean implements Serializable {
private String name = "";
@ManagedProperty(value = "#{demoService}")
private Service service;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setService(Service service) {
this.service = service;
}
public String getReverseName() {
return service.reverse(name);
}
}
To demonstrate the dependency injection with JSF 2 I use a service to reverse the name. Simply add the @ManagedProperty with the name of the service and it will get injected. Of course we need the service. Here it is:
package com.maxheapsize.jsf2demo;
import javax.faces.bean.*;
@ManagedBean(name="demoService")
@ApplicationScoped
public class Service {
public String reverse(String name) {
return new StringBuffer(name).reverse().toString().toLowerCase();
}
}
Very simple…isn’t it ?
The only thing what’s missing is the web.xml and the webpage itself.
The web.xml is pretty straight forward and should not show any surprises.
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Web Application</display-name>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
</web-app>
The index.xhtml has some differences from earlier versions of JSF. First, JSF now supports Ajax out of the box. To have this enabled you need to load the jsf.js javascript library. The inputText tag binds to our managed bean and includes an f:ajax tag. This tag determines which part should be rerendered (in this case the element with the id reverseName). F:ajax will execute on value holding components always with an ‘onchange’ event and on action components (like commandButtons) with an ‘onclick’ event.
The output will trigger the injected service in our managed bean and return the reversed input string.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>JSF Demo</title>
</h:head>
<h:body>
<h:outputScript name="jsf.js" library="javax.faces" target="body">
</h:outputScript>
<h1>Ajax JSF 2 Demo</h1>
<h:form>
<h:inputText id="name" value="#{helloWorldBean.name}">
<f:ajax render="reverseName"/>
</h:inputText>
<h:commandButton value="Say reverse Hi via Ajax">
<f:ajax execute="name" render="reverseName"/>
</h:commandButton>
<h:outputText id="reverseName" value="#{helloWorldBean.reverseName}"/>
</h:form>
</h:body>
</html>

JSF 2 Ajax Demo
And that’s it. Sure it’s a simple example, but so far I do like the minimal configuration and the ajax integration.