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);
}
}