Sometimes we need to send data from Controller to JSp. Here I'm going to explain how we can send and iterate Object List in JSP file. You can do this easily by following the below steps:
1- Define the below dependency in you pom.xml file for jackson mapper:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.11</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.11</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.11</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-xc</artifactId>
<version>1.9.11</version>
</dependency>
2- Define the model class of which list you want to iterate:
TickitModel.java
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
public class TicketModel
{
private int tickitId;
private String tickitName;
public int getTickitId()
{
return tickitId;
}
public void setTickitId(int tickitId)
{
this.tickitId = tickitId;
}
public String getTickitName()
{
return tickitName;
}
public void setTickitName(String tickitName)
{
this.tickitName = tickitName;
}
}
3- Write the below code to send object list to the JSP:
modelAndView = new ModelAndView("findMe"); //Here findMe is the JSP where we want ti display the list data
List<TicketModel> ticketModels = new ArrayList<TicketModel>();
TicketModel ticketModel1 = new TicketModel();
ticketModel1.setTickitId(1);
ticketModel1.setTickitName("New Tickit1");
ticketModels.add(ticketModel1);
ticketModel2 = new TicketModel();
ticketModel2.setTickitId(2);
ticketModel2.setTickitName("New Tickit2");
ticketModels.add(ticketModel2);
ObjectMapper mapper = new ObjectMapper();
String tickitModelList = "";
try {
tickitModelList = mapper.writeValueAsString(ticketModels);
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
modelAndView.addObject("ticketModels", tickitModelList);
4- Now write the below function in script tag to show the object list data:
var ticketModelsList = ${ticketModels};
$.each(ticketModelsList, function (indexa, all) {
var tickitId = all.tickitId;
alert(tickitId);
});
Hope this will help you :)
0 Comment(s)