@RequestMapping
用来生成地址,例如:
@Controller
public class StudentController {
//生成的接口地址为:http://localhost:8080/student
//等价于@GetMapping("student")
@RequestMapping(value = "student",method = RequestMethod.GET)
public String student(){
return "这是学生接口";
}
//生成的接口地址为:http://localhost:8080/student/name
//等价于@PostMapping("student/name")
@RequestMapping(value = "student/name",method = RequestMethod.POST)
public String studentName(){
return "这是学生姓名接口";
}
}
@RequestMapping也可以放在类上,相当于该类中的所有方法地址前先加上类上@RequestMapping中的地址,例如:
@Controller
@RequestMapping("class")
public class StudentController {
//生成的接口地址为:http://localhost:8080/class/student
//等价于@GetMapping("student")
@RequestMapping(value = "student",method = RequestMethod.GET)
public String student(){
return "这是学生接口";
}
//生成的接口地址为:http://localhost:8080/class/student/name
//等价于@PostMapping("student/name")
@RequestMapping(value = "student/name",method = RequestMethod.POST)
public String studentName(){
return "这是学生姓名接口";
}
}
@ResponseBody
将接口的返回结果以JSON的格式返回;例如:
@Controller
public class StudentController {
@ResponseBody
@RequestMapping(value = "student",method = RequestMethod.GET)
public Student student(){
Student student = new Student();
student.setId("123456");
student.setName("张三");
student.setAge(20);
return student;
}
}
这里可以看到方法的返回值类型是Student对象,调用接口的结果如下图,结果自动转换为了JSON格式,一般在前后端的交互中数据通常是以JSON格式来交互的。
@ResponseBody注解也可以放在类上,表示该类下的所有方法的返回值都会转换成JSON,相当于该类中的所有方法上都加上了@ResponseBody注解,例如:
@Controller
@ResponseBody
public class StudentController {
@RequestMapping(value = "student",method = RequestMethod.GET)
public Student student(){
Student student = new Student();
student.setId("123456");
student.setName("张三");
student.setAge(20);
return student;
}
}
接口结果同样为JSON格式:
还有一个最常用的方法,用@RestController来代替@Controller;
@RestController就相当于是@Controller和@ResponseBody的组合应用;
这种方式使用的最多也最方便!!! 例如:
@RestController
public class StudentController {
@RequestMapping(value = "student",method = RequestMethod.GET)
public Student student(){
Student student = new Student();
student.setId("123456");
student.setName("张三");
student.setAge(20);
return student;
}
}