@ModelAttribute用法

Posted qiudaozhang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了@ModelAttribute用法相关的知识,希望对你有一定的参考价值。

@ModelAttribute用法详解

1 用在方法上方式一

package com.sz.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;

@Controller
@RequestMapping("/hello")
public class HelloController {

    @ModelAttribute
    public void init(Model model){
        model.addAttribute("girl","菲菲");
    }


    @RequestMapping("/m1")
    public String m1(Model model) {
        System.out.println(model.containsAttribute("girl"));
        System.out.println(model.containsAttribute("girl2"));

        return "msg";
    }
}
// 结果为 true false

逻辑上任何具体请求处理之前先执行init方法,也就是说在model当中一定会存在init当中添加的内容。

2. 作为方法上方式二

package com.sz.controller;

import com.sz.pojo.Girl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/hello")
public class HelloController {

 

    @ModelAttribute("girl")
    public Girl init(Model model){
        Girl g  = new Girl();
        g.setAge(28);
        g.setName("菲菲");
        return g;
    }


    @RequestMapping("/m1")
    public String m1(Model model) {
        System.out.println(model.containsAttribute("girl"));
        System.out.println(model.containsAttribute("girl2"));

        return "msg";
    }

 
}
//结果为true false

3. 用在方法参数签名

package com.sz.controller;

import com.sz.pojo.Girl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/hello")
public class HelloController {
 
    @RequestMapping("/m2")
    public String m2(@ModelAttribute("girl") Girl girl,Model model) {

        System.out.println(model.containsAttribute("girl"));
        System.out.println(model.containsAttribute("girl2"));
        System.out.println(girl.getName() + girl.getAge());
        return "msg";
    }
}
// 结果为true false

4. 用在方法签名上并且使用路径变量绑定

@RequestMapping("/m2/{age}/{name}")
public String m2(@ModelAttribute  Girl girl ,Model model  ) {

    System.out.println(model.containsAttribute("girl"));
    System.out.println(model.containsAttribute("girl2"));
    System.out.println(girl.getName() + girl.getAge());
    return "msg";
}
// true
// false
// fifi28

以上是关于@ModelAttribute用法的主要内容,如果未能解决你的问题,请参考以下文章

全面解析Spring中@ModelAttribute注解的用法

Spring MVC @ModelAttribute详解

@PathVariable和@RequestParam的区别,@SessionAttributes, @ModelAttribute的用法

@ModelAttribute运用详解

@ModelAttribute 注解

spring学习之@ModelAttribute运用详解