springBoot返回json的一个问题

转自:https://www.cnblogs.com/gyjx2016/p/5896138.html

首先看下面的代码

复制代码
@Controller
@RequestMapping("/users")
public class UserController {
    @RequestMapping(method=RequestMethod.GET)
    public HttpResponse getList(HttpServletRequest req,HttpServletResponse rep){
        String id = req.getSession().getId();
        return new HttpResponse(id);
    }
}
复制代码

在通过ajax访问的时候会出现

javax.servlet.ServletException: Circular view path [users]: would dispatch back to the current handler URL [/users] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

这个异常,它的意思是没有指定视图结果,让你检查一下你的视图配置,在springmvc中我们是使用viewResolver,通过在controller中return的前缀来决定跳转到相应的视图

那么在springBoot怎么解决这个问题?

两个方案:

1、添加@ResponseBody

复制代码
 
 

@Controller@RequestMapping("/users")public class UserController {  @RequestMapping(method=RequestMethod.GET)  @ResponseBody  public HttpResponse getList(HttpServletRequest req,HttpServletResponse rep){      String id = req.getSession().getId();      return new HttpResponse(id);    }}

 
复制代码

2、将@Controller换成@RestController// 标记为:restful

复制代码
@RestController
@RequestMapping("/users")
public class UserController {
    @RequestMapping(method=RequestMethod.GET)
    public HttpResponse getList(HttpServletRequest req,HttpServletResponse rep){
        String id = req.getSession().getId();
        return new HttpResponse(id);
    }
}
复制代码

 

Controller源码类

org.springframework.stereotype.Controller

RestController源码类

org.springframework.web.bind.annotation.RestController

 

两者区别在于

 

--------------------------------

 

ok

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值