|
If you use Google, Baidu, and other search tools to search for WebService-related knowledge, you can find more than N web pages. Through these web pages, I learned more about WebService. I would like to express my gratitude to those who are selfless and dedicated.
Examples of WebService on the Internet are mostly simple examples of Hello world, which are so simple that you have no idea about WebService. With the basic knowledge of WebService, I have been thinking about what kind of simple and practical stuff can be made into WebService to show its features. Today, we finally come up with a counter that uses a lot of counters and has relatively independent functions. WebService can be made into different systems once and for all (whether JSP or ASP, This is a prominent advantage of WebService) different applications save on such encoding, so you don't need to write counters any more. You just need to use it.
Now let's get started. This tutorial describes how to build a WebService environment and deploy a service, and then describes how to develop a counter.
Running diagram:
Ii. Basic work
1. Development Environment
I use axis as the Web service engine. It is an open source web service engine of Apache. It is currently one of the most mature open-source Web service engines. The following describes how to use axis to build a web service environment.
① Install the Tomcat 5.5 Application Server (5.0 can also be installed, but I have been using );
② Extract the axis package after the download (http://ws.apache.org/Axis), copy the axis directory in the package to the webapps directory under the Tomcat directory;
③ Copy the class files under the axis/WEB-INF/lib directory to the common/lib directory under the Tomcat directory;
④ Restart Tomcat and access http: // localhost: 8080/axis/happyaxis. jsp. If you can access tomcat, the installation is successful;
Note that axis has several optional packages, such as email. jar ...., you can find and put it in the common/lib directory under the Tomcat directory. You do not need to use the relevant functions.
In this way, the development environment is ready.
2. How to deploy Web Services
There are three deployment methods: dynamic invocation interface (DiI), stubs, and dynamic proxy. Here we will introduce the simple method and the method I use: DiI.
In the DiI mode, write the Java file of the service (assuming the name is helloworld. java), then copy it (note that it is the source file) to the webapps/axis directory, and change the suffix to JWS (the file name is helloworld. JWS), and then access http: // localhost: 8080/axis/helloworld. JWS? WSDL: The page displays the WSDL automatically generated by axis, so that a Web Service is deployed. Is it very simple.
My counter service is deployed in this way. In the following article, I will only deploy the counter service. You don't have to say: how to deploy, I won't. It was about to be beaten in ancient times. So I think it is also a good thing to learn only four books and five classics in ancient times. Now, I want to learn so many things that I can't learn for half a day.
Iii. Preparation of the counter service
The counter is easy to understand. My counters are also simple. They have the following functions and features: they provide four types of counters (total number, monthly, weekly, and daily). Considering that web services serve multiple applications, this counter also supports multiple users, and uses XML files to record data.
The record file name is D: \ counter. xml. Note that this file is hard-coded in the service. If you modify the name, modify it in the service program. The file content format is as follows:
<? XML version = "1.0" encoding = "UTF-8"?>
<Counter>
<Item>
<Name> wallimn </Name>
& Lt; password & gt; 123 & lt;/password & gt;
<DC> 59 </DC>
<WC> 59 </WC>
<MC> 59 </MC>
<TC> 59 </TC>
<RT> 16:01:29 </RT>
</Item>
<Counter>
It is a counter service, but it is no different from writing common Java applications. My counter code is relatively simple, so I will not introduce it too much. I will paste it below and there will be a small amount of comments in the source code. I believe you can understand it without reading comments. The Service has only one interface: Counter (string name, string password), which can be used on the client later. I used the dom4j parsing XML package with the program. To debug the XML package, prepare the jar package. For the deployment method, refer to the preceding section.
Import java. Io. file;
Import java. Io. filewriter;
Import java. Io. ioexception;
Import java. Text. dateformat;
Import java. Text. parseexception;
Import java. util. calendar;
Import java. util. date;
Import java. util. iterator;
Import org. dom4j. Document;
Import org. dom4j. extends entexception;
Import org. dom4j. element;
Import org. dom4j. Io. saxreader;
Import org. dom4j. Io. xmlwriter;
/**
* Function: Provides the WebService of the counter service, which can be used by multiple users. <Br/>
* @ Version: V1.0
* @ Author: Wang Li Meng (Email: wallimn@sohu.com QQ: 54871876)
* @ Date: 04:32:45
*/
Public class wscounterbywallimn {
// Counter document. Note the name path.
Private final string filen = "D:/counter. xml ";
Private Final Static dateformat dateformater = dateformat. getdatetimeinstance ();
// Value returned when an error occurs
Private Final Static string errorinfo = "-1;-1;-1;-1 ";
Public wscounterbywallimn (){}
/**
* Function: Open the counter document. <br/>
* Encoding: Wang Li Meng time: 04:44:29 <br/>
*/
Private document opendocument (){
Document Doc = NULL;
Saxreader reader = new saxreader ();
Try {
File xmlfile = new file (filen );
Doc = reader. Read (xmlfile );
Xmlfile = NULL;
}
Catch (incluentexception e ){
E. printstacktrace ();
}
Return Doc;
}
/**
* Function: obtain the details of the counter with the specified name, and set the counter to add 1. <Br/>
* Encoding: Wang Li Meng time: 04:49:57 <br/>
*/
Private synchronized string countertick (string name, string password ){
Document Doc = opendocument ();
Date currdt = new java. util. Date ();
// MC: month counter (monthly counter); DC: day counter (daily counter );
// TC: Total counter (total counter); WC: Week counter (weekly counter );
// RT: registe time registration time
String MC = "-1", Dc = "-1", Tc = "-1", WC = "-1", rT = "-1 ";
Element root = Doc. getrootelement ();
Element selitem = NULL, item = NULL;
For (iterator it = root. elementiterator ("item"); it. hasnext ();){
Item = (element) it. Next ();
If (name. Equals (item. element ("name"). gettext ())){
Selitem = item;
String Pwd = item. elementtext ("password ");
If (! Password. Equals (PWD )){
Return errorinfo; // The password is incorrect.
}
MC = item. element ("MC"). gettext ();
Dc = item. element ("DC"). gettext ();
TC = item. element ("Tc"). gettext ();
WC = item. element ("WC"). gettext ();
RT = item. element ("RT"). gettext ();
Break;
}
}
// If selitem is empty, there is no counter with a name. Add one.
If (selitem = NULL ){
// System. Out. println ("No counter with this name found:" + name );
RT = dateformater. Format (currdt );
Selitem = Doc. getrootelement (). addelement ("item ");
Selitem. addelement ("name"). settext (name );
Selitem. addelement ("Tc"). settext ("0 ");
Selitem. addelement ("MC"). settext ("0 ");
Selitem. addelement ("WC"). settext ("0 ");
Selitem. addelement ("DC"). settext ("0 ");
Selitem. addelement ("RT"). settext (RT );
Selitem. addelement ("password"). settext (password );
MC = "0 ";
WC = "0 ";
Dc = "0 ";
TC = "0 ";
}
// Process the counter plus one operation.
Calendar currcr = calendar. getinstance ();
// The total number is always increased by 1.
TC = string. valueof (integer. parseint (TC) + 1 );
Selitem. element ("Tc"). settext (TC );
Date lastdt = NULL;
Try {
Lastdt = dateformater. parse (RT );
}
Catch (parseexception e ){
Lastdt = new java. util. Date ();
}
Calendar lastcr = calendar. getinstance ();
Lastcr. settime (lastdt );
Currcr. settime (currdt );
// System. Out. println ("last registration time:" + dateformater. Format (lastdt ));
// System. Out. println ("this registration time:" + dateformater. Format (currdt ));
If (lastcr. Get (calendar. Year) = currcr. Get (calendar. Year )){
// The same month, the monthly count plus 1
If (lastcr. Get (calendar. month) = currcr. Get (calendar. month )){
MC = string. valueof (integer. parseint (MC) + 1 );
}
Else {
MC = "1 ";
}
// The day is the same, and the day count plus 1
If (lastcr. Get (calendar. day_of_year) = currcr. Get (calendar. day_of_year ))
Dc = string. valueof (integer. parseint (DC) + 1 );
Else
Dc = "1 ";
If (lastcr. Get (calendar. week_of_year) = currcr. Get (calendar. week_of_year ))
WC = string. valueof (integer. parseint (WC) + 1 );
Else
WC = "1 ";
}
Else {// If the year is different, the monthly and weekly counters are certainly different.
MC = "1"; DC = "1"; WC = "1 ";
}
Selitem. element ("MC"). settext (MC );
Selitem. element ("WC"). settext (WC );
Selitem. element ("DC"). settext (DC );
// Registration record time
Selitem. element ("RT"). settext (dateformater. Format (currdt ));
Try {
Xmlwriter XW = new xmlwriter (New filewriter (filen ));
XW. Write (DOC );
XW. Close ();
}
Catch (ioexception e ){
E. printstacktrace ();
}
Return TC + ";" + MC + ";" + WC + ";" + DC;
}
/**
* Function: the interface exposed by the service, that is, the specified name and password, returns the specified count, and Adds 1 to the counter. <Br/>
* Encoding: Wang Li Meng time: 10:05:22 <br/>
*/
Public String counter (string name, string password ){
If (Password = NULL | Name = NULL) return errorinfo;
Return countertick (name, password );
}
}
4. Client writing
The client is a page. To make it clear, I first write a class that calls Web Service. The content of the class is as follows:
Package com. wallimn. WebService; // The package name.
Import org. Apache. axis. Client. call;
Import org. Apache. axis. Client. Service;
Public class counterserviceclient {
Private string counterarr [];
Public Boolean getcounter (string countername, string password ){
Boolean res = false;
Try {
String endpoint = "http: // localhost: 8080/axis/wscounterbywallimn. JWS"; // note that it must match your development environment.
Service = new service ();
Call call = (CALL) service. createcall ();
Call. settargetendpointaddress (New java.net. URL (endpoint ));
Call. setoperationname ("counter ");
// Enter the name of the method you want to call
String counter = (string) Call. Invoke (new object [] {countername, password });
Counterarr = counter. Split (";");
Res = (counterarr! = NULL & counterarr. Length = 4 );
}
Catch (exception e ){
}
Return res;
}
Public String getdc (){
Return counterarr [3];
}
Public String getmc (){
Return counterarr [1];
}
Public String gettc (){
Return counterarr [0];
}
Public String getwc (){
Return counterarr [2];
}
}
It's easy to go to the page (test. jsp). I also paste it below:
<% @ Page Language = "Java" Import = "com. wallimn. WebService. counterserviceclient" pageencoding = "gb18030" %>
<%
Counterserviceclient client = new counterserviceclient ();
Client. getcounter ("hello", "123 ");
%>
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Title> counter test page </title>
<Meta http-equiv = "Pragma" content = "no-Cache">
<Meta http-equiv = "cache-control" content = "no-Cache">
<Meta http-equiv = "expires" content = "0">
<Meta http-equiv = "keywords" content = "wallimn, counter, WebService">
<Meta http-equiv = "Description" content = "counter usage example">
</Head>
<Body>
<H2 align = "center"> counter details </H2>
<HR/>
Total access volume: <% = client. gettc () %> <br/>
Traffic Volume today: <% = client. getdc () %> <br/>
Visits this week: <% = client. getwc () %> <br/>
Traffic Volume this month: <% = client. getmc () %> <br/>
<HR/>
<P> welcome to the discussion <br/> blog: http://blog.csdn.net/wallimn <br/> Email: wallimn@sohu.com </P>
</Body>
</Html>
V. Conclusion
So far, all the programs developed and used by a complete counter web service have been completed. Deploy the above classes and pages to any context and open test. jsp in a browser to view the results.
Welcome to my blog (http://blob.csdn.net/wallimn) message or e-mail (wallimn@sohu.com) exchange. |