@Controller和@RestController的区别

@RestController注解 = @ResponseBody + @Controller

@Controller:配合视图解析器InternalResourceViewResolver,返回到指定页面
@RestController:返回json数据
@ResponseBody:将java对象转为json格式的数据
@RequestMapping:指定路由映射

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 * @since 4.0.1
	 */
	@AliasFor(annotation = Controller.class)
	String value() default "";

}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {

	/**
	 * The value may indicate a suggestion for a logical component name,
	 * to be turned into a Spring bean in case of an autodetected component.
	 * @return the suggested component name, if any (or empty String otherwise)
	 */
	@AliasFor(annotation = Component.class)
	String value() default "";

}

@Controller 通常是被使用服务于web 页面的。默认controller方法返回的是一个string 串,表示要展示哪个模板页面或者是要跳转到哪里去。

@Controller
@Api(tags= {"请求404的特殊处理,返回index.html页面"})
public class NotFoundErrorController implements ErrorController{

private static final String ERROR_PATH = "/error"; 
	
	@RequestMapping(value=ERROR_PATH) 
	public ModelAndView handleError(HttpServletRequest request,HttpServletResponse response) {
		if(HttpStatus.NOT_FOUND.value() == response.getStatus()) {
			return new ModelAndView("/index.html");
		}
		return new ModelAndView();
	}
	@Override
	public String getErrorPath() {
		return ERROR_PATH;
	}
}

@RestController 就是专门用在编写API的时候,返回一个JSON或者是XML等等。

@RestController
@RequestMapping("/nvwa-nros/v1/app")
@Api(tags= {"功能App"})
public class AppController {
	
	@Autowired
	private IAppService appService;
	
	/**
	 * 查询所有的应用
	 * @return
	 */
	@GetMapping("/list")
	@ApiOperation(value="查询所有的应用",notes="查询所有的应用")
	public List<App> allApps(){
		List<App> theAllApp = appService.select();
		return theAllApp;
	}
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值