轉自: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