@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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值