Web Service truy xuất cơ sở dữ liệu
Trong bài này, chúng ta sẽ làm 1 ứng dụng web service truy xuất đến cơ sở dữ liệu.
Phần 1: tạo Cơ sở dữ liệu
Tạo Databse tên LogonWS, tạo 1 bảng tên Users với cấu trúc như hình sau
| Column Name | Data Type |
|
userID |
nvarchar(30) |
|
Password |
nvarchar(50) |
Nhập vài mẫu tin để thử.
Tạo 1 DSN với tên LogonWS tham chiếu đến database này.
Phần 2: Tạo Web Service
File->New->Dynamic Web Project, đặt tên cho project là WS_DB

Nhấn Finish
Thêm vào 1 package tên vovanhai.wordpress.com
Thêm vào lớp tên LongonService.java có nội dung như sau:
|
package vovanhai.wordpress.com;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement;
public class LogonService { /** * Đăng nhập hệ thống * @param userName * @param password * @return 1: thành công; 0: sai Password; -1: sai username */ public int Logon(String userName,String password){ Connection con = null; Statement stm = null; ResultSet rs = null; int result = 0; String selectStatement = “select * from Users where userID=’”+userName+“‘”; try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); con = DriverManager.getConnection(“jdbc:odbc:LogonWS”,“sa”,“”); stm = con.createStatement(); rs = stm.executeQuery(selectStatement); if(!rs.next()) result = -1;//sai username else{ String psw=rs.getString(“password”); if(psw.equals(password)){ result= 1; //thành công } else result= 0;//sai password } }catch(Exception ex){ ex.printStackTrace(); } return result; } } |
Kết quả như hình sau khi xem trong Package Explorer

Nhấn phải chuột lên lớp LogonService.java trong project Explorer, chọn New->Others…

Chọn Web Service, nhấn Next. Kết quả như hình

Nhấn Finish để hoàn tất công việc. Eclipse sẽ tựn động cài các thư viện và phát sinh các trong web quản lý của Axis2. Đồng thời eclipse cũng mở cho chúng ta cửa sổ Web Service Exploere như hình, và chúng ta có thể kiểm tra web service của chúng ta trên đó.

Bây giờ chúng ta mở rộng thư mục axis2-web của project trong cửa sổ Project Explorer, tìm đến trang index.jsp, nhấn chuột phải lên trang này, chọn Run As->Run on Server, chọn Tomcat rồi nhấn Finish, kết quả như hình sau


Nhấn chọn Service ta được

Ta có thể xem WSDL file bằng cách nhấn vào link LogonService. Ghi nhớ lại URL này.
http://localhost:8086/WS_DB/services/LogonService?wsdl
Vậy là chúng ta có 1 Web Service truy xuất CSDL.
Bây giờ ta thử phát triển 1 ứng dụng JSP Web Client truy xuất Web Service này, xem ở đây
kaka said
chào anh, trong phần WebContent không có mục axis2-web thì phải làm thế nào?
Anh duc said
Thay oi! Lam sao bao mat webservice tren asp.net dc ha thay?
vovanhai said
Đó là 1 vấn đề, hôm nào rỗi tôi sẽ viết các bài liên quan!
tungnguyen said
chào anh tôi đang thử webservice try xuất với csdl nhung đến bước start server thì báo lỗi sau
Could not publish server configuration for Tomcat v6.0 Server at localhost.
tôi phải làm thế nào?
vovanhai said
Download Tomcat 6.0.18 bản ZIP về, giải nén, thiết lập biến môi trường %TOMCAT_HOME%. TRong Eclipse thiết lập server mới. OK.
tungnguyen said
Cảm ơn anh tôi làm được rồi.
nguyen viet tram said
thầy ơi, em truy xuất đến bước web service rồi mà nó báo lỗi
“‘Staring Tomcat 6.0 Service at localhost’encountered a problem”
Several ports(8005,8080,8009)required……
—
là sao vậy thầy.
Thân.
vovanhai said
Là Tomcat bị lỗi chứ sao. Xem lại Tomcat thử!
Phan Tien Dung said
Thầy ơi! em đã làm như vậy @:”Download Tomcat 6.0.18 bản ZIP về, giải nén, thiết lập biến môi trường %TOMCAT_HOME%. TRong Eclipse thiết lập server mới. OK.”
nhưng mà vẫn bị lỗi:
Could not publish server configuration for Tomcat v6.0 Server at localhost.
Multiple Contexts have a path of “/WebSVNhiPhan”.
Multiple Contexts have a path of “/TongDemo”.
em không biết phải làm thế nào nữa???
botay said
chào anh, trong phần WebContent không có mục axis2-web thì phải làm thế nào?
e cũng thấy ko có. sao giờ?
vovanhai said
Bạn phải cấu hình Axis chứ!
Trong eclipse, vào menu Window->References, chọn Web Services, chọn mục Axis2 References, trong thẻ Axis2 Runtime chọn đến thư mục mà bạn đã giải nén Axis2. Chúc vui!
vovanhai said
Lỗi của em là do em triển khai các project có cùng path.
Em xóa mấy cái thư mục của em trong WebApps sau đó khởi động Tomcat, chạy http://localhost:8080, nếu nó chạy là OK, lỗi không phải của TOmcat.
thai huynh said
chao ban !
cho minh hoi , hien minh dang rat can va rat gap ve van de nay mong ban chi giup
minh su dung : tomcat6, jdk1.6, axis2_1.5,
TOMCAT_HOME, JAVA_HOME, AXIS2_HOME
khi minh tao service thi ko co bao loi gi ca, khi chay file index.jsp thi thay binh thuong, nhung khi click link VALIDATION thi bi loi nay mong ban chi giup
INFO: Reloading this Context has started
[INFO] Deploying module: addressing-1.5 – file:/C:/apache-tomcat-6/webapps/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/WS_DB/WEB-INF/modules/addressing-1.5.mar
[INFO] Deploying module: metadataExchange-1.5 – file:/C:/apache-tomcat-6/webapps/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/WS_DB/WEB-INF/modules/mex-1.5.mar
[INFO] Deploying module: mtompolicy-1.5 – file:/C:/apache-tomcat-6/webapps/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/WS_DB/WEB-INF/modules/mtompolicy-1.5.mar
[INFO] Deploying module: ping-1.5 – file:/C:/apache-tomcat-6/webapps/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/WS_DB/WEB-INF/modules/ping-1.5.mar
[INFO] Deploying module: script-1.5 – file:/C:/apache-tomcat-6/webapps/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/WS_DB/WEB-INF/modules/scripting-1.5.mar
[INFO] Deploying module: soapmonitor-1.5 – file:/C:/apache-tomcat-6/webapps/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/WS_DB/WEB-INF/modules/soapmonitor-1.5.mar
[INFO] Deploying module: addressing – file:/C:/apache-tomcat-6/lib/axis2-WADI.jar
[INFO] Deploying module: addressing – file:/C:/apache-tomcat-6/webapps/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/WS_DB/WEB-INF/lib/axis2-1.4.1.jar
[INFO] Deploying Web service: Login – file:/C:/apache-tomcat-6/webapps/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/WS_DB/WEB-INF/services/Login/
[INFO] Deploying Web service: version.aar – file:/C:/apache-tomcat-6/webapps/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/WS_DB/WEB-INF/services/version.aar
[INFO] Deploying module: addressing – file:/C:/apache-tomcat-6/lib/axis2-WADI.jar
[INFO] Deploying module: addressing – file:/C:/apache-tomcat-6/webapps/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/WS_DB/WEB-INF/lib/axis2-1.4.1.jar
[ERROR]
java.lang.NullPointerException
at org.apache.axis2.clustering.context.DefaultContextManager.updateContexts(DefaultContextManager.java:81)
at org.apache.axis2.clustering.context.Replicator.replicate(Replicator.java:81)
at org.apache.axis2.receivers.AbstractMessageReceiver.replicateState(AbstractMessageReceiver.java:71)
at org.apache.axis2.receivers.AbstractInOutMessageReceiver.invokeBusinessLogic(AbstractInOutMessageReceiver.java:41)
at org.apache.axis2.receivers.AbstractMessageReceiver.receive(AbstractMessageReceiver.java:100)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:176)
at org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:275)
at org.apache.axis2.transport.http.AxisServlet.doPost(AxisServlet.java:133)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:228)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:216)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:634)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:445)
at java.lang.Thread.run(Unknown Source)
null
thai huynh said
theo bai viet cua ban !! neu thoi muon su dung PHP de goi webservice nay(java va axis2) thi goi nhu the nao xin ban chi giup !!
vovanhai said
Chưa làm bằng PHP. Thông cảm nhé!
Bạn nào rành chỗ này mong được chia sẻ. Thanks!
vovanhai said
Làm trên bảng Axis2-1.4 nên cái này chưa gặp. Để thử lại sau vậy.
thai huynh said
chao ban !
minh thu 1 webservice nhu o tren
trong thu muc minh co 2 file class(hay nhieu file class)
vi du:
vovanhai.wordpress.com
Thêm vào lớp tên LongonService.java
Thêm vào lớp tên EntrityBeen.java
trong LongonService.java co mot method
public String getEntrity(){
EntrityBeen be = new EntrityBeen();
be.SetUserName(“123″);
be.SetPassWord(“123″);
return “test been set uaer va pass” ;
}
thi khi tao webservice minh chi chon dc file LongonService.java dung ko ?
nhu vay khi tao client thi minh ko thay duoc file EntrityBeen.java
(client chi co 2 file ApplicationServiceCallbackHandler.java va ApplicationServiceStub.java) dung ra co 2 file nay va mot file EntrityBeen.java nua moi dung !
nhu vay minh fai lam sao !! mong ban chi giup !
Thanks.
vovanhai said
bạn mong muốn gọi dịch vụ getEntrity kể kết quả trả về của bạn là 1 chuỗi “test…”, như vậy thì phương thức đó chỉ chạy ở phía server thì tội gì nó mang đôi tượng về phía client cho bạn!
thai huynh said
minh su dung axis2 , khi ta client tu http://sandbox.adjuggler.com:8901/ui/axis/AdJugglerApplication?wsdl, thi client cua minh get tat cac doi tuong ve client ,
minh tao mot chuong trinh test cho client
<%
try{
String us=request.getParameter("us");
String psw=request.getParameter("psw");
String zone=request.getParameter("zone");
AdJugglerApplicationSoapBindingStub stub = new AdJugglerApplicationSoapBindingStub();
AdJugglerApplicationEndpointProxyProxy px = new AdJugglerApplicationEndpointProxyProxy();
String sesionId = px.login(us,psw,zone);
HTMLBannerBean htnlBeen = new HTMLBannerBean();
htnlBeen = px.getHTMLBanner(sesionId,462499);
htnlBeen.setName("user test");
htnlBeen.setEntityID(1234);
htnlBeen.setSourceCode("”);
htnlBeen.setCustomId(“1234″);
int ins = px.createHTMLBanner(sesionId,htnlBeen);
out.println( sesionId + “”+ ins);
HTMLBannerBean :la doi tuong minh duoc GET ve !!
nen viec goi cac function tren service rat de dang !!
khi minh get url http://sandbox.adjuggler.com:8901/ui/axis/AdJugglerApplication?wsdl ve duoc thi no co day du cac Been(or OBJect)o client ,nhung hien tai thi minh ko lam dc nhu vay !! mong ban chi giup , vi minh dang lam viec nay rap !!
thai huynh said
ban thu dung axis2 get service
http://sandbox.adjuggler.com:8901/ui/axis/AdJugglerApplication?wsdl
thi ban se lay dc tat ca cac Been cua chung ve client
va service cua chung co url la :
−
khong nhung chung ta tao thi lai co
http://localhost:8080/ui/axis/AdJugglerApplication
…..
…
minh muon thay doi url do theo yeu cau
vd : http://xxx.yyyyy.com/….
va get tat ca cac api Been do ve client
mong ban chi giup !
Thanh Tung said
chao cac anh chi !
cho em hoi !! em muon tao mot webserver va webservice co cung mot port thi fai lam nhu the nao ?
vi khi em tao webservice trong eclipse thi no sinh ra mot server rieng , em muon su dung chung mot server chung port de khi start server len thi ca hai cung chay dc !
thanks !!!!
vovanhai said
Cho dù eclipse lên port nào, bạn cứ chạy trên 8080 cho apache Tomcat la OK
Thanh Tung said
khi tao webservice thi trong eclipse co sinh ra mot servers va folder “servers” nay nam trong webapp cua tomcat nen start tomcat thi webservice ko dc start
cach giai quyet la : copy <contex… trong server.xml nay vao server.xml cua tomcat dong thoi copy thu muc WEB-INF ra ngoai webcontent thi chay dc. OK
minh muon hoi class chinh cua webservice la interface cac function trong nay nam trong class khac dc implement interface nay, vay config sao de client goi interface cua webservice thi cac function trong interface thay dc cac function implement chua code ?
mong anh chi chi giup minh !! thanks !
Thanh Tung said
hi anh chi, cam on anh chi da giup do
gio em co mot project su dung STRUST va SPRING ko dung build.xml dang chay tot
gio trong project nay em tao them mot thu muc services
trong do em lam mot class Hello.java
em muon su dung axis2 lam webservice trong project nay,
vay gio em khai bao nhu the nao ?
them nhung gi vay ?
hien tai em chay http://localhost:8080/HelpNet/login.do
sao sao de chay http://localhost:8080/HelpNet/services/Hello?wsdl
mong cac anh chi chi giup gium !thanks
ThanhBinh said
Nếu mình thêm hibernate + spring vào web service axis2 để truy xuất database thì như thế nào. Các bạn có ai có kinh nghiệm về điều này. Hãy post lên đi!
Tuan said
Anh oi. Cho em hoi. Em lam va chay duoc den trang index roi. Nhung khi click vao service thi no bao loi 500 la sao ha anh. Xin anh giup do
Võ Văn Hải said
Lỗi 500 là lỗi internal server.
thanh said
chào thầy!
trước tiên cám ơn thầy vì thời gian qua những bài viết của thầy đã mở đầu trong việc mở rộng trong nâng cao kiến thức ngôn ngữ java của em.
Em đang tim hiểu giao tiếp với n – web services với nhau? rất mong được sự phản hồi sớm của thầy!
Em xin chân thành cảm ơn!
Võ Văn Hải said
Chưa hiểu rõ câu hỏi của bạn. n-ws là sao? nếu như ý bạn nói là các ws giao tiếp với nhau thì điều đó là hiển nhiên không cần hỏi nữa bởi SOAP được thiết kế cho việc này.
Phạm Huy Đức said
Chào anh, em đang làm 1 ứng dụng để lấy 1 ArrayList từ Webservice, mục đích là để hiển thị danh sách khách hàng. Nếu kiểu giá trị trả về là String thì ko sao nhưng nếu để là ArrayList thì không thể Deploy được. Em đang dùng Netbean 7.0.1, Glassfish 3.1 . Thân cảm ơn anh
Tran Chinh said
Chao thay.
trong bai viet thay` de la`:
Tạo 1 DSN với tên LogonWS tham chiếu đến database này.
co nghia~ la sao a?
thay co the cho em xin link tham khao ve viec tao DSN tham chieu toi Database ko a?
Chuc vui!
Võ Văn Hải said
DSN là DataSource Name. bạn tham khảo ở đây Làm việc với SQL server
Võ Văn Hải said
Sao không nhỉ? quan trọng là object của bạn trong ArrayList có implements Serializable không?
Tran Chinh said
bai viet do noi ve SQL Server con` MySQL thi sao a? em da~ ket noi truc tiep voi csdl ma ko tao DSN no van~ truy xuat du~ lieu duoc. Neu lam nhu thi co anh~ huong~ gi ko a? Vi em dang bi loi~ ngay khi tao WS_Client.
Nhung said
Thầy ơi! em có làm bài webservice về java liên kết database access,
thầy có thể hướng dẫn cách làm cho em được không? Bài như thế này.
Ứng dụng websrvice phục vụ tra cứu tên chủ nhân số điện thoại, số cmnd
lưu trong CSDL/Text file. Text file ở đây là access.
lê thị thanh huyền said
Chào thầy cho em hỏi:
Trong eclipse khi em chạy chương trình thì bị lỗi này: Launching playaudio has encountered a problem. Device is unspeccified or unavailable
Võ Văn Hải said
“Trong eclipse khi em chạy chương trình thì bị lỗi này: Launching playaudio has encountered a problem. Device is unspeccified or unavailable”
Em chạy cái gì mà nó ra lỗi này? chứ ws làm sao ra lỗi này được.
Hung said
Thầy có thể ví dụ về return ArrayList được không ạ. cám ơn thầy!
tranchitams3201 said
Thầy ơi,
Em có xây dựng một webservice truy xuất đến cơ sở dữ liệu trong đó có phương thức select(String sql) sẽ trả về đối tượng ResultSet, khi Deploy thì không thành công. Có phải Webservices không hỗ trợ kiểu trả về này không thầy? Có cách nào khắc phục không?
Cảm ơn thầy…!
Võ Văn Hải said
“Em có xây dựng một webservice truy xuất đến cơ sở dữ liệu trong đó có phương thức select(String sql) sẽ trả về đối tượng ResultSet, khi Deploy thì không thành công. Có phải Webservices không hỗ trợ kiểu trả về này không thầy?”
Em phải đọc resultset ra 1 collection nào đó, ví dụ như arraylist rồi trả về.