Spring MVC中Controller如何將數據返回給頁面


要實現Controller返回數據給頁面,Spring MVC 提供了以下幾種途徑:

  • ModelAndView:將視圖和數據封裝成ModelAndView對象,作為方法的返回值,數據最終會存到HttpServletRequest對象中!
  • Model對象:通過給方法添加引用Model對象入參,直接往Model對象添加屬性值。那么哪些類型的入參才能夠引用Model對象,有三種類型,分別是  org.springframework.ui.Model、org.springframework.ui.ModelMap 或 java.uti.Map。只要是這些類型的入參,都是指向Model對象的,而且不管定義多少個這些類型的入參都是指向同一個Model對象!
  • @SessionAttributes:通過給Controller類添加@SessionAttributes注解,該注解的name和value屬性值都是Model的key值,意思是指Model中這些key對應的數據也會存到HttpSession,不僅僅存到HttpServletRequest對象中!這樣頁面可以共享HttpSession中存的數據了!
  • @ModelAttribute:使用@ModelAttribute注解的方法會在此Controller每個方法執行前被執行,指定@ModelAttribute的name或value都是一樣的功能,都是作為key,將注解的方法返回的對象作為value存放到Model中,不指定name和value的話,則以注解的方法返回的類型名稱首字母小寫作為key。

當然,除了上述的途徑,也可以使用傳統的方式,那就是直接使用HttpServletRequest或HttpSession對象來存數據,頁面上再去取。

注意:Model中存的數據,最終都會存放到HttpServletRequest對象中,頁面上可以通過HttpServletRequest對象獲取數據。

接下來,我們就看看demo,通過demo來理解如何通過這幾種方式實現將數據返回給頁面。

demo場景:通過ResetFul風格的URL路徑傳遞用戶ID給Controller,Controller查詢出對應的用戶信息返回給頁面。

Spring MVC配置的視圖解析器:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
    <property name="prefix" value="/jsp/" />  
    <property name="suffix" value=".jsp" />  
</bean>  

  ReturnModelDataController1.java:

package edu.mvcdemo.controller;  
  
import java.util.Map;  
  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.beans.factory.annotation.Qualifier;  
import org.springframework.context.annotation.Scope;  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.ui.ModelMap;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.servlet.ModelAndView;  
import edu.mvcdemo.model.User;  
import edu.mvcdemo.service.IUserService;  
  
/** 
 * @編寫人: yh.zeng 
 * @編寫時間:2017-7-10 下午9:16:54 
 * @文件描述: Controller中如何將model數據返回給頁面的demo1 
 */  
@Controller  
@Scope(value="singleton") //只實例化一個bean對象(即每次請求都使用同一個bean對象),默認是singleton  
@RequestMapping("users")  
public class ReturnModelDataController1 {  
      
    @Autowired  
    @Qualifier("userService")  
    private IUserService userService;  
  
      
    /** 
     * 方式一,通過ModelAndView返回用戶信息數據到頁面 
     * @return 
     */  
    @RequestMapping(value="/view/{userId}/use/ModelAndView", method=RequestMethod.GET)  
    private ModelAndView getUserInfo(@PathVariable("userId") Integer userId){  
        User user = userService.getUserById(userId);  
        return new ModelAndView("userinfo", "user", user);  
    }  
      
    /** 
     * 方式二,通過Model返回用戶信息數據到頁面 
     * @return 
     */  
    @RequestMapping(value="/view/{userId}/use/Model", method=RequestMethod.GET)  
    private String getUserInfo(@PathVariable("userId") Integer userId, Model model){  
        User user = userService.getUserById(userId);  
        model.addAttribute("user", user);  
        return "userinfo";  
    }  
      
      
    /** 
     * 方式三,通過ModelMap返回用戶信息數據到頁面 
     * @return 
     */  
    @RequestMapping(value="/view/{userId}/use/ModelMap", method=RequestMethod.GET)  
    private String getUserInfo(@PathVariable("userId") Integer userId, ModelMap model){  
        User user = userService.getUserById(userId);  
        model.addAttribute("user", user);  
        return "userinfo";  
    }  
      
    /** 
     * 方式四,通過Map返回用戶信息數據到頁面 
     * @return 
     */  
    @RequestMapping(value="/view/{userId}/use/Map", method=RequestMethod.GET)  
    private String getUserInfo(@PathVariable("userId") Integer userId, Map<String,Object> model){  
        User user = userService.getUserById(userId);  
        model.put("user", user);  
        return "userinfo";  
    }  
  
}  

RetunnModelDataController2.java:

[java]  view plain  copy
package edu.mvcdemo.controller;  
  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.beans.factory.annotation.Qualifier;  
import org.springframework.context.annotation.Scope;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.SessionAttributes;  
import org.springframework.web.servlet.ModelAndView;  
import edu.mvcdemo.model.User;  
import edu.mvcdemo.service.IUserService;  
  
/** 
 * @編寫人: yh.zeng 
 * @編寫時間:2017-7-11 下午9:09:03 
 * @文件描述: Controller中如何將model數據返回給頁面的demo2 
 */  
@Controller  
@Scope(value="singleton") //只實例化一個bean對象(即每次請求都使用同一個bean對象),默認是singleton  
@RequestMapping("users")  
@SessionAttributes({"user"}) //Model中key=user的數據也會存到HttpSession  
public class RetunnModelDataController2 {  
      
    @Autowired  
    @Qualifier("userService")  
    private IUserService userService;  
      
    /** 
     * 方式五,通過@SessionAttributes將指定key的模型數據存到HttpSession,讓頁面可以獲取 
     * @return 
     */  
    @RequestMapping(value="/view/{userId}/use/SessionAttributes", method=RequestMethod.GET)  
    private ModelAndView getUserInfo(@PathVariable("userId") Integer userId){  
        User user = userService.getUserById(userId);  
        return new ModelAndView("userinfo", "user", user);  
    }  
  
}  

RetunnModelDataController3.java:

package edu.mvcdemo.controller;  
  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.beans.factory.annotation.Qualifier;  
import org.springframework.context.annotation.Scope;  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.ModelAttribute;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import edu.mvcdemo.model.User;  
import edu.mvcdemo.service.IUserService;  
  
/** 
 * @編寫人: yh.zeng 
 * @編寫時間:2017-7-11 下午9:09:03 
 * @文件描述: Controller中如何將model數據返回給頁面的demo3 
 */  
@Controller  
@Scope(value="singleton") //只實例化一個bean對象(即每次請求都使用同一個bean對象),默認是singleton  
@RequestMapping("users")  
public class RetunnModelDataController3 {  
      
    @Autowired  
    @Qualifier("userService")  
    private IUserService userService;  
      
    /** 
     * 注解@ModelAttribute用法一: 
     * 使用@ModelAttribute注解的方法會在此Controller每個方法執行前被執行, 
     * 指定@ModelAttribute的name或value都是一樣的功能,都是作為key,將注解的方法返回的對象作為value存放到Model中, 
     * 不指定name和value的話,則以注解的方法返回的類型名稱首字母小寫作為key。 
     * @param userId  ResetFul路徑的請求參數 
     * @return 
     */  
    @ModelAttribute(name="user")   
    public User addAccount(@PathVariable("userId") Integer userId) {    
       return userService.getUserById(userId);    
    }    
  
    /** 
     * 注解@ModelAttribute用法二: 
     * 使用@ModelAttribute注解的方法會在此Controller每個方法執行前被執行 
     * @param userId    ResetFul路徑的請求參數 
     * @param model     模型對象,可以使用org.springframework.ui.Model、org.springframework.ui.ModelMap  
     *                       或 java.uti.Map 作為入參類型,以引用模型對象 
     */  
  /*@ModelAttribute 
    public void addAccount(@PathVariable("userId") Integer userId, Model model) {   
       User user =  userService.getUserById(userId);  
       model.addAttribute("user", user); 
    }*/  
      
    /** 
     * 方式六,通過@SessionAttributes將指定key的模型數據存到HttpSession,讓頁面可以獲取 
     * @return 
     */  
    @RequestMapping(value="/view/{userId}/use/ModelAttribute", method=RequestMethod.GET)  
    private String getUserInfo(@PathVariable("userId") Integer userId){  
        return "userinfo";  
    }  
  
}  

RetunnModelDataController4.java:

package edu.mvcdemo.controller;  
  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpSession;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.beans.factory.annotation.Qualifier;  
import org.springframework.context.annotation.Scope;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import edu.mvcdemo.model.User;  
import edu.mvcdemo.service.IUserService;  
  
/** 
 * @編寫人: yh.zeng 
 * @編寫時間:2017-7-11 下午9:09:03 
 * @文件描述: Controller中如何將model數據返回給頁面的demo2 
 */  
@Controller  
@Scope(value="singleton") //只實例化一個bean對象(即每次請求都使用同一個bean對象),默認是singleton  
@RequestMapping("users")  
public class RetunnModelDataController4 {  
      
    @Autowired  
    @Qualifier("userService")  
    private IUserService userService;  
      
    /** 
     * 方式七,直接將數據存到HttpSession,讓頁面可以獲取 
     * @param userId 
     * @param session 
     * @return 
     */  
    @RequestMapping(value="/view/{userId}/use/HttpSession", method=RequestMethod.GET)  
    private String getUserInfo(@PathVariable("userId") Integer userId, HttpSession session){  
        User user = userService.getUserById(userId);  
        session.setAttribute("user", user);  
        return "userinfo";  
    }  
      
    /** 
     * 方式八,直接將數據存到HttpServletRequest,讓頁面可以獲取 
     * @param userId 
     * @param session 
     * @return 
     */  
    @RequestMapping(value="/view/{userId}/use/HttpServletRequest", method=RequestMethod.GET)  
    private String getUserInfo(@PathVariable("userId") Integer userId, HttpServletRequest request){  
        User user = userService.getUserById(userId);  
        request.setAttribute("user", user);  
        return "userinfo";  
    }  
  
}  

用戶信息頁面userinfo.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>userinfo.jsp</title>  
</head>  
<body>  
        <c:if test="${sessionScope.user != null}">  
            <h3>HttpSession對象中也存了用戶信息!用戶信息如下:</h3>   
                        用戶編號:${sessionScope.user.no}  
            <br>  
                        用戶名:${sessionScope.user.userName}  
            <br>  
                        年齡:${sessionScope.user.age}  
        </c:if>  
        <c:if test="${requestScope.user != null}">  
            <h3>HttpServletRequest對象中存的用戶信息如下:</h3>   
                        用戶編號:${requestScope.user.no}  
            <br>  
                        用戶名:${requestScope.user.userName}  
            <br>  
                        年齡:${requestScope.user.age}  
        </c:if>  
</body>  
</html>  

效果:

方式一:通過org.springframework.web.servlet.ModelAndView實現

方式二:通過org.springframework.ui.Model實現

方式三:通過org.springframework.ui.ModelMap實現

方式四:通過java.util.Map實現

方式五:通過org.springframework.web.bind.annotation.SessionAttributes標注指定Model中的某些數據也存儲到HttpSession中

方式六:通過org.springframework.web.bind.annotation.ModelAttribute實現

方式七:直接將數據存到HttpSession,讓頁面可以獲取

方式八:直接將數據存到HttpServletRequest,讓頁面可以獲取

項目demo見https://github.com/zengyh/MavenSpringMvcDemo.git

 

要實現Controller返回數據給頁面,Spring MVC 提供了以下幾種途徑:

  • ModelAndView:將視圖和數據封裝成ModelAndView對象,作為方法的返回值,數據最終會存到HttpServletRequest對象中!
  • Model對象:通過給方法添加引用Model對象入參,直接往Model對象添加屬性值。那么哪些類型的入參才能夠引用Model對象,有三種類型,分別是  org.springframework.ui.Model、org.springframework.ui.ModelMap 或 java.uti.Map。只要是這些類型的入參,都是指向Model對象的,而且不管定義多少個這些類型的入參都是指向同一個Model對象!
  • @SessionAttributes:通過給Controller類添加@SessionAttributes注解,該注解的name和value屬性值都是Model的key值,意思是指Model中這些key對應的數據也會存到HttpSession,不僅僅存到HttpServletRequest對象中!這樣頁面可以共享HttpSession中存的數據了!
  • @ModelAttribute:使用@ModelAttribute注解的方法會在此Controller每個方法執行前被執行,指定@ModelAttribute的name或value都是一樣的功能,都是作為key,將注解的方法返回的對象作為value存放到Model中,不指定name和value的話,則以注解的方法返回的類型名稱首字母小寫作為key。

當然,除了上述的途徑,也可以使用傳統的方式,那就是直接使用HttpServletRequest或HttpSession對象來存數據,頁面上再去取。

注意:Model中存的數據,最終都會存放到HttpServletRequest對象中,頁面上可以通過HttpServletRequest對象獲取數據。

接下來,我們就看看demo,通過demo來理解如何通過這幾種方式實現將數據返回給頁面。

demo場景:通過ResetFul風格的URL路徑傳遞用戶ID給Controller,Controller查詢出對應的用戶信息返回給頁面。

Spring MVC配置的視圖解析器:

[html]  view plain  copy
 
  1. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  2.     <property name="prefix" value="/jsp/" />  
  3.     <property name="suffix" value=".jsp" />  
  4. </bean>  

ReturnModelDataController1.java:

[java]  view plain  copy
 
  1. package edu.mvcdemo.controller;  
  2.   
  3. import java.util.Map;  
  4.   
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.beans.factory.annotation.Qualifier;  
  7. import org.springframework.context.annotation.Scope;  
  8. import org.springframework.stereotype.Controller;  
  9. import org.springframework.ui.Model;  
  10. import org.springframework.ui.ModelMap;  
  11. import org.springframework.web.bind.annotation.PathVariable;  
  12. import org.springframework.web.bind.annotation.RequestMapping;  
  13. import org.springframework.web.bind.annotation.RequestMethod;  
  14. import org.springframework.web.servlet.ModelAndView;  
  15. import edu.mvcdemo.model.User;  
  16. import edu.mvcdemo.service.IUserService;  
  17.   
  18. /** 
  19.  * @編寫人: yh.zeng 
  20.  * @編寫時間:2017-7-10 下午9:16:54 
  21.  * @文件描述: Controller中如何將model數據返回給頁面的demo1 
  22.  */  
  23. @Controller  
  24. @Scope(value="singleton"//只實例化一個bean對象(即每次請求都使用同一個bean對象),默認是singleton  
  25. @RequestMapping("users")  
  26. public class ReturnModelDataController1 {  
  27.       
  28.     @Autowired  
  29.     @Qualifier("userService")  
  30.     private IUserService userService;  
  31.   
  32.       
  33.     /** 
  34.      * 方式一,通過ModelAndView返回用戶信息數據到頁面 
  35.      * @return 
  36.      */  
  37.     @RequestMapping(value="/view/{userId}/use/ModelAndView", method=RequestMethod.GET)  
  38.     private ModelAndView getUserInfo(@PathVariable("userId") Integer userId){  
  39.         User user = userService.getUserById(userId);  
  40.         return new ModelAndView("userinfo""user", user);  
  41.     }  
  42.       
  43.     /** 
  44.      * 方式二,通過Model返回用戶信息數據到頁面 
  45.      * @return 
  46.      */  
  47.     @RequestMapping(value="/view/{userId}/use/Model", method=RequestMethod.GET)  
  48.     private String getUserInfo(@PathVariable("userId") Integer userId, Model model){  
  49.         User user = userService.getUserById(userId);  
  50.         model.addAttribute("user", user);  
  51.         return "userinfo";  
  52.     }  
  53.       
  54.       
  55.     /** 
  56.      * 方式三,通過ModelMap返回用戶信息數據到頁面 
  57.      * @return 
  58.      */  
  59.     @RequestMapping(value="/view/{userId}/use/ModelMap", method=RequestMethod.GET)  
  60.     private String getUserInfo(@PathVariable("userId") Integer userId, ModelMap model){  
  61.         User user = userService.getUserById(userId);  
  62.         model.addAttribute("user", user);  
  63.         return "userinfo";  
  64.     }  
  65.       
  66.     /** 
  67.      * 方式四,通過Map返回用戶信息數據到頁面 
  68.      * @return 
  69.      */  
  70.     @RequestMapping(value="/view/{userId}/use/Map", method=RequestMethod.GET)  
  71.     private String getUserInfo(@PathVariable("userId") Integer userId, Map<String,Object> model){  
  72.         User user = userService.getUserById(userId);  
  73.         model.put("user", user);  
  74.         return "userinfo";  
  75.     }  
  76.   
  77. }  

RetunnModelDataController2.java:

[java]  view plain  copy
 
  1. package edu.mvcdemo.controller;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.beans.factory.annotation.Qualifier;  
  5. import org.springframework.context.annotation.Scope;  
  6. import org.springframework.stereotype.Controller;  
  7. import org.springframework.web.bind.annotation.PathVariable;  
  8. import org.springframework.web.bind.annotation.RequestMapping;  
  9. import org.springframework.web.bind.annotation.RequestMethod;  
  10. import org.springframework.web.bind.annotation.SessionAttributes;  
  11. import org.springframework.web.servlet.ModelAndView;  
  12. import edu.mvcdemo.model.User;  
  13. import edu.mvcdemo.service.IUserService;  
  14.   
  15. /** 
  16.  * @編寫人: yh.zeng 
  17.  * @編寫時間:2017-7-11 下午9:09:03 
  18.  * @文件描述: Controller中如何將model數據返回給頁面的demo2 
  19.  */  
  20. @Controller  
  21. @Scope(value="singleton"//只實例化一個bean對象(即每次請求都使用同一個bean對象),默認是singleton  
  22. @RequestMapping("users")  
  23. @SessionAttributes({"user"}) //Model中key=user的數據也會存到HttpSession  
  24. public class RetunnModelDataController2 {  
  25.       
  26.     @Autowired  
  27.     @Qualifier("userService")  
  28.     private IUserService userService;  
  29.       
  30.     /** 
  31.      * 方式五,通過@SessionAttributes將指定key的模型數據存到HttpSession,讓頁面可以獲取 
  32.      * @return 
  33.      */  
  34.     @RequestMapping(value="/view/{userId}/use/SessionAttributes", method=RequestMethod.GET)  
  35.     private ModelAndView getUserInfo(@PathVariable("userId") Integer userId){  
  36.         User user = userService.getUserById(userId);  
  37.         return new ModelAndView("userinfo""user", user);  
  38.     }  
  39.   
  40. }  

RetunnModelDataController3.java:

[java]  view plain  copy
 
  1. package edu.mvcdemo.controller;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.beans.factory.annotation.Qualifier;  
  5. import org.springframework.context.annotation.Scope;  
  6. import org.springframework.stereotype.Controller;  
  7. import org.springframework.ui.Model;  
  8. import org.springframework.web.bind.annotation.ModelAttribute;  
  9. import org.springframework.web.bind.annotation.PathVariable;  
  10. import org.springframework.web.bind.annotation.RequestMapping;  
  11. import org.springframework.web.bind.annotation.RequestMethod;  
  12. import edu.mvcdemo.model.User;  
  13. import edu.mvcdemo.service.IUserService;  
  14.   
  15. /** 
  16.  * @編寫人: yh.zeng 
  17.  * @編寫時間:2017-7-11 下午9:09:03 
  18.  * @文件描述: Controller中如何將model數據返回給頁面的demo3 
  19.  */  
  20. @Controller  
  21. @Scope(value="singleton"//只實例化一個bean對象(即每次請求都使用同一個bean對象),默認是singleton  
  22. @RequestMapping("users")  
  23. public class RetunnModelDataController3 {  
  24.       
  25.     @Autowired  
  26.     @Qualifier("userService")  
  27.     private IUserService userService;  
  28.       
  29.     /** 
  30.      * 注解@ModelAttribute用法一: 
  31.      * 使用@ModelAttribute注解的方法會在此Controller每個方法執行前被執行, 
  32.      * 指定@ModelAttribute的name或value都是一樣的功能,都是作為key,將注解的方法返回的對象作為value存放到Model中, 
  33.      * 不指定name和value的話,則以注解的方法返回的類型名稱首字母小寫作為key。 
  34.      * @param userId  ResetFul路徑的請求參數 
  35.      * @return 
  36.      */  
  37.     @ModelAttribute(name="user")   
  38.     public User addAccount(@PathVariable("userId") Integer userId) {    
  39.        return userService.getUserById(userId);    
  40.     }    
  41.   
  42.     /** 
  43.      * 注解@ModelAttribute用法二: 
  44.      * 使用@ModelAttribute注解的方法會在此Controller每個方法執行前被執行 
  45.      * @param userId    ResetFul路徑的請求參數 
  46.      * @param model     模型對象,可以使用org.springframework.ui.Model、org.springframework.ui.ModelMap  
  47.      *                       或 java.uti.Map 作為入參類型,以引用模型對象 
  48.      */  
  49.   /*@ModelAttribute 
  50.     public void addAccount(@PathVariable("userId") Integer userId, Model model) {   
  51.        User user =  userService.getUserById(userId);  
  52.        model.addAttribute("user", user); 
  53.     }*/  
  54.       
  55.     /** 
  56.      * 方式六,通過@SessionAttributes將指定key的模型數據存到HttpSession,讓頁面可以獲取 
  57.      * @return 
  58.      */  
  59.     @RequestMapping(value="/view/{userId}/use/ModelAttribute", method=RequestMethod.GET)  
  60.     private String getUserInfo(@PathVariable("userId") Integer userId){  
  61.         return "userinfo";  
  62.     }  
  63.   
  64. }  

RetunnModelDataController4.java:

[java]  view plain  copy
 
  1. package edu.mvcdemo.controller;  
  2.   
  3. import javax.servlet.http.HttpServletRequest;  
  4. import javax.servlet.http.HttpSession;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6. import org.springframework.beans.factory.annotation.Qualifier;  
  7. import org.springframework.context.annotation.Scope;  
  8. import org.springframework.stereotype.Controller;  
  9. import org.springframework.web.bind.annotation.PathVariable;  
  10. import org.springframework.web.bind.annotation.RequestMapping;  
  11. import org.springframework.web.bind.annotation.RequestMethod;  
  12. import edu.mvcdemo.model.User;  
  13. import edu.mvcdemo.service.IUserService;  
  14.   
  15. /** 
  16.  * @編寫人: yh.zeng 
  17.  * @編寫時間:2017-7-11 下午9:09:03 
  18.  * @文件描述: Controller中如何將model數據返回給頁面的demo2 
  19.  */  
  20. @Controller  
  21. @Scope(value="singleton"//只實例化一個bean對象(即每次請求都使用同一個bean對象),默認是singleton  
  22. @RequestMapping("users")  
  23. public class RetunnModelDataController4 {  
  24.       
  25.     @Autowired  
  26.     @Qualifier("userService")  
  27.     private IUserService userService;  
  28.       
  29.     /** 
  30.      * 方式七,直接將數據存到HttpSession,讓頁面可以獲取 
  31.      * @param userId 
  32.      * @param session 
  33.      * @return 
  34.      */  
  35.     @RequestMapping(value="/view/{userId}/use/HttpSession", method=RequestMethod.GET)  
  36.     private String getUserInfo(@PathVariable("userId") Integer userId, HttpSession session){  
  37.         User user = userService.getUserById(userId);  
  38.         session.setAttribute("user", user);  
  39.         return "userinfo";  
  40.     }  
  41.       
  42.     /** 
  43.      * 方式八,直接將數據存到HttpServletRequest,讓頁面可以獲取 
  44.      * @param userId 
  45.      * @param session 
  46.      * @return 
  47.      */  
  48.     @RequestMapping(value="/view/{userId}/use/HttpServletRequest", method=RequestMethod.GET)  
  49.     private String getUserInfo(@PathVariable("userId") Integer userId, HttpServletRequest request){  
  50.         User user = userService.getUserById(userId);  
  51.         request.setAttribute("user", user);  
  52.         return "userinfo";  
  53.     }  
  54.   
  55. }  

用戶信息頁面userinfo.jsp:

[html]  view plain  copy
 
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  5. <html>  
  6. <head>  
  7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  8. <title>userinfo.jsp</title>  
  9. </head>  
  10. <body>  
  11.         <c:if test="${sessionScope.user != null}">  
  12.             <h3>HttpSession對象中也存了用戶信息!用戶信息如下:</h3>   
  13.                         用戶編號:${sessionScope.user.no}  
  14.             <br>  
  15.                         用戶名:${sessionScope.user.userName}  
  16.             <br>  
  17.                         年齡:${sessionScope.user.age}  
  18.         </c:if>  
  19.         <c:if test="${requestScope.user != null}">  
  20.             <h3>HttpServletRequest對象中存的用戶信息如下:</h3>   
  21.                         用戶編號:${requestScope.user.no}  
  22.             <br>  
  23.                         用戶名:${requestScope.user.userName}  
  24.             <br>  
  25.                         年齡:${requestScope.user.age}  
  26.         </c:if>  
  27. </body>  
  28. </html>  

效果:

方式一:通過org.springframework.web.servlet.ModelAndView實現

方式二:通過org.springframework.ui.Model實現

方式三:通過org.springframework.ui.ModelMap實現

方式四:通過java.util.Map實現

方式五:通過org.springframework.web.bind.annotation.SessionAttributes標注指定Model中的某些數據也存儲到HttpSession中

方式六:通過org.springframework.web.bind.annotation.ModelAttribute實現

方式七:直接將數據存到HttpSession,讓頁面可以獲取

方式八:直接將數據存到HttpServletRequest,讓頁面可以獲取

項目demo見https://github.com/zengyh/MavenSpringMvcDemo.git


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM