现在要写一个java的web service, 想做一个在后台一直运行的主线程。
其实有点类似于asp.net中的asax文件的作用,继承System.Web.HttpApplication,然后实现Application_Start方法和Application_End方法,从而启动线程。
请问在java中要怎么实现这个模型?

解决方案 »

  1.   

    下面是一个简单的示例,在jdk6下创建web service服务
    package com.cplatform.webservice;
    import java.util.concurrent.LinkedBlockingQueue;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    import javax.xml.ws.Endpoint;public class TestServer {    
        public static void main(String[] args) throws Exception {        // 创建工作任务队列
            LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(5000);
            // 创建工作线程池
            ThreadPoolExecutor processThreadPool = new ThreadPoolExecutor(2, 5, 2, TimeUnit.SECONDS, workQueue);        // 创建发布
            Endpoint endpoint;
            endpoint = Endpoint.create(new HelloWorldImpl());
                    
            // 设置工作线程池
            endpoint.setExecutor(processThreadPool);
            
            // 在指定URL发布
            endpoint.publish("http://localhost:9999/");        while (true) {
                Thread.sleep(1000);
            }
        }
        
    }package com.cplatform.webservice;import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebResult;
    import javax.jws.WebService;
    import javax.jws.soap.SOAPBinding;
    @WebService(name = "HelloWorld", targetNamespace = "http://www.cplatform.com/webservice")
    @SOAPBinding(style = SOAPBinding.Style.RPC)
    public interface HelloWorld {    
        @WebMethod(operationName = "NewOperation", action = "http://www.cplatform.com/webservice/NewOperation")
        @WebResult(name = "NewOperationResponse", targetNamespace = "http://www.cplatform.com/webservice")
        public String newOperation(@WebParam(name = "NewOperationRequest", targetNamespace = "http://www.cplatform.com/webservice")
        String NewOperationRequest);    @WebMethod(operationName = "sayHello", action = "http://www.cplatform.com/webservice/sayHello")
        @WebResult(name = "sayHelloResponse", targetNamespace = "http://www.cplatform.com/webservice")
        public String sayHello(@WebParam(name = "sayHelloRequest", targetNamespace = "http://www.cplatform.com/webservice")
        String sayHelloRequest);}
    package com.cplatform.webservice;import javax.jws.WebService;
    @WebService(serviceName = "HelloWorld", targetNamespace = "http://www.cplatform.com/webservice", endpointInterface = "com.cplatform.webservice.HelloWorld")
    public class HelloWorldImpl implements HelloWorld {    public String newOperation(String NewOperationRequest) {
            return "newOperation Result";//throw new UnsupportedOperationException();
        }    public String sayHello(String sayHelloRequest) {
            return "sayHello Result";//throw new UnsupportedOperationException();
        }
    }运行testService,然后浏览器访问 http://localhost:9999/?wsdl 看看