如何将http标头添加到soap webservice glassfish

时间:2012-09-12 00:21:23

标签: java web-services soap netbeans glassfish

如何使用netbeans和glassfish将http标头添加到soap webservice?

我的网络服务课程:

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:*”标题

我该怎么做?

1 个答案:

答案 0 :(得分:1)

在互联网上搜索了几个小时,我最终编写了以下代码,以便添加额外的http标头。我正在使用netbeans生成的webservice和内置的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);
    }
}