Determines whether two URLs share the same origin according to the Same-Origin Policy. Two URLs are considered to have the same origin if they have the same protocol (scheme), host, and port. The method handles default ports correctly by using the URL's default port when the explicit port is -1
(final URL originUrl, final URL newUrl)
| 1502 | * @return {@code true} if both URLs have the same host and effective port; {@code false} otherwise |
| 1503 | */ |
| 1504 | public static boolean isSameOrigin(final URL originUrl, final URL newUrl) { |
| 1505 | if (!originUrl.getProtocol().equals(newUrl.getProtocol())) { |
| 1506 | return false; |
| 1507 | } |
| 1508 | |
| 1509 | if (!originUrl.getHost().equalsIgnoreCase(newUrl.getHost())) { |
| 1510 | return false; |
| 1511 | } |
| 1512 | |
| 1513 | int originPort = originUrl.getPort(); |
| 1514 | if (originPort == -1) { |
| 1515 | originPort = originUrl.getDefaultPort(); |
| 1516 | } |
| 1517 | int newPort = newUrl.getPort(); |
| 1518 | if (newPort == -1) { |
| 1519 | newPort = newUrl.getDefaultPort(); |
| 1520 | } |
| 1521 | return originPort == newPort; |
| 1522 | } |
| 1523 | } |