Java 如何在 Spring MVC 中使用 model.addAttributes 添加对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18975077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:00:49  来源:igfitidea点击:

How to add Object in using model.addAttributes in Spring MVC

javajspspring-mvc

提问by sinagarajan

I'm trying to retrieve the user information from DB and display in the front end (JSP) using Spring MVC.

我正在尝试从数据库中检索用户信息并使用 Spring MVC 显示在前端 (JSP) 中。

Inside the controller, currently I'm adding the following code,

在控制器内部,目前我正在添加以下代码,

                     ModelMap model;
        model.addAttribute("email", user.getEmailAddress());
        model.addAttribute("name", user.getuserName());
        model.addAttribute("birthday", user.getBirthday());
    model.addAttribute("street",user.getUserAddress().getStreet_address());
        model.addAttribute("state", user.getUserAddress().getState());
        model.addAttribute("city", user.getUserAddress().getCity());
        model.addAttribute("zip", user.getUserAddress().getZip());
        model.addAttribute("country", user.getUserAddress().getCountry());

In the front-end JSP, I display them using ${email} ,${name} ,${birthday} etc . However I would like to do something like this,

在前端 JSP 中,我使用 ${email} 、${name} 、${birthday} 等来显示它们。但是我想做这样的事情,

ModelMap model; model.addAttribute("user",user);

ModelMap 模型;model.addAttribute("user",user);

and in front end , display as ${user.getName()}. However this is not working . Can you let me know if there are any other ways to do this ?

在前端,显示为 ${user.getName()}。然而,这是行不通的。你能告诉我是否还有其他方法可以做到这一点吗?

采纳答案by Prabhakaran Ramaswamy

In controller add as below

在控制器中添加如下

    ModelMap model = new ModelMap();
    model.put("user", user);

In jsp use like this

在jsp中像这样使用

    ${user.name}

回答by Ernestas Kardzys

Or there is another option - to use @ModelAttribute like this: http://krams915.blogspot.com/2010/12/spring-3-mvc-using-modelattribute-in.html(contains Model and ModelAttribute examples).

或者还有另一种选择 - 像这样使用@ModelAttribute:http: //krams915.blogspot.com/2010/12/spring-3-mvc-using-modelattribute-in.html(包含模型和模型属性示例)。

回答by Jonathan PtheitroadIER

Don't forget the JSP option isELIgnored="false"as below:

不要忘记 JSP 选项isELIgnored="false"如下:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" isELIgnored="false"
pageEncoding="ISO-8859-1"%>

回答by vishal thakur

**In Controller do IT**    
@RequestMapping(value = "/loginStep.do", method = RequestMethod.GET)
        public String loginStep(ModelMap model,HttpServletRequest request, HttpServletResponse response,HttpSession session) {
    model.addAttribute("YearList", yearList);
    return "uploadPDFPage";
    }
**In uploadPDFPage JSP Do it**
${YearList}