简体   繁体   English

Spring3.1 CORS。 此代码是什么意思? 我不明白为什么作者使用“分号”

[英]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. 我一直在寻找在spring3.1上启用CORS的解决方案,几乎每个人都使用如下相同的代码。

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 我从https://gist.github.com/kdonald/2232095看到了这段代码

Do you see that 'semi-colon' at the end of the if statement's condition? 您是否在if语句的条件末尾看到“分号”? 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. 这段代码看起来像典型的if语句,但由于使用了“分号”,因此它以一种完全怪异的方式运行。

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. 分号将结束if语句,使其成为空的if语句。 This syntax is allowed since you can write braceless if statements. 允许使用此语法,因为您可以编写无括号的if语句。

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. 这可能是作者的错字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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