@CrossOrigin(origins=”http://localhost:8081″)
only allows request from the specified url(port) visit
Example
Greeting.java
@Data
@AllArgsConstructor
public class Greeting {
private final long id;
private final String content;
public Greeting() {
this.id = -1;
this.content = "";
}
}
GreetingController.java
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@CrossOrigin(origins = "http://localhost:8081")
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(required = false, defaultValue = "World") String name) {
System.out.println("==== get greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
@GetMapping("/greeting-javaconfig")
public Greeting greetingWithJavaconfig(@RequestParam(required = false, defaultValue = "World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
resources/static/good.js
$(document).ready(function() {
$.ajax({
url: "http://localhost:8081/greeting"
}).then(function(data, status, jqxhr) {
$('.greeting-id').append(data.id);
$('.greeting-content').append(data.content);
console.log(jqxhr);
});
});
resources/template/good.html
<!DOCTYPE html>
<html>
<head>
<title>Hello CORS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="good.js"></script>
</head>
<body>
<div>
<p class="greeting-id">The ID is </p>
<p class="greeting-content">The content is </p>
</div>
</body>
</html>
MVCConfig.java
@Configuration
public class MCVConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/good").setViewName("good");
}
}
Start the application on port 8081 and 9000 respectively.
SERVER_PORT=8081 mvn spring-boot:run
SERVER_PORT=9000 mvn spring-boot:run
Then come to browser, try addresses
localhost:8081/good
localhost:9000/good
You can see 8081 can show while 9000 is not showing.