一、解决方法
A . 编写一个监听器,在监听器中发布服务
二、案例一
- 方法A:编写一个监听器,在监听器中发布服务
1. 编写服务接口
package com.shyroke.service;import javax.jws.WebParam;import javax.jws.WebResult;import javax.jws.WebService;@WebServicepublic interface IFirst { @WebResult(name = "addResult") public int add(@WebParam(name = "x") int x, @WebParam(name = "y") int y);}
2. 实现服务接口
package com.shyroke.service;import javax.jws.WebParam;import javax.jws.WebResult;import javax.jws.WebService;@WebService(endpointInterface = "com.shyroke.service.IFirst")public class IFirstImpl implements IFirst { public int add(int x, int y) { return x + y; }}
3. 在监听器中发布
package com.shyroke.listener;import javax.crypto.EncryptedPrivateKeyInfo;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import javax.xml.ws.Endpoint;import com.shyroke.service.IFirstImpl;public class MyListener implements ServletContextListener { public void contextInitialized(ServletContextEvent arg0) { System.out.println("项目初始化。。"); /** * 发布服务 */ Endpoint.publish("http://localhost:3030/web_webService", new IFirstImpl()); System.out.println("发布服务。。。。。。"); } public void contextDestroyed(ServletContextEvent arg0) { System.out.println("项目销毁。。"); }}
4. 编写servlet
package com.shyroke.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class TestServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.print("这是一个servlet"); out.flush(); out.close(); }}
5. web.xml配置监听器和servlet
com.shyroke.listener.MyListener testServlet com.shyroke.servlet.TestServlet testServlet /servlet/TestServlet
6. 结果
-
缺陷
- 通过监听器发布的web服务,web服务的端口和web工程的端口是不能一致的,否则就会报错。