在GWT / Spring MVC中处理SOP - 休息

时间:2014-08-26 12:09:02

标签: java spring spring-mvc tomcat gwt

我正在实现GWT webapp的客户端,我需要与提供REST API的基于Spring的Web服务器进行交互。我通过利用DTO模式通过GET和POST进行通信。当我在同一个Tomcat实例上部署GWT客户端和Spring服务器时,一切正常。如果我在两个实例上部署它们,我会得到HTTP状态0,这表示正在应用SOP。

在服务器上,我实现并设置了CORS过滤器:

@Component
public class SimpleCORSFilter implements Filter {

public void doFilter(ServletRequest req, ServletResponse res,
        FilterChain chain) throws IOException, ServletException {

    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods",
            "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
    chain.doFilter(req, res);
}

public void init(FilterConfig filterConfig) {
}

public void destroy() {
}

}

在我放的web.xml中:

<filter>
    <filter-name>simpleCORSFilter</filter-name>
    <filter-class>com.lh.clte.web.util.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>simpleCORSFilter</filter-name>
    <servlet-name>rest</servlet-name>
</filter-mapping>

在GWT方面,我正在以这种方式构建请求:

protected void sendPost(String url, DTO dto,
        RequestCallback callback) {
    RequestBuilder b = new RequestBuilder(RequestBuilder.POST, url);

    String data = stringify(dto);
    b.setHeader("Content-Type", "application/json");
    b.setHeader("Access-Control-Allow-Origin", "*");
    b.setHeader("Access-Control-Allow-Methods",
            "POST, GET, OPTIONS, DELETE");
    b.setHeader("Access-Control-Max-Age", "3600");
    b.setHeader("Access-Control-Allow-Headers", "x-requested-with");

    b.setRequestData(data);

    b.setCallback(callback);
    try {
        b.send();
    } catch (RequestException e) {
        e.printStackTrace();
    }
}

public native String stringify(JavaScriptObject jso) /*-{
    return JSON.stringify(jso);
}-*/;

鉴于这一切,我可以调整应用程序以应对SOP并允许在不同服务器上部署的最佳方法是什么?感谢。

1 个答案:

答案 0 :(得分:0)

设置适当的标题服务器和客户端修复了问题:

服务器(CORS过滤器):

    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods",
            "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers",
            "X-Requested-With,Content-Type");

GWT请求构建:

    b.setHeader("Content-Type", "application/json");