【问题标题】:JAVA JSON Restfull WebService No 'Access-Control-Allow-Origin' header is present on the requested resource [duplicate]JAVA JSON Restful Web服务请求的资源上没有“Access-Control-Allow-Origin”标头[重复]
【发布时间】:2016-08-21 18:13:19
【问题描述】:

我有一个 JAVA RESTful 网络服务,它将返回 JSON 字符串,它是用 Java 编写的。我的问题是当我使用以下 URL 向该 Web 服务发送请求时

http://localhost:8080/WebServiceXYZ/Users/insert

它给了我下面的错误信息

XMLHttpRequest cannot load http://localhost:8080/WebServiceXYZ/Users/insert/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 500.

这是我的代码

package com.lb.jersey;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.json.JSONException;
import org.json.JSONObject;

@Path("/Users")
public class RegistrationService
{
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/insert")
    public String InsertCredentials (String json) throws JSONException
    {
        java.util.Date dt = new java.util.Date();
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(dt);

        String phone = null;
        JSONObject returnJson = new JSONObject();
        try
        {
            JSONObject obj = new JSONObject(json);
            JSONObject result1 = obj.getJSONObject("Credentials");
            phone = result1.getString("phone");
            DBConnection conn = new DBConnection();

            int checkUserID = conn.GetUserIDByPhone(phone);
            if(checkUserID <= 0)
            {
                DBConnection.InsertorUpdateUsers(phone, currentTime);
            }

            int userID = conn.GetUserIDByPhone(phone);
            int otp = (int) Math.round(Math.random()*1000);

            DBConnection.InsertorUpdateCredentials(userID, otp, currentTime);

            JSONObject createObj = new JSONObject();
            createObj.put("phone", phone);
            createObj.put("otp", otp);
            createObj.put("reqDateTime", currentTime);
            returnJson.put("Credentials", createObj);

            System.out.println(returnJson);
        }
        catch (Exception e)
        {
        }
        return returnJson.toString();
    }
}

我的 web.xml 代码

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>WebServiceXYZ</display-name>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>com.lb.jersey</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

我已经阅读了很多文章但没有进展,所以请告诉我,我该如何处理这个问题?

【问题讨论】:

    标签: java json rest cors jax-ws


    【解决方案1】:

    这是假设您使用码头作为您的服务器。希望对你有帮助...

    将以下代码添加到您的 web.xml

    <filter>
    <filter-name>cross-origin</filter-name>
    <filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
    <init-param>
      <param-name>allowedOrigins</param-name>
      <param-value>*</param-value>
    </init-param>
    <init-param>
      <param-name>allowedMethods</param-name>
      <param-value>GET,POST,DELETE,PUT,HEAD</param-value>
    </init-param>
    <init-param>
      <param-name>allowedHeaders</param-name>
      <param-value>origin, content-type, accept</param-value>
    </init-param>
    </filter>
    <filter-mapping>
    <filter-name>cross-origin</filter-name>
    <url-pattern>/*</url-pattern>
    </filter-mapping>
    

    以及 pom.xml 中的以下依赖项

    <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlets</artifactId>
            <version>8.0.0.M0</version>
    </dependency>
    

    配置tomcat的链接是link...这里是另一个link2相应修改:)

    【讨论】:

    • 在我的项目中没有“pom.xml”文件。
    • 您使用的是 maven 项目吗?如果没有,那么您将不会拥有 pom.xml 文件。在这种情况下,最好下载 jar 文件并将其手动添加到您的路径中。这是假设您使用码头作为您的服务器
    • 我没有使用 maven 项目。
    • 我没有使用 maven 项目,抱歉打错了..
    • 你使用jetty作为你的服务器吗?
    【解决方案2】:

    您可以尝试设置 HttpServletResponse 的标头

    import javax.servlet.http.HttpServletResponse;
    
    @Path("/Users")
    public class RegistrationService
    {
    
        @Context
        private HttpServletResponse servletResponse;
    
        private void allowCrossDomainAccess() {
            if (servletResponse != null){
                servletResponse.setHeader("Access-Control-Allow-Origin", "*");
            }
        }
    
        @POST
        @Produces(MediaType.APPLICATION_JSON)
        @Path("/insert")
        public String InsertCredentials (String json) throws JSONException
        {
            allowCrossDomainAccess();
            // your code here
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-25
      • 2015-06-15
      • 2017-02-07
      • 2023-03-16
      • 2014-07-30
      • 2016-01-14
      • 2023-03-15
      • 2018-12-02
      • 2016-03-10
      相关资源
      最近更新 更多