Categories

Tags

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.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.返回具体类的方法
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>