问题
Im new to ftl(FreeMarker template). I send a List of object from my controller using model map like this
My controller code
@RequestMapping(value="/xxx")
public String myMethod(ModelMap model){
List<MyDTO> dto = mymethods(); // I return some list objects in this method
model.addAttribute("dto",dto);
model.addAttribute("dtoLength",dto.size());
return "myview";
}
MyDTO.java
public class myDTO{
Public String var1;
Public String var2;
public String getVar1() {
return var1;
}
public void setVar1(String var1) {
this.var1 = var1;
}
public String getVar2() {
return var2;
}
public void setVar2(String var2) {
this.var2 = var2;
}
}
Now i try to access dto from my ftl's javascript.I tried it many ways like this:
var dto=${dto};
it said whatever must be inside ${....} should be either string,integer,boolean ..blah blah
So i thought of iterating it like this to get what i want
var valueIWanted;
if(${dtoLength}>0){
for(var i=0 ; i < ${dtoLength} ; i++){
ticketList[i] = ${ticket[i].var2};
}
}
but i was not able to access it this way too.what am i supposed to do in here ?I think i m missing the syntax.Can anyone help me out with this?
回答1:
You can easily access modelMap data as :
<#list dto as dtoList>
<tr>
<td>${dtoList.var1}</td> <td>${dtoList.var1}</td>
</tr>
</#list>
You don't need to send the length of DTO
, if you are using it for other purpose then you can use it.
and you can simply iterate list, you don't need for
loop.
Look this.
If you want to access the data using the JavaScript then you can use ajax request on page load on controller and it sends you a response with data and then process that data and print on FTL page. If possible then use some JavaScript framework so to handle such a request become easy and convenient.
Still you can do : var dtoList= "${dto}";
. not without quote.
See SO Answer.
For to check empty or not :
[#if dto??]
//inside it write all your code
[/#if]
You can check it here.
With example.
回答2:
You might want to try
var dto="${dto}";
instead of
var dto=${dto};
来源:https://stackoverflow.com/questions/24219222/cannot-access-list-of-object-sent-from-modelmap-in-ftl-file