英文:
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("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,
答案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);
}
}
希望这能解决您的问题
英文:
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
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论