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

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

    欢迎大家关注我的公众号

  • 相关阅读:
    3个常用基于Linux系统命令行WEB网站浏览工具(w3m/Links/Lynx)
    Linux进程关系
    Linux信号基础
    Linux进程基础
    Linux架构
    Linux文本流
    Linux文件管理相关命令
    Linux命令行与命令
    【转载】 input 输入格式化
    【所见即所得】textarea 精确限制字数、行数,中、英、全半角混检 。源码带注释
  • 原文地址:https://www.cnblogs.com/gyjx2016/p/5896138.html
Copyright © 2011-2022 走看看