SpringMVC的ModelAttribute注解

ModelAttribute注解的方法会在controller每个方法执行前被执行

User.java

public class User {
    private int id;
    private String name;

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

用法1.@ModelAttribute注释void返回值的方法
HelloController.java

@Controller
public class HelloController {
    @ModelAttribute
    public void before(@RequestParam String name, Model model) {
        model.addAttribute("myname", name);
    }

    @RequestMapping(value = "/sayhello")
    public String sayhello() {
        return "hello";
    }
}

hello.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>hello</title>
</head>
<body>
    hello,My name is ${myname}
</body>
</html>

浏览器运行http://localhost:8080/sayhello?name=xiaoming

显示 hello,My name is xiaoming

===
用法2.@ModelAttribute注释返回具体类的方法
HelloController.java

@Controller
public class HelloController {
    @ModelAttribute
    public User before() {
        User user=new User();
        user.setName("xiaoming");
        return user;
    }

    @RequestMapping(value = "/sayhello2")
    public String sayhello() {
        return "hello2";
    }
}

hello2.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>hello2</title>
</head>
<body>
    hello,My name is ${user.name}
</body>
</html>

浏览器运行http://localhost:8080/sayhello2
显示 hello,My name is xiaoming

修改对象

    @RequestMapping(value = "/sayhello2")
    public String sayhello(User user) {//参数为User
        user.setName("zhangsan");//修改
        return "hello2";
    }

浏览器运行http://localhost:8080/sayhello2
显示 hello,My name is zhangsan

指定对象名称

    @RequestMapping(value = "/sayhello2")
    public String sayhello(@ModelAttribute("myUser") User user) {//类为User,对象名称为myUser
        user.setName("zhangsan");//修改
        return "hello2";
    }

hello2.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title>hello2</title>
</head>
<body>
    hello,My name is ${myUser.name}
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值