[英]How to implement CORS in Java RESTful webservices?
我是Java RESTful Web服務的新手。
這是我的Java代碼:
@Path("ConversionService")
public class FeetToInchAndInchToFeetConversionService {
@GET
@Path("/InchToFeet/{i}")
@Produces(MediaType.TEXT_XML)
public String convertInchToFeet(@PathParam("i") int i) {
int inch=i;
double feet = 0;
feet =(double) inch/12;
return "<InchToFeetService>"
+ "<Inch>" + inch + "</Inch>"
+ "<Feet>" + feet + "</Feet>"
+ "</InchToFeetService>";
}
我能夠運行該服務,並且可以看到輸出。
在這里,我需要在服務中實現CORS的幫助,能否請您告訴我如何在Java代碼中編寫CORS?
我們需要在單獨的類中編寫jersy過濾器,還是有可能在我的Java代碼中直接包含“ Access-Control-Allow-Origin”,“ *”。
您只需添加作為上下文參數即可訪問HttpServletResponse
:
public String convertInchToFeet(@PathParam("i") int i, @Context HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
//...
在jQuery中:
$.ajax({
crossDomain: true,
//...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.