2013-09-24 31 views
2

我試圖從DB中檢索用戶信息並使用Spring MVC在前端(JSP)中顯示。如何在Spring MVC中使用model.addAttributes添加對象

控制器裏面,我目前加入以下代碼,

     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()); 

在前端JSP,我展示他們使用$ {EMAIL} $ {name}的$ {}生日等。不過我想這樣做,

ModelMap model; model.addAttribute(「user」,user);

並在前端顯示爲$ {user.getName()}。但是這不起作用。你能否告訴我是否有其他方法可以做到這一點?

回答

6

在控制器如下

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

添加在JSP中使用這樣的

${user.name} 
+0

可變modelMap應該是模型在這裏。 – akshayb

+0

@akshayb謝謝..更新了答案 – Prabhakaran

+0

@Prabhakaran我們可以在模型屬性中插入空格或換行符... bcoz我的模型將整個字符串返回給jsp頁面...但我需要每個新聞都有空間b/w。 .... model.addAttribute( 「新聞」,新聞+ 「\ n」); – chopss

0

不要忘了如下的JSP選項isELIgnored="false"

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

這並沒有真正回答這個問題.... –

+1

@勞倫斯艾洛我同意。作者建議禁用表達式語言並不會以任何方式幫助OP向模型對象添加屬性,這些屬性可以通過引用對象的名稱和屬性從JSP中檢索。它似乎故意嘗試通過阻止它們能夠解析應用於其中的頁面中的EL來解決更多問題。請參閱docs.oracle.com/cd/E19316-01/819-3669/bnaic/index.html – ethesx

-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} 
相關問題