简体   繁体   中英

How can I send an object from a controller to a view Spring MVC

I'd like to send the result of the controller to the view The result is in json format What should I add to the controller so I can send the object to the view

  while (rs.next()) {
            Long issuenum = rs.getLong("issuenum");
            String assignee = rs.getString("assignee");
            String summary = rs.getString("summary");
            Date created = rs.getDate("created");
            Date resolutiondate = rs.getDate("resolutiondate");
            ResolvedTickets RS = new ResolvedTickets(rs.getLong("issuenum"), rs.getString("assignee"), rs.getString("summary"), rs.getDate("created"), rs.getDate("resolutiondate"));
            res.add(RS);
        }

        st.close();


        return res;
    }

ModelAndView is an object that holds both the model and view. The handler returns the ModelAndView object and DispatcherServlet resolves the view using View Resolvers and View.

The View is an object which contains view name in the form of the String and model is a map to add multiple objects.

In the below example 'employeeDetails' is the view name.

ModelAndView model = new ModelAndView("employeeDetails");
model.addObject("employeeObj", new EmployeeBean(123));
model.addObject("msg", "Employee information.");
return model;

There are many ways to access object in view :

1) ModelAndView Here you can directly add modelAndView.addObject("objectName", Object); You can acces it on page by following
${objectName}

Same For Model

2) If you want object in json format for that you have to convert object into json first by using ObjectMapper in spring-mvc and then you can catch that json string in view page as done method 1.

Example :

ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.toJson(yourObject);
mav.addObject("json",json);
And on view page you can acces it inside javascript :

<script>
var jsonString = ${json};
/* Here you can play with json now */
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM