码迷,mamicode.com
首页 > 其他好文 > 详细

@ModelAttribute用法

时间:2018-08-28 01:08:21      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:方法签名   mapping   ppi   方法   nsa   map   详解   ini   imp   

@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用法

标签:方法签名   mapping   ppi   方法   nsa   map   详解   ini   imp   

原文地址:https://www.cnblogs.com/qiudaozhang/p/9545327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!