package com.example.initializr_test.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
//@Controller注解表明了这个类是一个控制器类
//不加@Response注解,则当直接返回一个字符串的时候,就好比返回的是一个模板页面,类似我们返回一个jsp页面一样。所以我们需要加上模板引擎(这种返回html一类的模板的开发方式现在一般不会再用了,因为现在都是前后端分离式的开发,后台服务器一般只需要返回json格式的数据即可,所以了解即可)
//在pom.xml文件中加入spring-boot-starter-thymeleaf模板引擎
//
//
// org.springframework.boot
// spring-boot-starter-thymeleaf
//
//
//然后在resources/templates目录下创建html页面
//例如:controller中返回的字符串是update,就代表返回的是resources/templates目录下的update.html页面
@Controller
//@ResponseBody表示方法的返回值直接以指定的格式写入Http response body中,而不是解析为跳转路径。
@ResponseBody
//设置url的访问方式
//@RequestMapping注解是用来映射请求的,即指明处理器可以处理哪些URL请求,该注解既可以用在类上,也可以用在方法上。
//当使用@RequestMapping标记控制器类时,方法的请求地址是相对类的请求地址而言的;当没有使用@RequestMapping标记类时,方法的请求地址是绝对路径。
@RequestMapping("/test")
//@RestController
//@RestController注解,代表返回的是json格式的数据,这个注解是Spring4之后新加的注解,原来返回json格式的数据需要@ResponseBody配合@Controller一起使用;
//@RestController的作用等同于@Controller + @ResponseBody。
//如果要求方法返回的是json格式数据,而不是跳转页面,可以直接在类上标注@RestController,而不用在每个方法中标注@ResponseBody,简化了开发过程。
public class TestController {
//变量赋值
@Value("${com.didispace.test.name}")
private String name;
@Value("${com.didispace.test.title}")
private String title;
// @RequestMapping("/insert")
//method指定请求方法类型
//设置url的访问方式
@RequestMapping(value = "/insert/{id}",method = {RequestMethod.POST})
//返回值是字符串类型的,这个就是处理器在处理完任务后将要跳转的页面。如果想要方法直接返回结果,而不是跳转页面,这就要用到@ResponseBody注解了。
//@PathVariable注解获取url中的参数
public String insert(@PathVariable Integer id){
System.out.println("id:"+id);
System.out.println("name:"+name);
System.out.println("title:"+title);
return "update";
}
public void update(){
System.out.println("called update method");
}
@RequestMapping(value = "/request_param_test",method = {RequestMethod.POST})
// @RequestParam("id")注解获取请求的body中的参数
public void request_param_test(@RequestParam(value="id",required = false,defaultValue = "0") Integer id){
System.out.println("id:"+Integer.toString(id));
}
@PostMapping(value="/post_mapping_test")
// 直接指定了请求方式
public void post_mapping_test(@RequestParam(value="id",required = false,defaultValue = "0") Integer id){
System.out.println("id:"+Integer.toString(id));
}
@GetMapping(value="/reset_controller_test")
// 直接指定了请求方式
public String reset_controller_test(){
System.out.println("reset_controller_test");
return "reset_controller_test";
}
}
加载中,请稍候......