简体   繁体   中英

Spring Rest Controller not getting called after Pre Handle Method executed

I have added an interceptor in spring boot application in which i am doing some kind of validation.

Here I am facing the issue that even after validation is successfull and true is returned from PreHandle method, my controller method is not getting invoked.

 @Configuration
    public class InterceptorConfig implements WebMvcConfigurer {

    @Autowired
    AuthInterceptor authInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor);
    }
   }

Interceptor preHandle method is as follows:

@Override

public boolean preHandle(HttpServletRequest request,

                         HttpServletResponse response, Object object) throws Exception {

    String oAuthToken = request.getHeader("access_token");

    if(StringUtils.isEmpty(oAuthToken)) {

       throw new UnauthorizedUserException();

    }

    Header header = new BasicHeader("cookie","access_token="+oAuthToken);

    HttpResponse httpResponse = Utils.sendGetRequest(oAuthValidationUrl,header);

    if(httpResponse.getStatusLine().getStatusCode()!= HttpStatus.SC_OK){

        throw new UnauthorizedUserException();

    }

    return true;

}

Below is the controller code:

@PostMapping("/generateForm")public ResponseEntity<?> generateForm(@Valid @RequestBody Form form) throws BaseException {

logger.debug("______Inside Controller______");

ByteArrayOutputStream output = null;

ResponseDto resp = validateRequest(form15GHReq);

if (resp.getResponseCode().equals("ERROR")) {
 return ResponseEntity.status(HttpStatus.BAD_REQUEST).contentType(MediaType.APPLICATION_JSON).body(resp);
  }

 try {
  output =      formService.genereateForm15GHPDFByteArray(form15GHReq);
 } catch (Exception e) {
  logger.error("EXception occure:{}", e.getMessage());
  resp = new ResponseDto();
  resp.setResponseCode("ERROR");
 resp.setResponseMsg(e.getMessage());
 return  ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON).body(resp);
 } 
 logger.debug("_______Exit    Controller______");
  return  ResponseEntity.status(HttpStatus.OK).contentType(MediaType.APPLICATION_PDF).body(output.toByteArray());
}

Can anybody please help me by pointing out what i am doing wrong. Why my controller method is not getting invoked even after returning true.

Thanks,

Since you override the preHandle method, to pass the request to the controller you have to call the super implementation of the preHandle method like below,

 @Configuration
 public class WebMvcConfig extends WebMvcConfigurationSupport {

 @Autowired
 CustomInterceptor customInterceptor;

 @Override
 public void addInterceptors(InterceptorRegistry registry) {

     registry.addInterceptor(customInterceptor);

 }
}

@Component
public class CustomInterceptor extends HandlerInterceptorAdapter{

 @Override
  public boolean preHandle(HttpServletRequest request,
  HttpServletResponse response, Object object) throws Exception {

  String oAuthToken = request.getHeader("access_token");

   if(StringUtils.isEmpty(oAuthToken)) {

      throw new UnauthorizedUserException();

   }

    Header header = new BasicHeader("cookie","access_token="+oAuthToken);

   HttpResponse httpResponse = 
Utils.sendGetRequest(oAuthValidationUrl,header);

  if(httpResponse.getStatusLine().getStatusCode()!= HttpStatus.SC_OK){

      throw new UnauthorizedUserException();

 }

  return super.preHandle(request, response, object);

 }

}

Hope this fix your problem:)

My Bad. Code was all correct. Issue was with the request. Json request was being passed as Text. It was giving 415 error.That's the reason it was failing when it was trying to invoke controller.

Thanks to all who all provided valuable input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM