Showing posts with label Remote. Show all posts
Showing posts with label Remote. Show all posts

Thursday, 8 November 2012

Spring MVC REST Calls With HTTP Only

This post describes how to perform REST calls to a Spring MVC application using HTTP only. This example is a variation of the Spring MVC REST Calls With Ajax example. The code is available on GitHub in the Spring-REST-With-HTML-Only directory.

Web.xml

We need to add the HiddenHttpMethodFilter to our web.xml. It searches HTML form PUTs for a _method parameter. If the corresponding value is GET, PUT, POST or DELETE, the call is transformed into a REST call before it is transmitted to the controllers:
...
<servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <servlet-name>MyServlet</servlet-name>
</filter-mapping>
...

Main Page

We replace the buttons by HTML post forms:
<%@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">
  <title>Welcome To REST With HTML Only !!!</title>
</head>
<body>
    <h1>Welcome To REST With HTML Only !!!</h1>
    <form action="<c:url value='/MyData/123466/'/>"
          method="post" >
        <input type="hidden" name="_method" value="GET">
        <input type="submit" value="GET">
    </form>
    <form action="<c:url value='/MyData'/>"
          method="post" >
        <input type="hidden" name="time" value="555555">
        <input type="hidden" name="message" value="User PUT call !!!">
        <input type="hidden" name="_method" value="PUT">
        <input type="submit" value="PUT">
    </form>
    <form action="<c:url value='/MyData'/>"
          method="post" >
        <input type="submit" value="POST">
    </form>
    <form action="<c:url value='/MyData/654321'/>"
          method="post" >
        <input type="hidden" name="_method" value="DELETE">
        <input type="submit" value="DELETE">
    </form>
</body>
</html>

Controller

We need to modify our controller for PUT calls:
@Controller
@RequestMapping(value = "/MyData")
public class MyRESTController {

    @RequestMapping(value="/{time}", method = RequestMethod.GET)
    public @ResponseBody MyData getMyData(
            @PathVariable long time) {

        return new MyData(time, "REST GET Call !!!");
    }

    @RequestMapping(method = RequestMethod.PUT)
    public @ResponseBody MyData putMyData(
            @RequestParam("time") long time,
            @RequestParam("message") String message) {

        return new MyData(time, message);
    }

    @RequestMapping(method = RequestMethod.POST)
    public @ResponseBody MyData postMyData() {
        return new MyData(
            System.currentTimeMillis(), "REST POST Call !!!");
    }

    @RequestMapping(value="/{time}", method = RequestMethod.DELETE)
    public @ResponseBody MyData deleteMyData(
            @PathVariable long time) {

        return new MyData(time, "REST DELETE Call !!!");
    }

}

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:

  http://localhost:8585/spring-rest-with-html-only

The main page will be displayed:

Spring MVC REST Calls With HTML Only


If you click on a button, the corresponding JSON will be displayed:

Spring MVC With HTML Only JSON
More Spring related posts here.

Spring MVC REST Calls From Java

Sometimes, web applications running on servers need to access REST resources located on other servers. From a REST perspective, the physical server act as a logical REST client. This example describes how to proceed. It is based on the Spring MVC REST Calls With Ajax example. The code is available on GitHub in the Spring-Server-Side-REST-Call directory.

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 + " !!!");
    }

}
It return a MyRemoteData object as a JSON:
public class MyRemoteData {

    private String data = "";

    public MyRemoteData() { }

    public MyRemoteData(String message) {
       this.data = message;
    }

    // Setter & Getters

}
We simplify our existing controller to a simple GET. It uses Spring's RestTemplate to make a REST Http GET call to fetch remote data from our 'remote' server:
@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>
Ditto for our javascript:
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:

Spring REST Calls From Java

If you click on get, a pop-up is displayed:


More Spring related posts here.