SpringMVCのControllerからThymeleaf内のJavaScriptへ値をJSON形式で渡す方法は、以下のように JacksonのObjectMapperなどを利用すれば可能です。
java
1 package com . github . apz . springsample . controller ;
2
3 import java . util . ArrayList ;
4 import java . util . List ;
5
6 import org . springframework . stereotype . Controller ;
7 import org . springframework . web . bind . annotation . GetMapping ;
8 import org . springframework . web . servlet . ModelAndView ;
9
10 import com . fasterxml . jackson . core . JsonProcessingException ;
11 import com . fasterxml . jackson . databind . ObjectMapper ;
12
13 @Controller
14 public class JSONSampleController {
15
16 public JSONSampleController ( ObjectMapper objectMapper ) {
17 this . objectMapper = objectMapper ;
18 }
19
20 final ObjectMapper objectMapper ;
21
22 @GetMapping ( "jsonSample" )
23 public ModelAndView display ( ModelAndView mnv ) throws JsonProcessingException {
24
25 mnv . addObject ( "itemList" , objectMapper . writeValueAsString ( itemList ( ) ) ) ;
26 mnv . setViewName ( "itemList" ) ;
27 return mnv ;
28 }
29
30 List < SampleItem > itemList ( ) {
31 List < SampleItem > items = new ArrayList < SampleItem > ( ) { {
32 add ( new SampleItem ( 1 , "Aphpa" ) ) ;
33 add ( new SampleItem ( 2 , "Beta" ) ) ;
34 add ( new SampleItem ( 3 , "Charly" ) ) ;
35 add ( new SampleItem ( 4 , "Delta" ) ) ;
36 } } ;
37
38 return items ;
39 }
40
41 class SampleItem {
42 public SampleItem ( int id , String name ) {
43 this . id = id ;
44 this . name = name ;
45 }
46 public int getId ( ) {
47 return id ;
48 }
49 public String getName ( ) {
50 return name ;
51 }
52 private int id ;
53 private String name ;
54 }
55 }
56
html
1 <! DOCTYPE html >
2 < html xmlns: th = " http://www.thymeleaf.org " >
3 < head >
4 < meta charset = " UTF-8 " >
5 </ head >
6 < body >
7 < script th: inline = " javascript " >
8 /* <![CDATA[ * /
9 var itemList = /*[[ ${itemList} ]]*/ ;
10 console . debug ( itemList ) ;
11 /* ]]> * /
12 </ script >
13 </ body >
14 </ html >
https://qiita.com/alpha_pz/items/d21f818b5792d3880731
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/10/14 06:59