zoukankan      html  css  js  c++  java
  • 【springBoot】springBoot返回json的一个问题

    首先看下面的代码

    @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

    全文完,感谢您的耐心阅读~

    欢迎大家关注我的公众号

  • 相关阅读:
    PAT A1017 Queueing at Bank [硬核模拟]
    PAT A1105 Spiral Matrix [硬核模拟]
    PAT A1153 Decode Registration Card of PAT [排序模拟]
    PAT A1139 First Contact [图]
    jquery的animate动画
    wordpress建站过程5——footer.php
    wordpress建站过程4——index.php
    wordpress建站过程3——header.php
    HTML中加载flash方法
    轮播图的原理
  • 原文地址:https://www.cnblogs.com/gyjx2016/p/5896138.html
Copyright © 2011-2022 走看看