详细讲解@Controller和@RestController的区别

对于很多Java后端开发人员,使用注解开发是一件很快捷的方式,接下来讲解RestController注解。

其实@RestController注解就相当于@ResponseBody 和@Controller合在一起的作用的。
使用RestController的效果是将方法返回的对象直接在浏览器上展示成json格式,而如果单单使用@Controller会报错,需要ResponseBody配合使用。如果只是使用@RestController注解Controller类,则方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。
比如本来应该到success.jsp页面的,则其显示success,如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解就可以了。

/**
 * @ClassName WareController
 * @Author pain
 * @Date 2019/1/10 13:53
 * @Version 1.0
 **/
@RestController
@RequestMapping("/seckill")
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")    // 跨域请求
public class WareController {
    @Autowired
    WareService wareService;
    @Autowired
    HttpServletRequest httpServletRequest;
    @PostMapping("/createitem")
    public CommonResult addWare(@Valid WareModel wareModel, BindingResult bindingResult) throws ProcessException {
        // 检查校验是否有错误,如果有错误,抛出ProcessException异常并自定义异常信息
        if (bindingResult.hasErrors()) {
            // 从BindingResult中获取错误信息
            String errorMsg = BindingResultUtil.getErrorFromBingdingResult(bindingResult);
            // 抛出异常
            throw new ProcessException(ProcessErrorEnum.INVALID_PARAMETER, errorMsg);
        }
        // 调用WareService的insertWare()方法添加商品
        wareService.insertWare(wareModel);
        return CommonResult.create(null, "success");
    }

猜你喜欢

转载自blog.csdn.net/realize_dream/article/details/105330493