@RequestMapping("/return2")
@Controller
public class ReturnController2 {
@RequestMapping("/index")
public String returnIndex(){
return "/index.html";
}
}
@Controller : 定义⼀个控制器, Spring 框架启动时加载, 把这个对象交给Spring管理.
@ResponseBody : 定义返回的数据格式为⾮视图, 返回⼀个 text/html 信息
@Target
@Target ({ElementType.TYPE})表示类类型(修饰的是对象)
@Retention(RetentionPolicy.RUNTIME)表示生命周期
@RestController
@Controller+@ResponseBody
🎈返回数据@ResponseBody
@ResponseBody可以修饰类也可以修饰方法。
修饰类的时候,表示这个类下的所有方法,返回的均为数据
如果一个类中的所有方法返回的都是数据,我们就把这个注解加在类上。
修饰方法时,表示该方法返回的是数据
🎈返回html代码片段
@ResponseBody
@RequestMapping("/returnHtml")
public String returnHtml(){
return "<h1>返回HTML代码片段<h1>";
}
🎈返回JSON
当我们接口返回的是String时,content-Type是text/html
@ResponseBody
@RequestMapping("/returnDate")
public String returnIndex2(){
return "查看视图需要的数据";
}
当我们的接口返回的是对象时,content-Type自动设置成application/json
//返回JSON
@ResponseBody
@RequestMapping("/returnJson1")
public Person returnJson(){
Person person=new Person();
person.setAge(20);
person.setName("张老师");
person.setId(1);
return person;
}