1. 程式人生 > >springMVC(2)---處理模型資料ModelAndView

springMVC(2)---處理模型資料ModelAndView

    一. ModelAndView的用法:

使用ModelAndView類用來儲存處理完後的結果資料,以及顯示該資料的檢視。從名字上看ModelAndView中的Model代表模型,View代表檢視,這個名字就很好地解釋了該類的作用。業務處理器呼叫模型層處理完使用者請求後,把結果資料儲存在該類的model屬性中,把要返回的檢視資訊儲存在該類的view屬性中,然後讓該ModelAndView返回該Spring MVC框架。框架通過呼叫配置檔案中定義的檢視解析器,對該物件進行解析,最後把結果資料顯示在指定的頁面上。 

具體作用:

1、返回指定頁面

ModelAndView構造方法可以指定返回的頁面名稱,

也可以通過setViewName()方法跳轉到指定的頁面 ,

2、返回所需數值

使用addObject()設定需要返回的值,addObject()有幾個不同引數的方法,可以預設和指定返回物件的名字。

jsp示例:success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>success page</title>
</head>
<body>

    time: ${requestScope.time}

</body>
</html>

java示例: springmvcTestDriver.java

@Controller
@RequestMapping("/springmvc")
public class springmvcTestDriver(){
    
    private static final String SUCCESS = "success";    

    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView(){
    
    String viewName = SUCCESS;
    ModelAndView modelAndView = new ModelAndView(viewName);
    modelAndView.addObject("time", new Date());

    return modelAndView;
    }
}

二:處理模型資料之Map

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>index page</title>
</head>
<body>

<a href="/springmvc/testMap">Test Map</a>

</body>
</html>

success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>success page</title>
</head>
<body>

    names: ${requestScope.names}

</body>
</html>

SpringMvcTestDriver.java

@Controller
@RequestMapping("/springmvc")
public class SpringMvcTestDriver {

    private static final String SUCCESS = "success";

    @RequestMapping("/testMap")
    public String testMap(Map<String, Object> map) {
        map.put("names", Arrays.asList("Tom", "Jerry", "Mike"));

        return SUCCESS;
    }

}

二:處理模型資料之SessionAttributes

  • 若希望在多個請求之間共用某個模型屬性資料,則可以在控制器上標註一個@SessionAttributes,SpringMVC將在模型中對應的屬性暫存到HttpSession中
  • SessionAttributes除了可以通過屬性名指定需要放到會話中的屬性外,還可以通過模型屬性的物件型別指定哪些模型屬性需要放到會話中
  • @SessionAttributes(type=User.class)會將隱含模型中所有型別為User.class的屬性新增到會話中
    
  • @SessionAttributes(value={"user1", "user2"})
  • @SessionAttributes(types = {User.class, Dept.class})
    
  • @SessionAttributes(value = {"user1", "user2"}, types = {Dept.class})

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>index page</title>
</head>
<body>

<a href="/springmvc/testSessionAttributes">Test SessionAttributes</a>

</body>
</html>

success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>success page</title>
</head>
<body>

    request user: ${requestScope.user} <br/>

    session user: ${sessionScope.user} <br/>

    request school: ${requestScope.user} <br/>

    session school: ${sessionScope.user} <br/>

</body>
</html>

SpringMvcTestDriver.java

@Controller
@RequestMapping("/springmvc")
// 沒有@SessionAttributes註解,則只存在request域中;
// 添加了該註解後,request和session域中都有
// value和types的值代表哪些資料要被存放在HttpSession域中
@SessionAttributes(value = "user", types = {String.class})

public class SpringMvcTestDriver {

    private static final String SUCCESS = "success";

    @RequestMapping("testSessionAttributes")
    public String testSessionAttributes(Map<String, Object> map) {
        User user = new User("Tom", 25, "[email protected]");
        map.put("user", user);
        map.put("school", "atguigu");

        return SUCCESS;
    }
}

執行結果

request user: User{name='Tom', age=25, email='[email protected]', address=null} 
session user: User{name='Tom', age=25, email='[email protected]', address=null} 
request user: User{name='Tom', age=25, email='[email protected]', address=null} 
session user: User{name='Tom', age=25, email='[email protected]', address=null} 

二:處理模型資料之ModelAttribute

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>index page</title>
</head>
<body>

    <!--
        模擬修改操作:
        1.  原始資料為: 1,Tom,123456,12, tomatguigu.com
        2.  密碼不能被修改
        3.  表單回顯,模擬操作直接在表單填寫對應的屬性值
    -->
    <form action="/springmvc/testModelAttributes" method="post">
        <input type="hidden" name="id" value="1"/> <br/>
        username: <input type="text" name="username" value="Tom"> <br/>
        age: <input type="text" name="age" value="12"/> <br/>
        email: <input type="text" name="email" value="tomatguigu.com"/> <br/>
        <input type="submit" value="Submit"/>
    </form>

</body>
</html>

success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>success page</title>
</head>
<body>

    request user: ${requestScope.user} <br/>

    session user: ${sessionScope.user} <br/>

    request user: ${requestScope.user} <br/>

    session user: ${sessionScope.user} <br/>

</body>
</html>

SpringMvcTestDriver.java

/*
執行流程:
    1,  執行 @ModelAttribute 註解修飾的方法,從資料庫中取出物件,把物件放入map中
    2,  SpringMVC從map中取出User物件,並把表單傳來的資料賦值給User物件對應的屬性
    3.  SpringMVC把上述物件傳入目標方法的引數
    注意: 在@ModelAttribute修飾的方法中,放入到Map時的鍵需要和目標方法入參型別的第一個字母小寫的字串一致

 */
@Controller
@RequestMapping("/springmvc")
public class SpringMvcTestDriver {

    private static final String SUCCESS = "success";

    @ModelAttribute
    public void getUser(@RequestParam(value = "id", required = false) Integer id,
                        Map<String, Object> map) {
        if (id != null) {
            // 模擬從資料庫中獲取物件
            User user = new User(1, "Tom", "123456", 12, "tomatguigu.com");
            System.out.println("從資料庫中獲取一個物件:" + user);

            map.put("user", user);
        }
    }

    @RequestMapping("/testModelAttributes")
    public String testModelAttributes(User user) {
        System.out.println("修改:" + user);

        return SUCCESS;
    }

}

執行結果

從資料庫中獲取一個物件:User{id=1, userName='Tom', passWord=123456, age=12, email='tomatguigu.com'}
修改:User{id=1, userName='Tom', passWord=123456, age=13, email='tomatguigu.com'}

index.jsp

success.jsp

SpringMvcTestDriver.java