Tomcat“Access-Control-Allow-Origin”和JavaScript

时间:2014-04-28 13:51:43

标签: javascript http tomcat

我的服务器上的CORS存在很大问题。我的服务器在localhost上的Tomcat上运行。我实现的服务器有几个RestFul资源。 例如:

@Path("user")
public class UserService {
@GET
@Path("/{username}/{password}")
@Produces("text/plain")
public String checkLoginParameter(@PathParam("username") String username, @PathParam("password") String password) {
        String tempUserName = "";
        String tempPassword = "";
        String bool = "";

        EntityManager em = createEntityManager();
        try{
            User user = (User)em.createQuery("SELECT u FROM User u WHERE u.username='"+username+"' AND u.password='"+password+"'").getSingleResult();
            tempUserName = user.getUsername();
            tempPassword = user.getPassword();
        }
        catch(Exception e){}

        if(username.equals(tempUserName) && !username.isEmpty() && password.equals(tempPassword) && !password.isEmpty()){
            bool = "true";
        }
        else{
            bool = "false";
        }
        return bool;
   }      
}

Ressource正在运作。 现在我想从其他网站通过JavaScript访问Ressource。当我尝试这样做时,我收到一条错误消息:

XMLHttpRequest cannot load http://localhost:8080/RSAppStore/user/poc/poc. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

我知道我已经为我的服务器添加了CORS权限。 我是这样做的:

的web.xml:

<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
 <param-name>cors.allowOrigin</param-name>
    <param-value>*</param-value>
</init-param>
<init-param>
 <param-name>cors.supportedMethods</param-name>
    <param-value>GET, POST, HEAD, PUT, DELETE</param-value>
</init-param>
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
    <param-name>cors.exposedHeaders</param-name>
    <param-value>Set-Cookie</param-value>
</init-param>
<init-param>
    <param-name>cors.supportsCredentials</param-name>
    <param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

使用JavaScript访问:

<script type="text/javascript">
$(function(){
  $.ajax({
    type: "GET",
    crossDomain: true,
    url: "http://robosmart-appstore:robosmart@localhost:8080/RSAppStore/user/poc/poc",

    contentType: "text/plain",
    success: function( string ) {

      console.log(string);  


    },
    error:function () {
      console.log("err");
    }
  });
});
</script>

此外,我已经添加了这两个罐子。

cors-filter-1.9.2.jar
java-property-utils-1.9.jar

我在互联网上阅读了很多例子和解释,但似乎没有任何作用,我也不知道自己做错了什么。

1 个答案:

答案 0 :(得分:3)

我只是成功通过tomcat和angular.js传递CORS。

您可能需要配置一些内容:

  1. cors.supportedHeaders 更改为:

    <init-param>
        <param-name>cors.supportedHeaders</param-name>
        <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
    </init-param>
    
  2. 确保您的过滤器位于任何其他过滤器之前。

  3. 尝试将 contentType 更改为:

    contentType: "application/x-www-form-urlencoded; charset=utf-8"
    
  4. 试试吧。