spring boot 基于spring MVC的基础上进行了改进, 将@Controller 与@ResponseBody 进行了合并成一个新的注解 @RestController。
当用户请求时,需要有视图渲染的,与请求数据的请求分别使用@Controller与@RestController 。
- import org.springframework.boot.SpringApplication;
-
- import org.springframework.boot.autoconfigure.SpringBootApplication;
-
-
-
-
-
-
-
-
-
- @SpringBootApplication
-
- publicclassApp {
-
- publicstatic void main(String[] args) {
-
- SpringApplication.run(App.class, args);
-
- }
-
- }
请求数据:
- import org.springframework.web.bind.annotation.RequestMapping;
-
- import org.springframework.web.bind.annotation.RestController;
-
-
-
- @RestController
-
- public class HelloController {
-
-
- @RequestMapping(value={"/",""},method={RequestMethod.POST,RequestMethod.GET},produces = "application/json; charset=UTF-8")
-
- public String hello(){
-
- return"Hello world!";
-
- }
-
- }
返回数据:
如果返回类型的是一个 Class, value 是请求的映射集合, method是请求格式的集合,produces 是返回数据格式。
请求包含数据的视图:
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- @Controller
- @RequestMapping("/demo")
- public class DemoController {
- @RequestMapping("/getDemo")
- public String getDemo() {
- Map map=new HashMap();
- map.put("key","value");
- return "demo";
- }
- }
页面会跳转到 对应的 demo.html 或者 demo.jsp 页面。