Spring:基于注解的MVC程序示例

控制层(C)

首先创建一个controller

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class GreetingController {
    @RequestMapping("/greeting")
    public String greeting(@RequestParam(value="name", defaultValue="world")String name, Model model){
        model.addAttribute("name", name);
        return "index";
    }
}

@Controller注解标注这个类是一个控制类;

@RequestMapping("/greeting")注解映射/greeting访问到此方法;

@RequestParam(value="name", defaultValue="world")注解将请求中的name参数传递给变量,若无取默认值;

model 对象添加的属性可以从前台取到;

return 返回的值即为此controller绑定的页面名。

视图层(V)

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
    <p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>

启动应用程序

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) throws Exception{
        SpringApplication.run(Application.class, args);
    }
}

然后浏览器访问: http://localhost:8080/greeting?name=John

posted @ 2019-01-16 10:47  xuejianbest  阅读(151)  评论(0编辑  收藏  举报