1. 程式人生 > >Spring註解之@ModelAttribute理解

Spring註解之@ModelAttribute理解

在Spring MVC裡,@ModelAttribute通常使用在Controller方法的引數註解中,用於解釋model entity,但同時,也可以放在方法註解裡。

如果把@ModelAttribute放在方法的註解上時,代表的是:該Controller的所有方法在呼叫前,先執行此@ModelAttribute方法

舉些栗子:

public String test1(@ModelAttribute("user") UserModel user) 

只是此處多了一個註解@ModelAttribute("user"),它的作用是將該繫結的命令物件以“user”為名稱新增到模型物件中供檢視頁面展示使用。我們此時可以在檢視頁面使用${user.username}來獲取繫結的命令物件的屬性

如請求引數包含“?username=zhang&password=123&workInfo.city=bj”自動繫結到user 中的workInfo屬性的city屬性中。

/**
 * 設定這個註解之後可以直接在前端頁面使用hb這個物件(List)集合
 * @return
 */
@ModelAttribute("hb")
public List<String> hobbiesList(){
    List<String> hobbise = new LinkedList<String>();
    hobbise.add("basketball");
    hobbise.add("football");
    hobbise.add("tennis");
    return hobbise;
}

JSP頁面展示出來:

<br>
初始化的資料 : 	${hb }
<br>

	<c:forEach items="${hb}" var="hobby" varStatus="vs">
		<c:choose>
			<c:when test="${hobby == 'basketball'}">
			籃球<input type="checkbox" name="hobbies" value="basketball">
			</c:when>
			<c:when test="${hobby == 'football'}">
				足球<input type="checkbox" name="hobbies" value="football">
			</c:when>
			<c:when test="${hobby == 'tennis'}">
				網球<input type="checkbox" name="hobbies" value="tennis">
			</c:when>
		</c:choose>
	</c:forEach>

備註:

1、通過上面這種方式可以顯示出一個集合的內容

2、上面的jsp程式碼使用的是JSTL,需要匯入JSTL相關的jar包

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

public @ModelAttribute("user2") UserModel test3(@ModelAttribute("user2") UserModel user)
大家可以看到返回值型別是命令物件型別,而且通過@ModelAttribute("user2")註解,此時會暴露返回值到模型資料( 名字為user2 ) 中供檢視展示使用@ModelAttribute 註解的返回值會覆蓋@RequestMapping 註解方法中的@ModelAttribute 註解的同名命令物件

具體到應用中:

我們可以把這個@ModelAttribute特性,應用在BaseController當中,所有的Controller繼承BaseController,即可實現在呼叫Controller時,先執行@ModelAttribute方法。

比如許可權的驗證(也可以使用Interceptor)等

下面是一個設定request和response的方式(這個未測試,不知有沒線和安全問題)

package com.my.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.ModelAttribute;

public class BaseController {
    
    protected HttpServletRequest request;  
    protected HttpServletResponse response;  
    protected HttpSession session;
      
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response){  
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }
    
}

@ModelAttribute也可以做為Model輸出到View時使用,比如:

package com.my.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.my.controller.bean.Account;

@Controller
@RequestMapping(value="attr")
public class TestModelAttributeController {
    
    private static List<Account> accounts = new ArrayList<Account>();
    {
        accounts.add(new Account());
        accounts.add(new Account());
        
        Account ac1 = accounts.get(0);
        Account ac2 = accounts.get(1);
        
        ac1.setUserName("Robin");
        ac1.setPassword("123123");
        
        ac2.setUserName("Lucy");
        ac2.setPassword("123456");
    }

    @RequestMapping(method=RequestMethod.GET)
    public String index() {
        System.out.println("index");
        return "TestModelAttribute/index";
    }
    
    @ModelAttribute("accounts")
    public List<Account> getAccounts() {
        System.out.println("getAccounts");
        return accounts;
    }
    
}