Spring MVC @ModelAttribute注解

本文介绍在 Spring MVC 中非常重要的注解 @ModelAttribute,用来将请求参数绑定到 Model 对象。

在 Controller 中使用 @ModelAttribute 时,有以下几种应用情况。
应用在方法上
应用在方法的参数上
应用在方法上,并且方法也使用了 @RequestMapping

需要注意的是,因为模型对象要先于 controller 方法之前创建,所以被 @ModelAttribute 注解的方法会在 Controller 每个方法执行之前都执行。因此一个 Controller 映射多个 URL 时,要谨慎使用。

  1. 应用在方法上
    下面从应用在有无返回值的方法上两个方面进行讲解。
    1)应用在无返回值的方法
    示例 1:创建 ModelAttributeController,代码如下。
    package net.biancheng.controller;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    @Controller
    public class ModelAttributeController {
    // 方法无返回值
    @ModelAttribute
    public void myModel(@RequestParam(required = false) String name, Model model) {
    model.addAttribute(“name”, name);
    }
    @RequestMapping(value = “/model”)
    public String model() {
    return “index”;
    }
    }
    创建 index.jsp 页面,代码如下。
    <%@ page language=“java” contentType=“text/html; charset=UTF-8”
    pageEncoding=“UTF-8”%>
编程帮 ${name } 访问地址:http://local
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值