Basically, I’ve currently got an MVC project I’m working on where I can pass values from the server to the client using the following class…
package org.assessme.com;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class UserManagementController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/userManagement", method = RequestMethod.GET)
public Object home(Locale locale, Model model) {
logger.info("User management view controller loaded...");
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "userManagement";
}
}
This can then be accessed using the notation…
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello world!
</h1>
<P> The time on the server is ${serverTime}. </P>
</body>
</html>
My question is, how would I change this project so that I could use JSON as the Ajax requests so say a user clicks a button that has…
function userManage(){
$('div.mainBody').load('userManagement');
}
I want userManagement to return the view userManagement (like it does now), but also a json response of users.
Can anyone give me any advice around this?
Thanks,
In this post, the author explains how you can achieve this using Spring.
In your controller, you should have something like the below to return a JSON.
In your view, you should write a request using JQuery.
EDIT: You should also check this answear. If you add Jackson jars to your libs, Spring will start to parse your POJOS to JSON.