webservcie读写cookie

package com.lifesense.webservice;

import java.io.Serializable;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

@Stateless
@WebService(
        name="WebServiceTest",
        targetNamespace="http://www.lifesense.com/webservicetest/",
        serviceName="WebServiceTest",
        portName="WebServiceTest"
)
public class WebServiceTest implements Serializable{
    private static final long serialVersionUID = 1L;

    @Resource 
    private WebServiceContext wsContext; 
   
    @WebMethod(operationName = "sayHello")
    @WebResult(name = "result")
    public String sayHello(@WebParam(name = "name", mode = WebParam.Mode.IN)String name){
       
        MessageContext mc = wsContext.getMessageContext();  
       
        HttpServletResponse response = (HttpServletResponse )(mc.get(MessageContext.SERVLET_RESPONSE));
   
        Cookie cookie = new Cookie("name",name);
   
        response.addCookie(cookie);

       
        return name+",hello!";
       
    }
   
    @WebMethod(operationName = "sayBye")
    @WebResult(name = "result")
    public String sayBye(){
       
        MessageContext mc = wsContext.getMessageContext(); 
       
        HttpServletRequest request = (HttpServletRequest)(mc.get(MessageContext.SERVLET_REQUEST)); 
       
        Cookie[] cookies = request.getCookies();
        String name = null;
        if(cookies!=null)
        {
           for (int i = 0; i < cookies.length; i++)
            {
               Cookie c = cookies[i];    
               if(c.getName().equalsIgnoreCase("name"))
               {
                  System.out.println(c.getValue());
                  name = c.getValue();
               }
              
            }
          }
        return name+",hello!";
       
    }
}

你可能感兴趣的:(cookie)