当前位置 博文首页 > iloki的博客:@Controller和@RestController的区别

    iloki的博客:@Controller和@RestController的区别

    作者:[db:作者] 时间:2021-08-25 12:47

    @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;
    	}
    	
    }
    
    cs
    下一篇:没有了