【发布时间】:2015-04-03 20:31:18
【问题描述】:
我使用 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 部署在同一服务器和端口上时 - 一切正常。如何让它在不同的端口上工作?
【问题讨论】:
标签: java angularjs rest cross-browser cors