Usare AJAX con Java Spring
Oggi vediamo un semplice esempio di come usare AJAX insieme a Java Spring.
Il servizio che andremo a interrogare è OMDb, che abbiamo visto anche altre volte.
I dati verranno forniti in formato JSON e quindi useremo la libreria Gson per l'elaborazione dei dati.
Un esempio lo potete trovare qui; addesso lo applicheremo al web!
Prima di tutto scaricate la libreria Gson e incorporatela al progetto.
Poi creiamo la classe che farà da wrapper per il film di risposta:
public class Film {
public String Title;
public String Released;
public String Genre;
public String Director;
public String Writer;
public String Actors;
public String Plot;
public String Poster;
public String Runtime;
public String imdbID;
}
Ogni campo corrisponde a un valore di risposta che poi visualizzeremo nella pagina.
Bene, a questo punto passiamo al controller:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HomeController {
@RequestMapping(value = "/home")
public String home(Model model) {
return "home";
}
@RequestMapping(value = "/search")
public @ResponseBody
String searchResult(@RequestParam(value = "title") String title, @RequestParam(value = "id") String id, @RequestParam(value = "year") String year) throws MalformedURLException, IOException {
String search = "http://www.omdbapi.com/?";
if (id.isEmpty()) {
search += "i=&t=" + title;
} else {
search += "i=" + id + "&t=";
}
if (!year.isEmpty()) {
search += "&y=" + year;
}
String result;
try (BufferedReader bf = new BufferedReader(new InputStreamReader(new URL(search).openStream()))) {
Gson gson = new GsonBuilder().create();
Film film = gson.fromJson(bf, Film.class);
result = "{"title":"" + film.Title + "","actors":"" + film.Actors + "","released":"" + film.Released
+ "","genre":"" + film.Genre + "","director":"" + film.Director + "","writer":"" + film.Writer
+ "","plot":"" + film.Plot + "","poster":"" + film.Poster + "","runtime":"" + film.Runtime
+ "","imdbid":"" + film.imdbID + ""}";
}
return result;
}
}
Il primo metodo restituisce la pagina con il form che vedremo dopo; il secondo è quello che viene richiamato da jQuery (o anche da Javascript puro se volete, ma a me piace jQuery) alla pressione dei bottone:
function doAjaxPost() {
var title = $('#title').val();
var id = $('#id').val();
var year = $('#year').val();
$.ajax({
type: "Get",
url: "search.html",
data: "title=" + title + "&id=" + id + "&year=" + year,
success: function(res) {
var jsonRes = JSON.parse(res);
$('#title').val('');
$('#id').val('');
$('#year').val('');
$('#ajax-result').show();
$('#img_film').attr('src', jsonRes.poster);
$('#title_film').html(jsonRes.title);
$('#actors_film').html(jsonRes.actors);
$('#released_film').html(jsonRes.released);
$('#genre_film').html(jsonRes.genre);
$('#director_film').html(jsonRes.director);
$('#writer_film').html(jsonRes.writer);
$('#plot_film').html(jsonRes.plot);
$('#poster_film').html(jsonRes.poster);
$('#runtime_film').html(jsonRes.runtime);
$('#imdbid_film').html(jsonRes.imdbid);
}
});
}
Infine la pagina web (non fate caso a Kube, è un framework CSS che potete anche non usare):
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page session="false"%>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>IMDB</title>
<link type="text/css" rel="stylesheet" href="resources/kube402/css/kube.min.css">
<link type="text/css" rel="stylesheet" href="resources/style.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script src="resources/kube402/js/kube.min.js"></script>
<script src="resources/script.js"></script>
</head>
<body>
<div class="wrap">
<h1 class="text-centered">Search IMDB</h1>
<div class="units-row">
<div class="unit-50 centered" style="padding-top: 20px;">
<div class="units-row">
<div class="unit-100">
<label>
Title
<input type="text" id="title" name="title" class="width-100">
</label>
</div>
</div>
<div class="units-row">
<div class="unit-70">
<label>
Imdb Id
<input type="text" id="id" name="id" class="width-100">
</label>
</div>
<div class="unit-30">
<label>
Year
<input type="text" id="year" name="year" class="width-100">
</label>
</div>
</div>
<p>
<button class="btn btn-green" onclick="doAjaxPost();">Search</button>
</p>
</div>
</div>
<hr>
<div id="ajax-result" style="display: none;">
<div class="units-row">
<div class="unit-50">
<dl>
<dt>TITLE</dt>
<dd id="title_film"></dd>
<dt>ACTORS</dt>
<dd id="actors_film"></dd>
<dt>RELEASED</dt>
<dd id="released_film"></dd>
<dt>GENRE</dt>
<dd id="genre_film"></dd>
<dt>DIRECTOR</dt>
<dd id="director_film"></dd>
<dt>WRITER</dt>
<dd id="writer_film"></dd>
<dt>PLOT</dt>
<dd id="plot_film"></dd>
<dt>RUNTIME</dt>
<dd id="runtime_film"></dd>
<dt>IMDB ID</dt>
<dd id="imdbid_film"></dd>
</dl>
</div>
<div class="unit-50 text-right">
<img src="" id="img_film">
</div>
</div>
</div>
</div>
</body>
</html>
Come vedete c'è prima il form da riempire, con il bottone che alla pressione richiama la funzione JS che crea la chiamata AJAX attraverso il controller.
Enjoy!
java spring ajax javascript jquery json imdb omdb gson
Commentami!