@Controller和@RestController区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HSH205572/article/details/84384096

如下是@RestController的源码:

package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.stereotype.Controller;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    String value() default "";
}

从源码中可以看出@RestController注解相当于是把@ResponseBody + @Controller的作用合在了一起。

下面将分别从@Controller和@RestController返回页面和返回数据内容格式两方面做对比区分:

一  返回jsp或者html页面本身:
1. 如果只是使用@RestController注解Controller类,则Controlle类中的方法无法返回jsp等页面,配置的视图解析器InternalResourceViewResolver也不起作用,其返回的内容就是return 里的内容。

demo如下:

@RequestMapping("/initDataShow")
public String initDataShow() {
    return "homeProfile/population_data_show";
}

上述本来是想通过return "homeProfile/population_data_show";等 跳转到population_data_show.jsp页面的,但其只显示homeProfile/population_data_show 内容本身。

2. 如果需要返回到指定页面,则需要用 @Controller 再配合视图解析器InternalResourceViewResolver才行。


二  返回JSON,XML或自定义mediaType内容到页面
1.  使用@Controller注解Controller类,当Controller类中的方法需要返回JSON,XML或自定义mediaType等格式内容到页面时,则需要在对应的方法上加上@ResponseBody注解。

demo如下:

@RequestMapping("/api/test")
@Controller
public class TestController {

    @Autowired
    private SuoGeApiService suoGeApiService;

    @RequestMapping(value = "/test02", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public AjaxResult test02(@RequestParam(value = "nbxh", required = true) String nbxh) throws Exception {
        FrDto dto = suoGeApiService.getFrDto(nbxh);
        return AjaxResult.success(null, dto);
    }
}

2.  使用@RestController注解Controller类,则Controlle类中的方法会默认返回JSON格式数据到页面。

demo如下:

@RequestMapping("/api/testTwo")
@RestController
public class TestTwoController {

    @Autowired
    private SuoGeApiService suoGeApiService;

    @RequestMapping(value = "/test01", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult test01(@Validated @RequestParam(value = "nbxh", required = true) String nbxh) throws Exception {
        FrDto dto = suoGeApiService.getFrDto(nbxh);
        return AjaxResult.success(null, dto);
    }

    @RequestMapping(value = "/test02", method = {RequestMethod.GET, RequestMethod.POST},
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public AjaxResult test02(@RequestParam(value = "nbxh", required = true) String nbxh) throws Exception {
        FrDto dto = suoGeApiService.getFrDto(nbxh);
        return AjaxResult.success(null, dto);
    }

}

上述返回的json格式 如下:

{"status":"success","errorCode":"","msg":"","errors":[],"data":""}

猜你喜欢

转载自blog.csdn.net/HSH205572/article/details/84384096