【问题标题】:Rest template giving null body and status 302休息模板给出空正文和状态 302
【发布时间】:2016-07-22 14:06:55
【问题描述】:

我正在尝试在我的 mvc 控制器中使用 rest 调用,但是每次我这样做时它都会返回一个 http 状态为 302 的空主体。此外,我正在使用带有 spring security 的 spring boot 来获取 https。

我从这里关注了代码示例:http://websystique.com/springmvc/spring-mvc-4-restful-web-services-crud-example-resttemplate/Get list of JSON objects with Spring RestTemplate 但是这些都不起作用

谁能指点我正确的方向

谢谢,

休息

@RequestMapping(value = "/api/*")
@RestController
public class PostApiController {

static final Logger logger = LogManager.getLogger(PostApiController.class.getName());
private final PostService postService;


@Inject
public PostApiController(final PostService postService) {
    this.postService = postService;
}

  //-------------------Retrieve All Posts--------------------------------------------------------

@RequestMapping(value = "post", method = RequestMethod.GET)
public ResponseEntity<List<Post>> getAllPosts() {
    List<Post> posts = postService.findAllPosts();
    if(posts.isEmpty()){
        return new ResponseEntity<List<Post>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
    }
    return new ResponseEntity<List<Post>>(posts, HttpStatus.OK);
  }

}

控制器

@Controller
public class PostController {

static final Logger logger = LogManager.getLogger(PostController.class.getName());

 public static final String REST_SERVICE_URI =  "http://localhost:8080/api"; //"http://localhost:8080/api";


private final PostService postService;

@Inject
public PostController(final PostService postService) {
    this.postService = postService;
}



@SuppressWarnings("unchecked")
@RequestMapping(value = "/getAll")
// public String create(@Valid Post post, BindingResult bindingResult, Model
// model) {
public ModelAndView getAll() {
    // if (bindingResult.hasErrors()) {
    // return "mvchome";
    // }


     RestTemplate restTemplate = new RestTemplate();

     ResponseEntity<List<Post>> responseEntity = restTemplate.exchange(REST_SERVICE_URI+"/post",HttpMethod.GET, null, new ParameterizedTypeReference<List<Post>>() {});
    // ResponseEntity<Post[]> responseEntity = restTemplate.getForEntity(REST_SERVICE_URI+"/post", Post[].class);
     List<Post> postsMap = responseEntity.getBody();
     MediaType contentType = responseEntity.getHeaders().getContentType();
     HttpStatus statusCode = responseEntity.getStatusCode();

       // List<LinkedHashMap<String, Object>> postsMap = restTemplate.getForObject(REST_SERVICE_URI+"/post", List.class);
      //  String s= REST_SERVICE_URI+"/post";
       // logger.info(s);
        if(postsMap!=null){
            for(Post map : postsMap){
                logger.info("User : id="+map.getUid());
            }
        }else{
            logger.info("No user exist----------");
        }



    //List<Post> postList = postService.findAllPosts();
    ModelAndView mav = new ModelAndView("mvchome");
    mav.addObject("postsList", postsMap);
    Post newpost = new Post();

    mav.addObject("post", newpost);
    return mav;

    }
 }

***** 解决我的问题我修改了我的代码,只对选择的 url 路径进行重定向,而不是“/*”

 @Bean
  public EmbeddedServletContainerFactory servletContainer() {
    TomcatEmbeddedServletContainerFactory tomcat =
      new TomcatEmbeddedServletContainerFactory() {

        @Override
        protected void postProcessContext(Context context) {
          SecurityConstraint securityConstraint = new SecurityConstraint();
          securityConstraint.setUserConstraint("CONFIDENTIAL");
          SecurityCollection collection = new SecurityCollection();
          //used to be just collection.addPattern("/*"); now I changed it to specify which path I want it to redirect
          collection.addPattern("/mvchome/*");
          collection.addPattern("/home/*");
          securityConstraint.addCollection(collection);
          context.addConstraint(securityConstraint);
        }
      };
    tomcat.addAdditionalTomcatConnectors(createHttpConnector());
    return tomcat;
  }

【问题讨论】:

    标签: spring rest spring-mvc spring-security spring-boot


    【解决方案1】:

    http状态302一般是url设置错误造成的。

    首先,确保调用了public ResponseEntity&lt;List&lt;Post&gt;&gt; getAllPosts() {} 方法(只需在其中打印List&lt;Post&gt; 结果)。

    如果调用正确并且您可以在public ModelAndView getAll() {} 中获取返回值。

    问题应该是public ModelAndView getAll() {}方法的directing设置。

    检查你的 web.xml 或 spring 配置是否有问题。注意重定向到视图的配置和调度程序 servlet 的 url 映射。


    如果public ResponseEntity&lt;List&lt;Post&gt;&gt; getAllPosts() {}被调用,但无法得到返回值,则应该是public ResponseEntity&lt;List&lt;Post&gt;&gt; getAllPosts() {}方法的定向设置问题。

    为此检查您的 spring 配置和 web.xml。可能的原因通常是在配置和 web.xml 中误用了通配符,或者只是没有注意到错误的映射。

    【讨论】:

    • 我发现因为我正在做从 http 到 https 的重定向,它会影响其余模板调用。为了解决这个问题,我修改了EmbeddedServletContainerFactory 的代码,只为选定的网址重定向。当我这样做时,我的其余模板代码保持不变并且它可以工作。感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2019-01-18
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多