简体   繁体   中英

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.

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,

ModelMap model; 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 ?

In controller add as below

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

In jsp use like this

    ${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:

<%@ 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}

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