简体   繁体   English

如何将对象从控制器发送到视图Spring MVC

[英]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 我想将控制器的结果发送到视图中,结果以json格式发送我应该添加到控制器中的什么以便可以将对象发送到视图中

  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. ModelAndView是同时包含模型和视图的对象。 The handler returns the ModelAndView object and DispatcherServlet resolves the view using View Resolvers and View. 处理程序返回ModelAndView对象,DispatcherServlet使用View解析器和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. View是一个包含String形式的视图名称的对象,而model是添加多个对象的映射。

In the below example 'employeeDetails' is the view name. 在下面的示例中,“ employeeDetails”是视图名称。

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); 1)ModelAndView在这里您可以直接添加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. 2)如果要使用json格式的对象,则必须先在spring-mvc中使用ObjectMapper将对象转换为json,然后可以按照方法1在视图页面中捕获该json字符串。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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