Reputation: 9827
I've seen some some posts that say a return is needed after the repsonse.sendError in a Servlet Filter, is it needed? If so, why?
public class AuthorizationSecurityFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
boolean isAuth = //call to authenticate request
if (isAuth) {
chain.doFilter(request, response);
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return; //this needed?
}
}
}
Upvotes: 2
Views: 3572
Reputation: 7771
I don't know much about servlets but the return
statement is actually useless and will be removed by the compiler.
The javadoc says "After using this method, the response should be considered to be committed and should not be written to." I guess you are referring to this.
Imagine this snippet:
if( anyErrorCondition(request) ) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
}
// Further processing
In this case, you should definitely use a return
statement after calling sendError
because you want to prevent further processing.
This does not apply to your example which does not process the request after sending the error code but will instead reach the end of the method and return.
Summing up: No, you don't need a return
statement here, as long as you can guarantee that the request will not be processed after calling sendError
.
Upvotes: 7