@RestController处理http请求,其实相当于@Controller和@ResponseBody组合。 @RequestMapping配置url映射
1、加maven依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fernández创建,该作者还是Java加密库Jasypt的作者。2、Controller上只使用@Controller 3、工程resources目录下,templates目录下新建*.html。 4、url映射的方法中返回上一步的文件名。
前后端分离来进行开发,后端只提供数据,所以不推荐使用
@PathVariable获取路径中的值,这是RESTful方式
@RequestMapping(value = "/person/{name}",method = RequestMethod.GET) public String person(@PathVariable("name") String name){ // http://localhost:8060/girl/person/kakaluote return "say hello to " + name; }@RequestParam获取路径中的值,传统方式,post和get都一样
@RequestMapping(value = "/person",method = RequestMethod.GET) public String book(@RequestParam("book") String book){ // http://localhost:8060/girl/person?book=java return "say hello to " + book; }@RequestParam设置默认值
@RequestMapping(value = "/man",method = RequestMethod.GET) public String bookOne(@RequestParam(value = "book",required = false,defaultValue = "spring boot") String book){ //required表示是否必传 // http://localhost:8060/girl/man // http://localhost:8060/girl/man?book=java return "say hello to " + book; }@RequestMapping每次都写method比较麻烦,用@GetMapping和@PostMapping等替代,方便很多
@GetMapping(value = "/weather/get") public String getWeather(){ return "qinglang"; } @PostMapping(value = "/weather/post") public String postWeather(){ return "xiayu"; }Spring Boot基础