设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 数据 创业者 手机
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

Spring MVC @ModelAttribute说明

发布时间:2022-07-19 11:57 所属栏目:51 来源:互联网
导读:本文介绍在 Spring MVC 中非常重要的注解 @ModelAttribute,用来将请求参数绑定到 Model 对象。 以上示例,在请求 /model?name=%E7%BC%96%E7%A8%8B%E5%B8%AE 后,Spring MVC 会先执行 myModel 方法,将 name 的值存入到 Model 中。然后执行 model 方法,这样
  本文介绍在 Spring MVC 中非常重要的注解 @ModelAttribute,用来将请求参数绑定到 Model 对象。
 
  以上示例,在请求 /model?name=%E7%BC%96%E7%A8%8B%E5%B8%AE 后,Spring MVC 会先执行 myModel 方法,将 name 的值存入到 Model 中。然后执行 model 方法,这样 name 的值就被带到了 model 方法中。
 
  将 myModel 和 model 方法合二为一后,代码如下。
  @RequestMapping(value = "/model")
  public String model(@RequestParam(required = false) String name, Model model) {
      model.addAttribute("name", name);
      return "index";
  }
  2)应用在有返回值的方法
  示例 2:修改 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("name")
      public String myModel(@RequestParam(required = false) String name) {
          return name;
      }
      @RequestMapping(value = "/model")
      public String model() {
          return "index";
      }
  }
  修改 index.jsp,代码如下。
  <%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
  <!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>编程帮</title>
  </head>
  <body>
      ${string }
  </body>
  </html>
  访问地址和运行结果与示例 1 相同。
 
  对于以上情况,返回值对象 name 会被默认放到隐含的 Model 中,在 Model 中 key 为返回值首字母小写,value 为返回的值。等同于 model.addAttribute("string", name);。

(编辑:ASP站长网)

    网友评论
    推荐文章
      热点阅读