0

I was looking for a solution to enable CORS on spring3.1 and almost everybody uses the same code like below.

public class CorsFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");        
    if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())); {
        // CORS "pre-flight" request
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "Authorization");        
        response.addHeader("Access-Control-Max-Age", "1728000");
    }
    filterChain.doFilter(request, response);
}

}

I saw this code from https://gist.github.com/kdonald/2232095

Do you see that 'semi-colon' at the end of the if statement's condition? I was a little bit angry because I was struggling with this code for more than an hour...

This code looks like typical if statement but because of that 'semi-colon' makes it run in a totally weird way.

I still don't understand how does this code work, and if it works, why did the author write the code like this way...

Not only for the 'semi-colon', but also for {} this parenthesis is useless also if that 'semi-colon' is used for any purpose.

Is there anybody who can help me understand this code?

1 Answer 1

1

The semicolon will end the if-statement, making it an empty if statement. This syntax is allowed since you can write braceless if statements.

The standalone braces will then declare an anonymous block, which adds the headers. This block will always execute. So you will always add the headers.

This is probably a typo from the author.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.