Controller
To simulate a remote server, we create a fake remote controller:@Controller @RequestMapping(value = "/MyRemoteData") public class MyRemoteController { @RequestMapping(value="/{time}", method = RequestMethod.GET) public @ResponseBody MyRemoteData getMyRemoteData( @PathVariable long time) { return new MyRemoteData( "My remote data called at: " + time + " !!!"); } }
public class MyRemoteData { private String data = ""; public MyRemoteData() { } public MyRemoteData(String message) { this.data = message; } // Setter & Getters }
@Controller @RequestMapping(value = "/MyData") public class MyRESTController { @RequestMapping(value="/{time}", method = RequestMethod.GET) public @ResponseBody MyData getMyData( @PathVariable long time) { RestTemplate restTemplate = new RestTemplate(); String remote = "http://localhost:8585/spring-server-side-rest-call/" + "MyRemoteData/" + System.currentTimeMillis(); MyRemoteData mrd = restTemplate.getForObject( remote, MyRemoteData.class); return new MyData(System.currentTimeMillis(), mrd.getData()); } }
Main Page
We simplify our main page and only keep our GET button:<%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!doctype html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;" charset=UTF-8"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"> </script> <script type="text/javascript" src="<c:url value='/resources/js/SpringServerSideRestCall.js'/>"> </script> <title>Welcome To REST With Java !!!</title> </head> <body> <h1>Welcome To REST With Java !!!</h1> <button type="button" onclick="RestGet()">GET</button> </body> </html>
var prefix = "/spring-server-side-rest-call"; var RestGet = function() { $.ajax({ type: 'GET', url: prefix + "/MyData/" + Date.now(), dataType: 'json', async: true, success: function(result) { alert("At " + result.time + ": " + result.message); }, error: function(jqXHR, textStatus, errorThrown) { alert(jqXHR.status + " " + jqXHR.responseText); } }); }
Running The Example
Once compiled, the example can be run with mvn tomcat:run. Then, browse:http://localhost:8585/spring-server-side-rest-call/
The main page will be displayed:
If you click on get, a pop-up is displayed:
More Spring related posts here.
No comments:
Post a Comment