简体   繁体   English

如何在Spring MVC中使用model.addAttributes添加Object

[英]How to add Object in using model.addAttributes in Spring MVC

I'm trying to retrieve the user information from DB and display in the front end (JSP) using Spring MVC. 我正在尝试从DB检索用户信息并使用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 . 在前端JSP中,我使用$ {email},$ {name},$ {birthday}等显示它们。 However I would like to do something like this, 但是我想做这样的事情,

ModelMap model; ModelMap模型; model.addAttribute("user",user); model.addAttribute( “用户”,用户);

and in front end , display as ${user.getName()}. 在前端,显示为$ {user.getName()}。 However this is not working . 但这不起作用。 Can you let me know if there are any other ways to do this ? 如果有其他方法可以告诉我吗?

In controller add as below 在控制器中添加如下

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

In jsp use like this 在jsp中使用这样的

    ${user.name}

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

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"%>
**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}

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

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