CORS过滤器不能与Java + angularjs一起使用

时间:2015-02-04 10:44:12

标签: java angularjs rest cross-browser cors

我使用Java作为后端(RESTful服务)和Angularjs作为前端。问题是后端和前端应用程序在不同的端口上,所以我需要使用CORS过滤器。 它看起来像这样:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CORSFilter implements Filter {

    public CORSFilter() {
    }

    public void init(FilterConfig fConfig) throws ServletException {
    }

    public void destroy() {
    }

    public void doFilter(
        ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

        ((HttpServletResponse) response).addHeader("Access-Control-Allow-Origin", "*");
        ((HttpServletResponse) response).addHeader("Access-Control-Allow-Methods", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
        ((HttpServletResponse) response).addHeader("Access-Control-Allow-Headers", "GET, PUT, OPTIONS, X-XSRF-TOKEN");

        chain.doFilter(request, response);
    }
}

的web.xml:

<filter>
    <filter-name>CORSFilter</filter-name>
    <filter-class>com.company.companyserver.CORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

RESTful服务:

@POST
@Path("login")
@Produces("application/json")
public Response login(@Context HttpServletRequest req, UserTable user) {
    req.getSession(true);
    if (req.getUserPrincipal() == null) {
        try {
            req.login(user.getUsername(), user.getPassword());
        } catch (ServletException e) {
            return Response.status(Response.Status.BAD_REQUEST).type("text/plain").entity("Login or Password is incorrect").build();
        }
    } else {
        return Response.status(Response.Status.OK).type("text/plain").entity("You are already logged in").build();
    }
    return Response.status(Response.Status.OK).type("text/plain").entity("Login successfull").build();
}

@GET
@Path("logout")
@Produces("application/json")
public Response logout(@Context HttpServletRequest req) {
    try {
        req.logout();
        req.getSession().invalidate();
    } catch (ServletException e) {
        return Response.status(Response.Status.BAD_REQUEST).type("text/plain").entity("Can not logout").build();
    }
    return Response.status(Response.Status.OK).type("text/plain").entity("Logout successfull").build();
}

前端:

 $http.post(apiUrl + 'usertable/login', {
        username: 'admin',
        password: 'admin'
    });

    $http.get(apiUrl + 'usertable/logout').success(function (a) {
        var o = a;
    });

每次我在RESTful服务中检查getUserPrincipal()时,我都会将其等于null。当我的java和angularjs部署在同一台服务器和端口上时 - 一切正常。如何让它在不同的端口上工作?

2 个答案:

答案 0 :(得分:1)

我在之前的一个java项目中使用过CORS。我在那里使用org.apache.catalina.filters.CorsFilter并且它工作正常。

如果以下代码正常工作,请尝试。

    <filter>
        <filter-name>CorsFilter</filter-name>
        <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
        <init-param>
            <param-name>cors.allowed.origins</param-name>
            <param-value>*</param-value>
        </init-param>
        <init-param>
            <param-name>cors.allowed.methods</param-name>
            <param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE</param-value>
        </init-param>
        <init-param>
            <param-name>cors.allowed.headers</param-name>
            <param-value>Content-Type,X-Requested-With,Accept,Accept-Encoding,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

答案 1 :(得分:1)

首先,你在这里遇到错误:

((HttpServletResponse) response).addHeader("Access-Control-Allow-Methods", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
((HttpServletResponse) response).addHeader("Access-Control-Allow-Headers", "GET, PUT, OPTIONS, X-XSRF-TOKEN");

标题是&#34; Cache-Control,Pragma,Origin,Authorization,Content-Type,X-Requested-With&#34;和方法&#34; GET,PUT,OPTIONS,X-XSRF-TOKEN&#34;。

先试试这个。