I am using @RestController to provide a REST service. But I need to set Access-Control-Allow-Origin in the response header. How would I do this?
My RestController:
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class restController {
@RequestMapping("/some")
public Response some(@RequestParam(value="body") String user) {
return new Response(user);
}
}
My Response:
public class Response {
long id;
String user;
public Response(String user) {
this.id = 7;
this.user = user;
}
}
@RestController works very well but how can I modify it or the response to set Access-Control-Allow-Origin?
Try this code:
@CrossOrigin(origins = "*")
@RequestMapping("/some")
public Response some(@RequestParam(value="body") String user) {
return new Response(user);
}
or this
@RequestMapping("/some")
public Response some(@RequestParam(value="body") String user,HttpServletResponse
response) {
response.addHeader("Access-Control-Allow-Origin", "*");
return new Response(user);
}