Spring Rest Controller not getting called after Pre Handle Method executed

huangapple go评论74阅读模式
英文:

Spring Rest Controller not getting called after Pre Handle Method executed

问题

我在Spring Boot应用程序中添加了一个拦截器,在拦截器中执行了一些验证操作。

在这里,我面临的问题是,即使验证成功并且从PreHandle方法返回了true,我的控制器方法也没有被调用。

拦截器配置如下:

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Autowired
    AuthInterceptor authInterceptor;

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

拦截器的preHandle方法如下:

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

以下是控制器代码:

@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());
}

请问有人能够帮我指出我做错了什么?为什么即使返回true,我的控制器方法也没有被调用。

谢谢,

英文:

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(&quot;access_token&quot;);

    if(StringUtils.isEmpty(oAuthToken)) {

       throw new UnauthorizedUserException();

    }

    Header header = new BasicHeader(&quot;cookie&quot;,&quot;access_token=&quot;+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(&quot;/generateForm&quot;)public ResponseEntity&lt;?&gt; generateForm(@Valid @RequestBody Form form) throws BaseException {

logger.debug(&quot;______Inside Controller______&quot;);

ByteArrayOutputStream output = null;

ResponseDto resp = validateRequest(form15GHReq);

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

 try {
  output =      formService.genereateForm15GHPDFByteArray(form15GHReq);
 } catch (Exception e) {
  logger.error(&quot;EXception occure:{}&quot;, e.getMessage());
  resp = new ResponseDto();
  resp.setResponseCode(&quot;ERROR&quot;);
 resp.setResponseMsg(e.getMessage());
 return  ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON).body(resp);
 } 
 logger.debug(&quot;_______Exit    Controller______&quot;);
  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,

答案1

得分: 0

由于您重写了preHandle方法,为了将请求传递给控制器,您需要调用preHandle方法的超类实现,如下所示:

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

希望这能解决您的问题 Spring Rest Controller not getting called after Pre Handle Method executed

英文:

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(&quot;access_token&quot;);

   if(StringUtils.isEmpty(oAuthToken)) {

      throw new UnauthorizedUserException();

   }

    Header header = new BasicHeader(&quot;cookie&quot;,&quot;access_token=&quot;+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 Spring Rest Controller not getting called after Pre Handle Method executed

答案2

得分: 0

抱歉,代码本身没有问题。问题出在请求上。JSON请求被传递为纯文本。这导致了415错误。这就是在尝试调用控制器时失败的原因。

感谢所有提供有价值意见的人。

英文:

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.

huangapple
  • 本文由 发表于 2020年4月4日 15:56:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/61025238.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定