spring mvc @ModelAttribute使用

@ModelAttribute 绑定请求参数到命令对象

 

@ModelAttribute一个具有如下三个作用:

①绑定请求参数到命令对象:放在功能处理方法的入参上时,用于将多个请求参数绑定到一个命令对象,从而简化绑

定流程,而且自动暴露为模型数据用于视图页面展示时使用;

②暴露表单引用对象为模型数据:放在处理器的一般方法(非功能处理方法)上时,是为表单准备要展示的表单引用

对象,如注册时需要选择的所在城市等,而且在执行功能处理方法(@RequestMapping 注解的方法)之前,自动添加

到模型对象中,用于视图页面展示时使用;

③暴露@RequestMapping 方法返回值为模型数据:放在功能处理方法的返回值上时,是暴露功能处理方法的返回值为

模型数据,用于视图页面展示时使用。

 

一、绑定请求参数到指定对象     

 

Java代码   收藏代码
  1. public String test1(@ModelAttribute("user") UserModel user)  
 只是此处多了一个注解@ModelAttribute("user"),它的作用是将该绑定的命令对象以“user”为名称添加到模型对象中供视图页面展示使用。我们此时可以在视图页面使用${user.username}来获取绑定的命令对象的属性。

 

 

如请求参数包含“?username=zhang&password=123&workInfo.city=bj”自动绑定到user 中的workInfo属性的city属性中。

 

 

Java代码   收藏代码
  1. @RequestMapping(value="/model2/{username}")  
  2. public String test2(@ModelAttribute("model") DataBinderTestModel model)  
URI 模板变量也能自动绑定到命令对象中 , 当你请求的URL 中包含“bool=yes&schooInfo.specialty=computer&hobbyList[0]=program&hobbyList[1]=music&map[key1]=value1&map[key2]=value2&state=blocked”会自动绑定到命令对象上。当URI模板变量和请求参数同名时, URI模板变量具有高优先权 。 

 

 

二、暴露表单引用对象为模型数据 

Java代码   收藏代码
  1. /** 
  2.  * 设置这个注解之后可以直接在前端页面使用hb这个对象(List)集合 
  3.  * @return 
  4.  */  
  5. @ModelAttribute("hb")  
  6. public List<String> hobbiesList(){  
  7.     List<String> hobbise = new LinkedList<String>();  
  8.     hobbise.add("basketball");  
  9.     hobbise.add("football");  
  10.     hobbise.add("tennis");  
  11.     return hobbise;  
  12. }  

 

JSP页面展示出来

Java代码   收藏代码
  1. <br>  
  2. 初始化的数据 :    ${hb }  
  3. <br>  
  4.   
  5.     <c:forEach items="${hb}" var="hobby" varStatus="vs">  
  6.         <c:choose>  
  7.             <c:when test="${hobby == 'basketball'}">  
  8.             篮球<input type="checkbox" name="hobbies" value="basketball">  
  9.             </c:when>  
  10.             <c:when test="${hobby == 'football'}">  
  11.                 足球<input type="checkbox" name="hobbies" value="football">  
  12.             </c:when>  
  13.             <c:when test="${hobby == 'tennis'}">  
  14.                 网球<input type="checkbox" name="hobbies" value="tennis">  
  15.             </c:when>  
  16.         </c:choose>  
  17.     </c:forEach>  

 备注:

1、通过上面这种方式可以显示出一个集合的内容

2、上面的jsp代码使用的是JSTL,需要导入JSTL相关的jar包

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

 

三、暴露@RequestMapping方法返回值为模型数据 

Java代码   收藏代码
  1. public @ModelAttribute("user2") UserModel test3(@ModelAttribute("user2") UserModel user)  

 

大家可以看到返回值类型是命令对象类型,而且通过@ModelAttribute("user2")注解,此时会暴露返回值到模型数据( 名字为user2 ) 中供视图展示使用

 

@ModelAttribute 注解的返回值会覆盖@RequestMapping 注解方法中的@ModelAttribute 注解的同名命令对象



在Spring MVC里,@ModelAttribute通常使用在Controller方法的参数注解中,用于解释model entity,但同时,也可以放在方法注解里。

如果把@ModelAttribute放在方法的注解上时,代表的是:该Controller的所有方法在调用前,先执行此@ModelAttribute方法

 

比如我们有一个Controller:TestController

复制代码
@Controller
@RequestMapping(value="test")
public class PassportController {

    @ModelAttribute
    public void preRun() {
        System.out.println("Test Pre-Run");
    }
    
    @RequestMapping(method=RequestMethod.GET)
    public String index() {
        return "login/index";
    }
    
    @RequestMapping(value="login", method=RequestMethod.POST)
    public ModelAndView login(@ModelAttribute @Valid Account account, BindingResult result)
        :
        :
    }
    
    @RequestMapping(value="logout", method=RequestMethod.GET)
    public String logout() {
        :
        :
    }
    
}
复制代码

在调用所有方法之前,都会先执行preRun()方法。

 

我们可以把这个@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;
    }
    
}
复制代码
复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib prefix="st" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!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>TestModelAttribute</title>
</head>
<body>
    <c:forEach items="${accounts}" var="item">
        <c:out value="${item.userName}"></c:out><br/>
    </c:forEach>
</body>
</html>
复制代码

页面将输出:

在Console中输出为:

 

这里可以看到,运行的先后次序为:先调用getAccounts(),再调用index()。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值