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

[Spring MVC] - @ModelAttribute使用的更多相关文章

  1. Spring MVC @ModelAttribute详解

    被@ModelAttribute注释的方法会在此controller每个方法执行前被执行,因此对于一个controller映射多个URL的用法来说,要谨慎使用. 我们编写控制器代码时,会将保存方法独立 ...

  2. Spring MVC @ModelAttribute注解

    在一个Controller内,被@ModelAttribute标注的方法会在此controller的每个handler方法执行前被执行. 被@ModelAttribute标注的方法的参数绑定规则和普通 ...

  3. Spring MVC @ModelAttribute

    1.@ModelAttribute注释void返回值的方法 @Controller public class HelloModelController { @ModelAttribute public ...

  4. spring mvc @ModelAttribute 每次执行requestmapping前自动执行

    在不少应用场景中,我们希望在每次执行requestmapping前自动执行一些操作,比如把某些数据(比如数据字典.系统配置.标准错误号,这在企业应用系统中极为常见)塞到model中供view访问,因为 ...

  5. Spring MVC @ModelAttribute 详解

    1.@ModelAttribute注释void返回值的方法 @Controller public class HelloModelController { @ModelAttribute public ...

  6. Spring MVC 对于@ModelAttribute 、@SessionAttributes 的详细处理流程

    初学 Spring MVC , 感觉对于 @ModelAttribute 和 @SessionAttributes 是如何被Spring MVC处理的,这一流程不是很清楚, 经过Google资料,有了 ...

  7. spring3 jsp页面使用<form:form modelAttribute="xxxx" action="xxxx">报错,附连接数据库的spring MVC annotation 案例

    在写一个使用spring3 的form标签的例子时,一直报错,错误信息为:java.lang.IllegalStateException: Neither BindingResult nor plai ...

  8. spring mvc:@RequestParam与@ModelAttribute异同

    关于spring mvc中的两个注解:@RequestParam.@ModelAttribute区别,原先并没有特别注意,直到最近找别人开发的一个小模块的bug时,才有意识的比较了两者的区别. 1.@ ...

  9. spring mvc:注解@ModelAttribute妙用

    在Spring mvc中,注解@ModelAttribute是一个非常常用的注解,其功能主要在两方面: 运用在参数上,会将客户端传递过来的参数按名称注入到指定对象中,并且会将这个对象自动加入Model ...

随机推荐

  1. JavaScript数组API

    1.将数组转化为字符串:2种:               1.var str=String(str);                       将数组转化为字符串并分隔每个元素          ...

  2. (Python)导出指定文件夹中as文件的完全限定类名

    AS3程序在编译的过程中,有一个特点是这样的,不管是项目中的类,还是标准库或者第三方库的类,编译的时候只会把用到的那些类文件编译进去,也就是说,某一些类,只要没有被主程序引用到,那这个文件是不会被编译 ...

  3. 错误信息:System.Resources.MissingManifestResourceException: 未能找到任何适合于指定的区域或非特定区域性的资源。请确保在编译时已将“****.****.Resource.resources”正确嵌入或链接到程序集"****",或者确保所有需要的附属程序集都可加载并已进行了完全签名

    在网上搜索了N久都没看到几篇解决的文章,最后在不懈的努力下终于解决了,所以决定写下解决方法方便以后遇到同样问题的朋友: 其实这个错误的主要问题就是没有找到需要的资源文件(该文件为Resources.r ...

  4. “不支持一个STA线程上针对多个句柄的WaitAll。”的解决方案

    一.异常提示 不支持一个 STA 线程上针对多个句柄的 WaitAll. 出错界面如下图: 二.解决方法 先直接上解决方案吧.其实解决方法很简单如下面的代码直接把main函数的[STAThread]属 ...

  5. C#获取参数getParameter

    昨天遇到了这样一个问题,getParameter时,首次进入页面读取默认值时,本应该读取到“全部”这个字符. 然后在实际读取过程当中却不是这样,实际读取到的是  类的对象值 重新运行时能够读取到 “全 ...

  6. CSS3中媒体查询,更换样式表

    <link rel="stylesheet" href="css/1.css" media="(min- width:600px)"& ...

  7. good

    1,将NodeList 转化成 Arrayvar divs = Array.from(document.querySelectorAll('div'));2,将 arguments 转化成 Array ...

  8. 【C语言学习】-06 函数

    函数分类.函数声明和定义.函数调用,形参实参.函数嵌套调用

  9. spirng定时任务的两种配置:注解和xml

    一 使用注解Task 1.在applicationContext.xml中配置 <?xml version="1.0" encoding="UTF-8"? ...

  10. loadrunner的基本操作

    一.遗留问题: 1.controller中,到设置的时间后,仍然在运行: 2.如何对多个用例的结果进行分析,找到系统可以承受的最佳的用户数量点: 3.vuser与实际的用户访问数量是一回事吗?比如vu ...