spring boot 处理请求的方式 Controller 与RestController

spring boot 基于spring MVC的基础上进行了改进, 将@Controller 与@ResponseBody 进行了合并成一个新的注解 @RestController。

当用户请求时,需要有视图渲染的,与请求数据的请求分别使用@Controller与@RestController 。

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

/**

 * Hello world!

 */

//其中@SpringBootApplication申明让spring boot自动给程序进行必要的配置,等价于以默认属性使用@Configuration,@EnableAutoConfiguration和@ComponentScan

@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// 标记为:restful

public class HelloController {
   

    @RequestMapping(value={"/",""},method={RequestMethod.POST,RequestMethod.GET},produces = "application/json; charset=UTF-8")

    public String hello(){

       return"Hello world!";

    }

}
返回数据:
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 页面。

下一章讲用户配置的几种模板支持。

你可能感兴趣的:(Spring,boot)