It sounds like you’re on the right track with a servlet filter, what you probably need to do is wrap the servlet response object with one that detects when a 401 status code has been set and adds your custom header at that time:
HttpServletResponse wrappedResponse = new HttpServletResponseWrapper(response) {
public void setStatus(int code) {
super.setStatus(code);
if(code == 401) handle401();
}
// three similar methods for the other setStatus and the two
// versions of sendError
private void handle401() {
this.addHeader(...);
}
};
filterChain.doFilter(request, wrappedResponse);