Jackson helps you to "Ajaxify" your Spring service in less than 5 mins

You can now turn your Spring service into an ajax service easily with the use of annotation and Jackson

Let's say you have a service to search for a product, something like this:

public class productServiceImpl{

private ProductDao productDaoImpl;

public List search(String searchString){
productDao.search(searchString);
}

}

And usually your Spring MVC controller will be something like this

@Controller
@RequestMapping("/product")
public class ProductController{

private ProductService productService;

@RequestMapping("/search")
public List search(@RequestParam("searchString") String searchString, ModelMap model) {
return productService.search(searchString);
}

To expose the search service as an ajax service, simply
1. Add jackson to your library if you haven't do so
2. Add to your applicationContext.xml
Remember also add the schema Location
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
to specify the name space
3. add @ResponseBody before the return type in the method as follow

@RequestMapping("/jsonsearch")
public @ResponseBody List search(@RequestParam("searchString") String searchString, ModelMap model) {
return productService.search(searchString);
}

That's it!

To access this simply send request to
http://localhost:8080/myapp/product/search?searchString=iphone



Comments (0)

Post a Comment