@Controller与@RestController的区别【转载】

@controller 只是使用这个注解类,那么只是说明这个类可以被spring扫到并加入到bean中,这个时候,类内部的方法返回String类目参数,会进行页面的跳转,直接跳转到String页面

@Controller  
@RequestMapping("/user2")  
public class UserController2 {  
//使用了@controller注解,这种可以放在页面跳转上  
    @RequestMapping(value="/hello")  
    public String hello(HttpServletRequest request,Model model) {  
        return "hello";  
    }  
}  

如果要在这个类中进行一些restAPI或者json数据的返回,那么需要在方法上面增加@ResponseBody注解如:下面的会以json数据格式进行返回
如,下面的方法返回hello字符串,说明会跳转到hello.html页面上去

@Controller  
@RequestMapping("/user2")  
public class UserController2 {  
@RequestMapping(value="/getUserLikeName")  
    public @ResponseBody List<UserDo> getUserLikeName(HttpServletRequest request,Model model) {  
        String name = request.getParameter("name");  
        List<UserDo> userDoList = new ArrayList<UserDo>();  
        userDoList = userService.getUserInfoLikeName(name);  
        return userDoList;  
    }  
}  

@RestController

这个注解集合了@Controller和@ResponseBody,也就是所有的方法都会按照json格式返回,如下面的代码不会跳转到hello.html而是在页面直接输出hello字符串,也就是方法上不用加@responseBody也会输出json格式的内容,但这种注解方式,不适合用于页面跳转

@RestController  
@RequestMapping("/user2")  
public class UserController2 {  
//使用了@controller注解,这种可以放在页面跳转上  
    @RequestMapping(value="/hello")  
    public String hello(HttpServletRequest request,Model model) {  
        return "hello";  
    }  
}

转载自: http://blog.csdn.net/uestc_lxp/article/details/53447345

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章