What I am trying to do is build a simple interceptor that checks whether the user has specified a language attribute in the headers or not. I have configured everything and all is running well but if I submit the request more than one time, I see that the error message got added in the array again and now is showing twice.
This is the code for the interceptor:
public class LanguageInterceptor extends HandlerInterceptorAdapter {
private List errors = new ArrayList();
private BadRequestException badRequestException = new BadRequestException();
private BadRequestExceptionData badRequestExceptionData = new BadRequestExceptionData();
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String LocaleLang = request.getHeader("Accept-Language");
if(null == LocaleLang) {
badRequestException.setStatus(HttpStatus.BAD_REQUEST.value());
badRequestException.setTitle("Illegal request");
errors.add("No language attribute specified in your request!");
badRequestExceptionData.setPageSize(errors);
badRequestException.setErrors(badRequestExceptionData);
ObjectMapper objectMapper = new ObjectMapper();
response.setStatus(HttpStatus.BAD_REQUEST.value());
response.getWriter().write(objectMapper.writeValueAsString(badRequestException));
response.setHeader("Content-Type", "application/json");
return false;
}
return true;
}
}
Example response:
{
"status": 400,
"errors": {
"pageSize": [
"No language specified in your request!",
"No language specified in your request!"
]
},
"title": "Illegal request"
}
Am I doing something wrong or do I have to empty the object when the preHandle function is done? My apologies if this question sounds a bit dull, I am still new to Java and Spring boot.
It looks like LanguageInterceptor
has been instantiated as a singleton. Shift all these three variables inside the method, preHandle
to make them local instead of instance variables.
List errors = new ArrayList();
BadRequestException badRequestException = new BadRequestException();
BadRequestExceptionData badRequestExceptionData = new BadRequestExceptionData();