1

I am trying to consume a rest call in my mvc controller, however every time I do it returns a null body with http status as 302.Also I am using spring boot with spring security to get https.

I've followed code samples from here: http://websystique.com/springmvc/spring-mvc-4-restful-web-services-crud-example-resttemplate/ and Get list of JSON objects with Spring RestTemplate however none of these work

Can someone please point me in the right direction

Thank you,

REST

@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

@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;

    }
 }

***** to fix my issue I modified my code to just do a redirect on select url paths instead of "/*"

 @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;
  }
Community
  • 1
  • 1
Krysta
  • 57
  • 1
  • 11

1 Answers1

0

The http status 302 is usually caused by wrong url setting.

First, make sure that public ResponseEntity<List<Post>> getAllPosts() {} method is called (just print List<Post> result inside it).

If it's called properly and you can get the return value inside public ModelAndView getAll() {}.

The problem should be the directing setting of the public ModelAndView getAll() {} method.

Check if you make something wrong in your web.xml or spring configuration. Pay attention to the configuration which redirects to views and the url mapping of your dispatcher servlet.


If public ResponseEntity<List<Post>> getAllPosts() {} is called but you can't get the return value, then it should be the issues of directing setting of the public ResponseEntity<List<Post>> getAllPosts() {} method.

Check your spring configuration and web.xml for that. The possible cause usually will be the misuse of wildcard in the configuration and web.xml, or just unnoticed wrong mapping.

Duncan
  • 696
  • 1
  • 5
  • 15
  • 1
    I found out that because I was doing a redirect from http to https it was affecting the rest template call. To fix it I modified my code for the `EmbeddedServletContainerFactory` to only redirect for selected urls. When I did that leaving my rest template code as it and it worked. Thanks for the help – Krysta Apr 03 '16 at 23:28