0

如何使用 netbeans 和 glassfish 将 http 标头添加到肥皂网络服务?

我的网络服务类:

package com.service;

import com.model.Contact;
import com.model.Phonebook;
import java.util.ArrayList;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;


@WebService(serviceName = "PhonebookService")
public class PhonebookService {

    private Phonebook phonebook = new Phonebook();

    @WebMethod(operationName = "insert")
    public String insert(@WebParam(name = "contact") Contact contact) {

        phonebook.add(contact);
        return contact.getName() + " inserted";

    }

    @WebMethod(operationName = "update")
    public String update(@WebParam(name = "contact") Contact contact) {

        phonebook.update(contact);
        return contact.getName() + " updated";

    }

    @WebMethod(operationName = "remove")
    public String remove(@WebParam(name = "contact") Contact contact) {

        phonebook.remove(contact);
        return contact.getName() + " removed";

    }

    @WebMethod(operationName = "list")
    public ArrayList<Contact> list() {

        return phonebook.list();

    }

}

我想添加“Access-Control-Allow-Origin:*”标题

我该怎么做?

4

1 回答 1

1

在互联网上搜索了几个小时,我最终编写了以下代码,允许添加额外的 http 标头。我将它与 netbeans 生成的 web 服务和内置 glassfish 3 服务器一起使用

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

@WebFilter(urlPatterns = { "/*" })
public class CrossOriginResourceSharingFilter implements Filter {

    public CrossOriginResourceSharingFilter() { }

    @Override
    public void init(FilterConfig fConfig) throws ServletException { }

    @Override
    public void destroy() { }

    @Override
    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-Headers", "Content-Type, Authorization, Accept"
        );
                ((HttpServletResponse)response).addHeader(
                        "Access-Control-Allow-Methods", "GET, POST, OPTIONS"
                );

        chain.doFilter(request, response);
    }
}
于 2012-09-12T04:25:56.150 回答