webservice伺服器與客戶端
阿新 • • 發佈:2018-11-08
微信公眾號:明之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);
}
}
歡迎關注公眾號!!