欢迎光临
感受代码之美

Spring注解@Controller和@RestController的区别?

官方文档:Annotation Type RestController 解释说:A convenience annotation that is itself annotated with @Controller and @ResponseBody

也就是@RestController注解相当于控制器前加@Controller,方法前加@ResponseBody共同的作用效果。

@RestController
@RequestMapping(value = "/login")
public class LoginController {
    @RequestMapping(value = "/loginSuccess")
    public String loginSuccess(SrClass srClass) {
        return "success";
    }
}

上面这段代码相当于

@Controller
@RequestMapping(value = "/login")
public class LoginController {

    @RequestMapping(value = "/loginSuccess")
    @ResponseBody
    public String loginSuccess(SrClass srClass) {
        return "success";
    }
}

如果第二段代码不加@ResponseBody,返回的就是success.jsp页面,加上之后返回的就是success字符串;而第一段代码返回的也是success,不再经过视图解析器解析了。

转载请注明来源:四个空格 » Spring注解@Controller和@RestController的区别?

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址