`
wisfly
  • 浏览: 60955 次
  • 性别: Icon_minigender_2
  • 来自: 杭州
社区版块
存档分类
最新评论

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

 

THE END

 小伙伴们,我开了一家海淘护肤品淘宝店,搜索店铺“禾子蝶的海淘铺”,正品保证,欢迎进店选购哦。谢谢!

分享到:
评论

相关推荐

    Spring MVC 之@ModelAttribute使用.rar

    Spring MVC 之@ModelAttribute使用.rar

    PNC_Lab04:Ingreso产品@Valid @ModelAttribute和BindingResult。 SpringMVC

    PNC_Lab04:Ingreso产品@Valid @ModelAttribute和BindingResult。 SpringMVC

    spring mvc中注解@ModelAttribute的妙用分享

    主要给大家介绍了关于spring mvc中注解@ModelAttribute妙用的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Android具有一定的参考学习价值,需要的朋友们下面来一起看看吧。

    Spring3MVC 在JSP中使用@ModelAttribute

    NULL 博文链接:https://liukai.iteye.com/blog/973717

    modelAttribute详解

    在学习SpringMVC的过程中,关于@ModelAttribute的使用方法一度遇到一些奇怪的问题,在深入研究源码之后,基本上弄清楚了其内部实现的原理。对于自己的理解有误区的地方进行了纠正,现进行总结如下: @...

    [Spring MVC] - ModelAttribute使用.docx

    在Spring MVC里,@ModelAttribute通常使用在Controller方法的参数注解中,用于解释model entity,但同时,也可以放在方法注解里。 如果把@ModelAttribute放在方法的注解上时,代表的是: 该Controller的所有方法在...

    ModelAttribute注解详细使用.docx

    org.springframework.web.bind.annotation.ModelAttribute注解类型将请求参数绑定到...提示:被@ModelAttribute注释的方法会在Controller每个方法执行前被执行,因此在一个Controller映射到多个URL时,要谨慎使用。

    SpringMVC ModelAttribute详解.docx

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

    springMVC详解以及注解说明

    • @ModelAttribute • @Cacheable • @CacheFlush • @Resource • @PostConstruct • @PreDestroy • @Repository • @Component (不推荐使用) • @Scope • @SessionAttributes • @InitBinder

    SpringMVC接收请求参数所有方式总结

    二、使用注解@DateTimeFormat或者@JsonFormat 15 三、Jackson序列化和反序列化定制 16 四、最佳实践 17 请求URL匹配 17 ‘?’形式的URL: 18 ‘*‘形式的URL: 18 ‘**‘形式的URL: 18 {spring:[a-z]+}形式的URL: ...

    spring mvc 参数绑定漏洞

    NULL 博文链接:https://yfm049.iteye.com/blog/860494

    SpringMVC SessionAttribute 使用说明.docx

    @ModelAttribute注解作用在方法上或者方法的参数上,表示将被注解的方法的返回值或者是被注解的参数作为Model的属性加入到Model中,然后Spring框架自会将这个Model传递给ViewResolver。Model的生命周期只有一个http...

    CRUDwebAppMavenized:这是在eclipse中使用Maven构建的spring、hibernate和Mysql项目

    使用 Spring、Hibernate、MySQL 添加、编辑、删除、搜索 设置动态 Web 项目并将其转换为 maven 项目 添加依赖项 - 确保在 maven 中进行全新安装,将您需要的 jars 放入项目中,这样您在编码时就不会出现库问题 设置...

    SSM入门到精通项目实战(附源码)

    掌握SpringMVC的项目整合配置,@Controller,@RequestMapping,@Resource,@PathVariable,@ResponseBody,@ModelAttribute,@CookieValue,@Transactional等注解的使用,json数据传值,国际化,拦截器,权限控制,...

    Spring MVC 3.0实战指南.ppt

    使用@RequestBody/@ResponseBody 使用HttpEntity&lt;T&gt;/ResponseEntity&lt;T&gt; 输出XML和JSON 使用HttpEntity&lt;T&gt;/ResponseEntity&lt;T&gt; 目录 数据绑定机理 数据类型转换 PropertyEditor依然有效 强大的ConversionService,让很...

    Spring3MVC注解教程.ppt

    使用@RequestBody/@ResponseBody 使用HttpEntity&lt;T&gt;/ResponseEntity&lt;T&gt; 输出XML和JSON 使用HttpEntity&lt;T&gt;/ResponseEntity&lt;T&gt; 目录 数据绑定机理 数据类型转换 PropertyEditor依然有效 强大的...

    springboot学习思维笔记.xmind

    使用容器发布事件 Spring高级话题 Spring Aware BeanNameAware BeanFactoryAware ApplicationContextAware MessageSourceAware ApplicationEventPublisherAware ResourceLoaderAware 多...

    Spring中文帮助文档

    使用@ModelAttribute提供一个从模型到数据的链接 13.12.6. 使用@SessionAttributes指定存储在会话中的属性 13.12.7. 自定义WebDataBinder初始化 13.13. 更多资源 14. 集成视图技术 14.1. 简介 14.2. JSP和...

    Spring API

    使用@ModelAttribute提供一个从模型到数据的链接 13.12.6. 使用@SessionAttributes指定存储在会话中的属性 13.12.7. 自定义WebDataBinder初始化 13.13. 更多资源 14. 集成视图技术 14.1. 简介 14.2. JSP和...

    rest风格+jdbctemplate的CRUD操作.rar

    ④修改用户:先根据id查询员工(get请求),然后跳转到修改页面,使用form标签回显当前对象内容${pageContext.request.contextPath }/emp"method="post" modelAttribute="employee"&gt;然后将封装好的对象传给控制器...

Global site tag (gtag.js) - Google Analytics