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

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

    欢迎大家关注我的公众号

  • 相关阅读:
    springboot +mybatis 使用PageHelper实现分页,并带条件模糊查询
    jQuery设置点击选中样式,onmouseover和onmouseout事件
    Ajax跨域设置
    Java获取文章的上一篇/下一篇
    Python str / bytes / unicode 区别详解
    Python bytes 和 string 相互转换
    Python bytearray/bytes/string区别
    Python eval 与 exec 函数区别
    Python eval 与 exec 函数
    Python set list dict tuple 区别和相互转换
  • 原文地址:https://www.cnblogs.com/gyjx2016/p/5896138.html
Copyright © 2011-2022 走看看