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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章