我們一般都會(huì)在Controller上加上@Controller注解,但是有時(shí)候也見(jiàn)有加上@RestController的,現(xiàn)在就說(shuō)說(shuō)他們的區(qū)別:
1、不同。
@Controller類(lèi)中的方法可以直接通過(guò)返回String跳轉(zhuǎn)到j(luò)sp、ftl、html等模版頁(yè)面。在方法上加@ResponseBody注解,也可以返回實(shí)體對(duì)象。
@RestController類(lèi)中的所有方法只能返回String、Object、Json等實(shí)體對(duì)象,不能跳轉(zhuǎn)到模版頁(yè)面。
@RestController相當(dāng)于@ResponseBody + @Controller。
2、補(bǔ)充
@RestController中的方法如果想跳轉(zhuǎn)頁(yè)面,則用ModelAndView進(jìn)行封裝,如下:
@RestController
public class UserController {
@RequestMapping(value = "/index",method = RequestMethod.GET)
public String toIndex(){
ModelAndView mv = new ModelAndView("index");
return mv;
}
}