在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()。

springMVC注解用法:@modelattribute的用法的更多相关文章

  1. SpringMVC常用注解的规则(用法)

    SpringMVC注解 @RequestMapping用法:    a. 用在controller方法上:        标记url到请求方法的映射, 其实就是通过一段url地址, 找到对应需要执行的 ...

  2. SpringMVC +mybatis+spring 结合easyui用法及常见问题总结

    SpringMVC +mybatis+spring 结合easyui用法及常见问题总结 1.FormatString的用法. 2.用postAjaxFillGrid实现dataGrid 把form表单 ...

  3. XStream中几个注解的含义和用法

    转自:http://blog.csdn.net/robert_mm/article/details/8459879 XStream是个很强大的工具,能将java对象和xml之间相互转化.xstream ...

  4. xstream中几个注解的含义和用法(转)

    XStream是个很强大的工具,能将Java对象和xml之间相互转化.xstream不在意java类中成员变量是私有还是公有,也不在乎是否有默认构造函数.它调用方式也非常简单:从xml对象转化为jav ...

  5. springMVC注解初步

    一.(补充)视图解析器---XmlViewResolver 作用:分离配置信息. 在视图解析器---BeanNameViewResolver的基础之上进行扩充,新建一个myView.xml分离信息 在 ...

  6. SpringMVC注解开发初步

    一.(补充)视图解析器---XmlViewResolver 作用:分离配置信息. 在视图解析器---BeanNameViewResolver的基础之上进行扩充,新建一个myView.xml分离信息 在 ...

  7. springMVC 注解版

    http://blog.csdn.net/liuxiit/article/details/5756115 http://blog.csdn.net/hantiannan/article/categor ...

  8. springmvc注解

    简介: handler method 参数绑定常用的注解,我们根据他们处理的Request的不同内容部分分为四类:(主要讲解常用类型) A.处理requet uri 部分(这里指uri templat ...

  9. Spring+SpringMVC+MyBatis深入学习及搭建(十六)——SpringMVC注解开发(高级篇)

    转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/7085268.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十五)——S ...

  10. springmvc注解@Controller和@RequestMapping

    Spring从2.5版本引入注解,从而让开发者的工作变得非常的轻松 springmvc注解Controller org.springframework.stereotype.Controller注解类 ...

随机推荐

  1. ios svn repository

    xcode默认自带Git和svn,首先讲下xcode4.6.3下配置svn: 1.检測你的mac中是否安装了svn: (1) 打开终端,输入 svn --version 假设出现下图信息,则说明已经安 ...

  2. 基于MVC4+EasyUI的Web开发框架经验总结(13)--DataGrid控件实现自己主动适应宽带高度

    在默认情况下,EasyUI的DataGrid好像都没有具备自己主动宽度的适应功能,通常是指定像素宽度的.可是使用的人员计算机的屏幕分辨率可能不一样,因此导致有些地方显示太大或者太小,总是不能达到好的预 ...

  3. Create an ASP.NET Core web app in Visual Studio Code

    https://www.microsoft.com/net/core#windowscmd https://download.microsoft.com/download/B/9/F/B9F1AF57 ...

  4. tp5框架知识点

    项目包含的关键点,后台,前台. 入口文件. 通用配置文件. 数据库配置文件. 共有文件,css,images,js. 控制器,模型,视图. 共有类. 共有函数. 属性,方法. 命名规范. 命名空间. ...

  5. [USACO07JAN]平衡的阵容Balanced Lineup RMQ模板题

    Code: #include<cstdio> #include<algorithm> using namespace std; const int maxn = 50000 + ...

  6. OR1200处理器中Wishbone总线接口模块WB_BIU介绍

    下面内容摘自<步步惊芯--软核处理器内部设计分析>一书 WB_BIU模块是OR1200处理器与外部Wishbone总线连接的接口模块.15.1节给出了WB_BIU模块的对外连接关系,并指出 ...

  7. [Python] Finding the most common elements in an iterable

    >>> import collections >>> # Tally occurrences of words in a list >>> cnt ...

  8. android SIM Switch功能和配置

    SIM Switch feature是Smart 3G switch feature在LTE版本号上发展演变而来的功能: MTK双卡双待单通版本号仅仅有一个3/4 G Protocol.所以同一时刻仅 ...

  9. 安装个wampserver 环境 执行php

    php代码执行要有相关环境. 在这里推荐一个环境工具.wampserver :内置了下面工具: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5 ...

  10. J2SE基础:2.对象的创建与使用

    1:參数传递的值传递与引用传递 A:值传递:基本数据类型传递都是值传递 B:引用传递(地址传递):对象数据类型都是引用传递. 2:类变量与成员变量(实例变量,对象变量) 类变量:通过类名调用,类变量被 ...