Java 阻止跨源请求的Ajax post请求结果:同源策略不允许读取远程资源

Java 阻止跨源请求的Ajax post请求结果:同源策略不允许读取远程资源,java,ajax,spring,Java,Ajax,Spring,好的,这是我第一次在这里发帖,所以如果你看到我需要纠正一些事情,请告诉我 我在尝试使用ajax将数据发布到api时遇到了问题。我使用tomcat8作为我的web服务器。我在控制器中添加了@CrossOrigin注释,这是其他人建议的。我还将localhost:9000作为允许的来源和授权添加到我的servlet.xml的允许标题中,但仍然没有成功 这是我的ajax代码: var my_url = "http://localhost:8088/booking/api/saveTransaction

好的,这是我第一次在这里发帖,所以如果你看到我需要纠正一些事情,请告诉我

我在尝试使用ajax将数据发布到api时遇到了问题。我使用tomcat8作为我的web服务器。我在控制器中添加了@CrossOrigin注释,这是其他人建议的。我还将localhost:9000作为允许的来源和授权添加到我的servlet.xml的允许标题中,但仍然没有成功

这是我的ajax代码:

var my_url = "http://localhost:8088/booking/api/saveTransaction";
var username = "user111";
var password = "userpass111";

              $.ajax({
                  method: "POST",
                  url: my_url,
                  dataType: "json",
                  headers: {
                    'Authorization':'Basic ' + btoa(username+":"+password),
                    'Content-Type':'x-www-form-urlencoded'
                  },
                  data: JSON.stringify(my_data),
                  success: function(data){
                    alert(data);
                  },
                  error: function(xhr, status, error){
                    alert(xhr);
                    alert(status);
                    alert(error);
                  }
              });
在我的控制器中

@CrossOrigin(origins = "http://localhost:9000")
@RequestMapping(value = "/api/saveTransaction", method = RequestMethod.POST)
public ResponseEntity<BiyaheApplicationResult> saveTransaction(Authentication authentication, @RequestBody CompanyTransaction transaction) {

    System.out.println("\n\n");
    System.out.println("START-SAVE-TRANSACTION");
    System.out.println("\n\n");

    BiyaheApplicationResult result = null;

    if(null != transaction) transaction.setTransactionDate(new Date());

    System.out.println("\n\n");
    System.out.println("TEST: SAVE-JSON-TRANSACTION");
    System.out.println("--------------------------------------------");
    System.out.println("[transaction]: " + BiyaheTextFormatter.serializeToJson(transaction));
    System.out.println("--------------------------------------------");
    System.out.println("\n\n");

    String username = authentication.getName();
    User user = this.userService.findUserByUsername(username);
    UserProfileView profile = this.userProfileViewService.getUserProfileViewById(user.getId());

    int companyId = -1;
    int branchId = -1;
    String loadingScheme = null;
    if(null != profile){
        if(BiyaheConstants.JGGC_HQ_COMPANY_ID < profile.getCompanyId()){
            companyId = profile.getCompanyId();
            CompanyConfiguration conf = this.companyConfigurationService.getCompanyConfigurationByCompanyId(companyId);
            loadingScheme = conf.getLoadingScheme();
        }

        if(BiyaheConstants.JGGC_HQ_BRANCH_ID < profile.getBranchId()){
            branchId = profile.getBranchId();
        }
    }

    double currentLoad = 0;

    boolean isSufficientLoad = false;
    if(BiyaheConstants.LOADING_SCHEME_CENTRALIZED.equalsIgnoreCase(loadingScheme)){
        CompanyLoadInfo coLoadInfo = this.companyLoadInfoService.getCompanyLoadInfoByCompanyId(companyId);
        if(null != coLoadInfo) {
            currentLoad = coLoadInfo.getCentralizeLoadAmount();
            isSufficientLoad = coLoadInfo.getCentralizeLoadAmount() > transaction.getTotalAmount();
        }
    }
    else if(BiyaheConstants.LOADING_SCHEME_DISTRIBUTED.equalsIgnoreCase(loadingScheme)){
        BranchLoadInfo branchLoadInfo = this.branchLoadInfoService.getBranchLoadInfoByBranchId(branchId);
        if(null != branchLoadInfo) {
            currentLoad = branchLoadInfo.getBranchLoad();
            isSufficientLoad = branchLoadInfo.getBranchLoad() > transaction.getTotalAmount();
        }
    }

    System.out.println("\n\n");
    System.out.println("SAVE-TRANSACTION");
    System.out.println("--------------------------------------------");
    System.out.println("[username]: " + username);
    System.out.println("[company]: " + profile.getCompanyName());
    System.out.println("[branch]: " + profile.getBranchName());
    System.out.println("[loading-scheme]: " + loadingScheme);
    System.out.println("[current-load-balance]: " + currentLoad);
    System.out.println("[transactionAmount]: " + transaction.getTotalAmount());
    System.out.println("[itemPrice]: " + transaction.getItemPriceTotal());
    System.out.println("[totalMarkup]: " + transaction.getMarkUpTotal());
    System.out.println("[isSufficientLoad]: " + isSufficientLoad);
    System.out.println("--------------------------------------------");
    System.out.println("\n\n");

    if(isSufficientLoad){
        /*
        {
            "transactionDate":null,
            "transactionType":"HOTEL",
            "transactionCode":"SOGO-6969",
            "totalAmount":2500.0,
            "itemPriceTotal":2250.0,
            "markUpTotal":250.0,
            "quantity":1.0,
            "customerName":"Rowena Palami",
            "customerEmail":"weng.palami@gmail.com",
            "customerContact":"(0918) 222-6969",
            "customerAddress":"Room #69 SOGO Hotel, Guadalupe, EDSA, MM"
        }
        * */

        String generatedReservationCode = null;
        do {
            generatedReservationCode = this.biyaheTransactionService.generateTransactionCode(10);
        }
        while(this.biyaheFlightSalesService.checkReservationCodes(generatedReservationCode));

        BiyaheSales sale = transaction.toBiyaheSales();
        sale.setReservationCode(generatedReservationCode);

        sale.setTransactionDate(new Date());
        sale.setAgent(user);

        System.out.println("\n\n");
        System.out.println("API :: SAVE-TRANSACTION");
        System.out.println("------------------------------------------------");
        System.out.println(sale.toString());
        System.out.println("------------------------------------------------");
        System.out.println("\n\n");

        this.biyaheFlightSalesService.addUpdateBiyaheFlightSales(sale);

        result = new BiyaheApplicationResult(SUCCESS_CODE_TRANSACTION_SAVE, SUCCESS_DISPLAY_TRANSACTION_SAVE);
        return new ResponseEntity(BiyaheTextFormatter.serializeToJson(result), HttpStatus.OK);
    }
    else {
        result = new BiyaheApplicationResult("ERROR", null, ERROR_CODE_INSUFFICIENT_BALANCE, ERROR_DISPLAY_INSUFFICIENT_BALANCE);
        return new ResponseEntity(BiyaheTextFormatter.serializeToJson(result), HttpStatus.NOT_ACCEPTABLE);
    }
}
@交叉原点(原点=”http://localhost:9000")
@RequestMapping(value=“/api/saveTransaction”,method=RequestMethod.POST)
public ResponseEntity saveTransaction(身份验证,@RequestBody CompanyTransaction事务){
System.out.println(“\n\n”);
System.out.println(“启动保存事务”);
System.out.println(“\n\n”);
BiyaheApplicationResult=null;
if(null!=事务)transaction.setTransactionDate(new Date());
System.out.println(“\n\n”);
System.out.println(“测试:SAVE-JSON-TRANSACTION”);
System.out.println(“--------------------------------------------------”);
System.out.println(“[transaction]:”+BiyaheTextFormatter.serializeToJson(transaction));
System.out.println(“--------------------------------------------------”);
System.out.println(“\n\n”);
字符串username=authentication.getName();
User User=this.userService.findUserByUsername(用户名);
UserProfileView profile=this.userProfileViewService.getUserProfileViewById(user.getId());
int companyId=-1;
int branchId=-1;
字符串加载模式=null;
if(null!=配置文件){
if(BiyaheConstants.JGGC_HQ_COMPANY_IDtransaction.getTotalAmount();
}
}
else if(BiyaheConstants.加载方案\分布式均衡信号方案(加载方案)){
BranchLoadInfo BranchLoadInfo=this.branchLoadInfoService.getbranchloadinfobybranchhid(branchhid);
如果(null!=branchLoadInfo){
currentLoad=branchLoadInfo.getBranchLoad();
isSufficientLoad=branchLoadInfo.getBranchLoad()>transaction.getTotalAmount();
}
}
System.out.println(“\n\n”);
System.out.println(“保存事务”);
System.out.println(“--------------------------------------------------”);
System.out.println(“[用户名]:”+用户名);
System.out.println(“[company]:”+profile.getCompanyName());
System.out.println(“[branch]:”+profile.getBranchName());
System.out.println(“[加载方案]:”+加载方案);
System.out.println(“[当前负载平衡]:”+当前负载);
System.out.println(“[TransactionMount]:”+transaction.getTotalAmount());
System.out.println(“[itemPrice]:”+transaction.getItemPriceTotal());
System.out.println(“[totalMarkup]:”+transaction.getMarkUpTotal());
System.out.println(“[isSufficientLoad]:”+isSufficientLoad);
System.out.println(“--------------------------------------------------”);
System.out.println(“\n\n”);
如果(isSufficientLoad){
/*
{
“transactionDate”:空,
“交易类型”:“酒店”,
“交易代码”:“SOGO-6969”,
“总金额”:2500.0,
“itemPriceTotal”:2250.0,
“markUpTotal”:250.0,
“数量”:1.0,
“客户名称”:“Rowena Palami”,
“客户邮件”:“翁。palami@gmail.com",
“客户联系人”:(0918)222-6969“,
“客户地址”:“MM南非瓜达卢佩索戈酒店69号房间”
}
* */
字符串generatedReservationCode=null;
做{
generatedReservationCode=this.biyaheTransactionService.generateTransactionCode(10);
}
while(this.biyaheFlightSalesService.checkReservationCodes(generatedReservationCode));
BiyaheSales sale=transaction.toBiyaheSales();
sale.setReservationCode(generatedReservationCode);
sale.setTransactionDate(新日期());
销售代理(用户);
System.out.println(“\n\n”);
System.out.println(“API::SAVE-TRANSACTION”);
System.out.println(“------------------------------------------------------------”);
System.out.println(sale.toString());
System.out.println(“------------------------------------------------------------”);
System.out.println(“\n\n”);
this.biyaheFlightSalesService.addUpdateBiyaheFlightSales(sale);
结果=新BIYAHEAPPLICATION结果(成功\代码\事务\保存,成功\显示\事务\保存);
返回新的ResponseEntity(BiyaheTextFormatter.serializeToJson(result),HttpStatus.OK);
}
否则{
结果=新的BIYAHEAPPLICATION结果(“错误”,null,错误代码,不足平衡,错误显示,不足平衡);
返回新的ResponseEntity(BiyaheTextFormatter.serializeToJson(结果),HttpStatus.NOT_可接受);
}
}
在我的Servlet上下文中

<mvc:annotation-driven />

<mvc:cors>
    <mvc:mapping path="/api/**"
                 allowed-origins="http://localhost:9000/"
                 allowed-methods="POST, GET, PUT, OPTIONS, DELETE"
                 allowed-headers="X-Auth-Token, Content-Type, Authorization"
                 exposed-headers="custom-header1, custom-header2"
                 allow-credentials="false"
                 max-age="4800" />

    <mvc:mapping path="/**"
                 allowed-origins="http://localhost:9000/"
                 allowed-methods="POST, GET, PUT, OPTIONS, DELETE"
                 allowed-headers="X-Auth-Token, Content-Type, Authorization"
                 exposed-headers="custom-header1, custom-header2"
                 allow-credentials="false"
                 max-age="4800" />
</mvc:cors>

在我的web控制台中,我收到->“跨源请求被阻止:同一源策略不允许在读取远程资源。(原因:CORS标头的Acce