简体   繁体   中英

Spring3.1 CORS. What does this code mean? I don't understand why the author used 'semi-colon' to that position

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM