[JAVA] Handle JSON in cross domain with Play Framework

There are various ways to create a WEB application with Play Framework on the net, but I don't think I often hear about passing JSON across domains, so I tried it. There was also a addictive point, so I will write it down when I have a memorandum.

environment

JSON generation

First, generate JSON on the server. It's simple to do, go to http: // localhost: 9000 / ajax and you'll be in your browser

[{"name":"mirai","changed":"miracle"},{"name":"riko","changed":"magical"},{"name":"kotoha","changed":"felice"}]

Will be displayed.

First, proceed to the point where "hello" can be output by the method of How to use Play Framework without using typesafe activator.

After "hello" is output, add the ajax method to Application.java.

app/controllers/Application.java


package controllers;

import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;

import java.util.*;
import java.util.ArrayList;

/**
 * Created by sunda on 17/05/28.
 */
public class Application extends Controller {

    public Result index() {
        return ok("hello");
    }

    public Result ajax() {
        List<Map<String, String>> list = new ArrayList<>();
        list.add(new HashMap<String, String>(){
            {put("name", "mirai");}
            {put("changed", "miracle");}
        });
        list.add(new HashMap<String, String>(){
            {put("name", "riko");}
            {put("changed", "magical");}
        });
        list.add(new HashMap<String, String>(){
            {put("name", "kotoha");}
            {put("changed", "felice");}
        });
        response().setHeader(Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, " *");
        return ok(Json.toJson(list));
    }

}

** The important part is ``` response (). SetHeader (Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN," * ");` ``. Without this, you cannot access from another domain. ** **

Next, set routes. Add the following to routes.

conf/routes


GET	/ajax	controllers.Application.ajax()

If you sbt run here and access http: // localhost: 9000 / ajax, the JSON from earlier should be output to the browser.

Receive JSON with Ajax

Next, I will write the client side. Receive the JSON from earlier with Javascript, format it appropriately and display it.

test.html


<!DOCTYPE html>
<html lang="ja">
  <head>
    <title>sample</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="./test.js"></script>
  </head>

  <body>
    <h1>JSON test</h1>
    <div>
      <dl id="precure">
      </dl>
    </div>
  </body>
</html>

It's annoying, so I use jQuery.

test.js


$(function() {
    
    $("#precure").each(function() {
	var $container = $(this);
    	$.getJSON("http://localhost:9000/ajax", function(data){
    	    var elements = [];
    	    $.each(data, function(i, item) {
		var name = '<dt>' + item.name + '</dt>';
		var changed = '<dd>' + item.changed + '</dd>';
    		elements.push($(name).get(0));
		elements.push($(changed).get(0));
    	    });
    	    $container.append(elements);	
    	});
    });
    
});

Now, when you open test.html in your browser, you will see a formatted page. maybe.

Recommended Posts

Handle JSON in cross domain with Play Framework
Handle JSON with minimal-json
Validation function in Play Framework
Double submit measures with Play Framework
Handle JSON effortlessly with Alamofire's respone Json
A story stuck with log output in Docker + Play framework environment
Authentication function in Play Framework [Access restrictions]
Play Framework 2.6 (Java) environment construction in Eclipse
Authentication function with Play Framework [Registration and authentication]
Working with huge JSON in Java Lambda
Diffed with JSON
I created an api domain with Spring Framework. Part 2
Handle passwords hashed with BCryptPasswordEncoder in Spring Security in Perl
I created an api domain with Spring Framework. Part 1