首先看下面的代码

@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

两者区别在于

【springBoot】springBoot返回json的一个问题-LMLPHP

--------------------------------

【springBoot】springBoot返回json的一个问题-LMLPHP

ok

05-08 15:19