数组不断在拦截器中添加相同的值

Array keeps on adding same value in interceptor

我想做的是构建一个简单的拦截器,检查用户是否在 headers 中指定了语言属性。我已经配置了所有内容并且一切正常 运行 但是如果我多次提交请求,我会看到错误消息再次添加到数组中并且现在显示两次。

这是拦截器的代码:

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

示例响应:

{
    "status": 400,
    "errors": {
        "pageSize": [
            "No language specified in your request!",
            "No language specified in your request!"
        ]
    },
    "title": "Illegal request"
}

我是做错了什么,还是在 preHandle 函数完成后必须清空 object?如果这个问题听起来有点乏味,我深表歉意,我对 Java 和 Spring 还是个新手。

LanguageInterceptor是单例bean,errors List 会在每次请求时保持状态。

您可以通过在方法中声明列表来解决这个问题。

此外,我建议您对例外情况也这样做。

看起来 LanguageInterceptor 已经 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();