Using Spring, I need to pass dynamic data to html to create a web page

I am creating a web page using spring, which is to build a table using an API call that returns a dynamic number of elements.

Here is what I have now:

@RequestMapping(value="/managecustomerconfigurations", method=RequestMethod.GET)
    public ModelAndView setUpPage(){
        ModelAndView model = new ModelAndView("customerconfigurations");
        model.addObject("cdata", custServe.listAllCustomers());
        return model;
    }

I can get cdata on my webpage if I type

<p th:text="'Customer:' + ${cdata}" />

but i cant see it if just type

${cdata}  

or if I put the data in any JavaScript (even if I use the onload method)

Quick sidenote: I'm using HTML 5, not JSP.

Ideallyr I would like to pass the API response in JavaScript and build a table based on this answer.

+4
source share
3 answers

Thymeleaf th: html. Html , .

Thymeleaf, . jsp, : , ${cdata} th:text.

( ), back-end javascript , ajax, html5. Html5 data- .

, div, , :

<div id="Some-Container" th:attr="data-someDescription=${cdataJson}"></div>

jQuery, html5 jQuery:

$("#Some-Container").data("someDescription");

jQuery, js-, , . js .

, json-, , javascript, mapper- :

<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />

:

@Autowired
private ObjectMapper jsonMapper;

, model, mapper json:

String cDataJson = jsonMapper.writeValueAsString(custServe.listAllCustomers());
model.addAttribute("cdataJson", cDataJson);
+2

JSP, HTML JavaScript, cdata . JSP, toString(), JSON. - JSP, AJAX. , , JSON.

AJAX:

@RequestMapping(value = "/customerdata", method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<List<Customer>> getCustomerData(){
    List<Customer> customers = custServe.listAllCustomers();
    return new ResponseEntity<>(customers, HttpStatus.OK);
}

JavaScript:

var cdata;
$.ajax({
   url: "/customerdata",
   dataType: "json",
   method: "get"
}).done(function(data){
    cdata = data;
    //do stuff
});
+1

jquery spring.

<select name="CustomerList" th:field="*{cdata}">

    <option th:each="task : ${cdata}" th:value="${task}"
        th:text="${task}"></option>

</select>

Spring

    @RequestMapping(value="/managecustomerconfigurations", method=RequestMethod.GET)
    public ModelAndView setUpPage(){
        ModelAndView model = new ModelAndView("customerconfigurations");
        try{
            JSONObject obj = new JSONObject(custServe.listAllCustomers());

            List<Integer> list = new ArrayList<Integer>();

            JSONArray array = obj.getJSONArray("returnObject");
            for(int i = 0 ; i < array.length() ; i++){
                int j = array.getJSONObject(i).getInt("id");
                list.add(j);
            }
            model.addObject("cdata", list);
        }
     return model;
    }
0

All Articles