webservice服务器与客户端

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/windzzm/article/details/73181851

微信公众号:明之Java
知识星球:https://t.zsxq.com/JEemUnm
码云项目地址:https://gitee.com/mingprogram/livesys
1、实现WebServiceImpl类,注意添加注解 @WebService ,方法添加@WebMethod

package com.zzm.webservice;

/**
 * Created by ming on 2017/6/13.
 */

import com.zzm.db.DBUtil;

import javax.jws.WebMethod;
import javax.jws.WebService;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebService
public class WebServiceImpl {
    @WebMethod

    public String findUserById(int id){
        try {
            String name = null;
            Connection ct = DBUtil.getConn();

            String sql = "select * from users where id="+id;
            PreparedStatement ps = ct.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            //System.out.println();
            while (rs.next()){
                int ids =  rs.getInt("id");
                name = rs.getString("userName");
                System.out.println("MYSQL数据库查出数据->"+id+"->"+name);
            }
            DBUtil.closeConn(rs,ps,ct);
            return "从webservice获取->"+name;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println("【执行】");
        return  null;
    }
}

2、服务器端main方法

package example;
import com.zzm.db.DBUtil;
import com.zzm.webservice.WebServiceImpl;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
import java.sql.*;

/**
 * Created by ming on 2017/6/13.
 */
@WebService()
public class HelloWorld {
  @WebMethod
  public String sayHelloWorldFrom(String from) {
    String result = "Hello, world, from " + from;
    System.out.println(result);
    return result;
  }
  public static void main(String[] argv) {
    /*Object implementor = new HelloWorld ();
    String address = "http://localhost:9000/HelloWorld";
    Endpoint.publish(address, implementor);*/
    WebServiceImpl ws = new WebServiceImpl();
    String address = "http://localhost:9000/webs";
    try {
      Endpoint.publish(address,ws);
      System.out.println("【开启webservice】");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}

3、客户端的实现
IDEA、Myeclipse添加webservice客户端

添加客户端main方法

package example;

import com.zzm.client.WebServiceImpl;
import com.zzm.client.WebServiceImplService;

/**
 * Created by ming on 2017/6/13.
 */
public class HelloWorldClient {
  public static void main(String[] argv) {
      WebServiceImpl service = new WebServiceImplService().getWebServiceImplPort();
      //invoke business method
      String name = service.findUserById(1);
      System.out.println(name);
  }
}

欢迎关注公众号!!
这里写图片描述

猜你喜欢

转载自blog.csdn.net/windzzm/article/details/73181851