axis2实践(二)Restful入门示例
1. 实例说明
本示例直接参照了RESTful Web Services with Apache Axis2,本示例基本就是沿用的原示例,就是一个对学生信息(包括姓名,年龄,课程)的管理的例子,提供如下Web服务:
1)获取所有学生信息
2)根据姓名获取单个学生信息
3)新增学生信息
4)修改学生信息
另外,本示例在原示例的基础上增加如下功能:
1)增加了与Web系统的集成
2)增加客户端调用代码
2. 创建WebService服务,
整个项目目录结构见下图
1)创建StudentService类,提供了查询,获取,新增,修改学生信息的功能,特别需要注意的是,getStudent()返回学生信息访问的URL.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.TransportInDescription;
import org.apache.axis2.engine.AxisConfiguration; public class StudentService { private Map<String, Student> map = new HashMap<String, Student>();
private String baseURL = null; public StudentService() {
map.put("jimmy", new Student("Jimmy", 20, new String[] { "English", "French", "Russian" }));
} public String[] getStudents() {
int size = map.size();
String[] students = new String[size];
Iterator<String> iterator = map.keySet().iterator();
int i = 0;
while (iterator.hasNext()) {
String studentName = iterator.next();
students[i] = getBaseURL() + "student/" + studentName;
i++;
}
return students;
} public Student getStudent(String name) throws StudentNotFoundException {
Student student = map.get(name);
if (student == null) {
throw new StudentNotFoundException("Details of student " + name + " cannot be found.");
}
return student;
} public String addStudent(Student student) throws StudentAlreadyExistsException {
String name = student.getName();
if (map.get(name) != null) {
throw new StudentAlreadyExistsException("Cannot add details of student " + name
+ ". Details of student " + name + " already exists.");
}
map.put(name, student);
return getBaseURL() + "student/" + name;
} public String updateStudent(Student student) throws StudentNotFoundException {
String name = student.getName();
if (map.get(name) == null) {
throw new StudentNotFoundException("Details of student " + name + " cannot be found.");
}
map.put(name, student);
return getBaseURL() + "student/" + name;
} public void deleteStudent(String name) throws StudentNotFoundException {
if (map.get(name) == null) {
throw new StudentNotFoundException("Details of student " + name + " cannot be found.");
}
map.remove(name);
} // This method attempts to get the Base URI for this service. This will be
// used to construct
// the URIs for the various detsila returned.
private String getBaseURL() {
if (baseURL == null) {
MessageContext messageContext = MessageContext.getCurrentMessageContext();
AxisConfiguration configuration = messageContext.getConfigurationContext()
.getAxisConfiguration();
TransportInDescription inDescription = configuration.getTransportIn("http");
try {
EndpointReference[] eprs = inDescription.getReceiver().getEPRsForService(
messageContext.getAxisService().getName(), null);
baseURL = eprs[0].getAddress();
} catch (AxisFault axisFault) {
}
}
return baseURL;
}
}
2)实体类:Student类
public class Student {
private String name;
private int age;
private String[] subjects;
public Student() {
super();
}
public Student(String name, int age, String[] subjects) {
super();
this.name = name;
this.age = age;
this.subjects = subjects;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String[] getSubjects() {
return subjects;
}
public void setSubjects(String[] subjects) {
this.subjects = subjects;
}
}
3)异常类
StudentAlreadyExistsException类:
public class StudentAlreadyExistsException extends Exception {
private static final long serialVersionUID = 1L;
public StudentAlreadyExistsException(String message) {
super(message);
}
}
StudentNotFoundException类:
public class StudentNotFoundException extends Exception {
private static final long serialVersionUID = 1L;
public StudentNotFoundException(String message) {
super(message);
}
}
4)服务描述文件,创建此文件,并将此文件置于\WEB-INF\services\StudentService\META-INF目录下,如果不存在此目录,则创建
service.xml文件:
<serviceGroup>
<service name="StudentService" scope="application">
<parameter name="ServiceClass">demo.axis2.restful.student.StudentService
</parameter>
<messageReceivers>
<messageReceiver mep="http://www.w3.org/ns/wsdl/in-only"
class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />
<messageReceiver mep="http://www.w3.org/ns/wsdl/in-out"
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />
</messageReceivers>
</service>
</serviceGroup>
3. 利用java2wsdl工具生成WSDL2.0文档
生成命令如下:
java2wsdl -wv 2.0 -o <output directory> -of <output file name> -sn <Name of the service> -cp <classpath uri> -cn <fully qualified name of the service class>
本示例执行的命令如下:
java2wsdl -wv 2.0 -o D:\example\demo.axis2.restful\src\main\webapp\WEB-INF\services\StudentService\META-INF -of StudentService.wsdl -sn StudentService -cp D:\example\demo.axis2.restful\target\classes\ -cn demo.axis2.restful.student.StudentService
命令成功执行完之后,将在指定目录下生成StudentService.wsdl,本示例将StudentService.wsdl文件放在 D:\example\demo.axis2.restful\src\main\webapp\WEB-INF\services \StudentService\META-INF下,也是在maven打包整个项目时,便于将相应的文件构建到指定目录中。
4. 构建Restful服务
1)修改StudentService.wsdl文件如下部分
<wsdl2:binding name="StudentServiceHttpBinding"
interface="tns:ServiceInterface" whttp:methodDefault="POST"
type="http://www.w3.org/ns/wsdl/http">
<wsdl2:fault ref="tns:StudentServiceStudentNotFoundException" />
<wsdl2:fault ref="tns:StudentServiceStudentAlreadyExistsException" />
<wsdl2:operation ref="tns:deleteStudent"
whttp:location="student/{name}" whttp:method="DELETE">
<wsdl2:input />
<wsdl2:output />
<wsdl2:outfault ref="tns:StudentServiceStudentNotFoundException" />
</wsdl2:operation>
<wsdl2:operation ref="tns:updateStudent"
whttp:location="student/{name}" whttp:method="PUT">
<wsdl2:input />
<wsdl2:output />
<wsdl2:outfault ref="tns:StudentServiceStudentNotFoundException" />
</wsdl2:operation>
<wsdl2:operation ref="tns:getStudent" whttp:location="student/{name}"
whttp:method="GET">
<wsdl2:input />
<wsdl2:output />
<wsdl2:outfault ref="tns:StudentServiceStudentNotFoundException" />
</wsdl2:operation>
<wsdl2:operation ref="tns:addStudent" whttp:location="students"
whttp:method="POST">
<wsdl2:input />
<wsdl2:output />
<wsdl2:outfault ref="tns:StudentServiceStudentAlreadyExistsException" />
</wsdl2:operation>
<wsdl2:operation ref="tns:getStudents" whttp:location="students"
whttp:method="GET">
<wsdl2:input />
<wsdl2:output />
</wsdl2:operation>
</wsdl2:binding>
2)修改web.xml,增加如下内容
<servlet>
<servlet-name>AxisServlet</servlet-name>
<display-name>Apache-Axis Servlet</display-name>
<servlet-class>
org.apache.axis2.transport.http.AxisServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>AxisServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
5. maven的项目管理文件pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>demo.axis2.restful</groupId>
<artifactId>demo.axis2.restful</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>demo.axis2.restful Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-kernel</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-jaxws</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-codegen</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-adb</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-transport-local</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>addressing</artifactId>
<version>1.6.2</version>
<type>mar</type>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>2.1.3</version>
<exclusions>
<exclusion>
<groupId>javax.xml.ws</groupId>
<artifactId>jaxws-api</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.xml.messaging.saaj</groupId>
<artifactId>saaj-impl</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.xml.stream.buffer</groupId>
<artifactId>streambuffer</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.xml.stream</groupId>
<artifactId>sjsxp</artifactId>
</exclusion>
<exclusion>
<groupId>org.jvnet.staxex</groupId>
<artifactId>stax-ex</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.org.apache.xml.internal</groupId>
<artifactId>resolver</artifactId>
</exclusion>
<exclusion>
<groupId>org.jvnet</groupId>
<artifactId>mimepull</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>demo.axis2.restful</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
6. 发布程序到tomcat或其他J2EE服务器,
启动服务器,就可在浏览器中通过如下URL http://localhost/demo.axis2.restful/services/StudentService?wsdl ,看到services定义了,说明服务发布成功
7. 客户端访问服务代码,
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient; public class StudentClient {
private static String toEpr = "http://localhost/demo.axis2.restful/services/StudentService"; public static void main(String[] args) throws AxisFault { Options options = new Options();
options.setTo(new EndpointReference(toEpr)); options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE); ServiceClient sender = new ServiceClient();
//sender.engageModule(new QName(Constants.MODULE_ADDRESSING));
sender.setOptions(options);
OMElement result = sender.sendReceive(getPayload());
System.out.println(result); } private static OMElement getPayload() {
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace omNs = fac.createOMNamespace("http://student.restful.axis2.demo", "tns");
OMElement method = fac.createOMElement("addStudent", omNs); OMElement student = fac.createOMElement("addStudent", omNs); OMElement value = fac.createOMElement("name", omNs);
value.addChild(fac.createOMText(value, "eric"));
student.addChild(value); value = fac.createOMElement("age", omNs);
value.addChild(fac.createOMText(value, "30"));
student.addChild(value); value = fac.createOMElement("subjects", omNs);
value.addChild(fac.createOMText(value, "English"));
student.addChild(value); value = fac.createOMElement("subjects", omNs);
value.addChild(fac.createOMText(value, "Russian"));
student.addChild(value); method.addChild(student);
return method;
}
}
另外还可以通过浏览直接访问,例如:http://localhost/demo.axis2.restful/services/StudentService/students 可以查询所有的学生信息,返回的信息如下:
<ns:getStudentsResponse xmlns:ns="http://student.restful.axis2.demo">
<ns:return>
http://Localhost/demo.axis2.restful/services/StudentService/student/jimmy
</ns:return>
</ns:getStudentsResponse>
以上信息是在存在一个姓名为jimmy学生信息的情况下返回的。把 http://Localhost/demo.axis2.restful/services/StudentService/student /jimmy 复制到浏览器的地址栏,就可以查看学生的详细信息了。
axis2实践(二)Restful入门示例的更多相关文章
- Spring(二)之入门示例
任何编程技术,特别是入门示例,通常都是Hello World,在这里我也遵循这个业界公认的原则. 这里我使用的maven项目,大家如果想要演示,建议使用Eclipse(含maven插件)或Idea(含 ...
- Velocity魔法堂系列一:入门示例
一.前言 Velocity作为历史悠久的模板引擎不单单可以替代JSP作为Java Web的服务端网页模板引擎,而且可以作为普通文本的模板引擎来增强服务端程序文本处理能力.而且Velocity被移植到不 ...
- Hessian探究(一)Hessian入门示例
一.hessian的maven信息: [html] view plain copy print? <dependency> <groupId>com.caucho</gr ...
- HTC脚本介绍和入门示例
一.简介 HTC脚本全称是Html Companent即html组件,个人认为它是为了在开发动态HTML中实现代码重用和页面共享目的,主要是把“行为”作为组件封装,可以在很大程度上简化DHTML的开发 ...
- Velocity魔法堂系列一:入门示例(转)
Velocity魔法堂系列一:入门示例 一.前言 Velocity作为历史悠久的模板引擎不单单可以替代JSP作为Java Web的服务端网页模板引擎,而且可以作为普通文本的模板引擎来增强服务端程序文本 ...
- WPF入门教程系列二十三——DataGrid示例(三)
DataGrid的选择模式 默认情况下,DataGrid 的选择模式为“全行选择”,并且可以同时选择多行(如下图所示),我们可以通过SelectionMode 和SelectionUnit 属性来修改 ...
- 【实战】Docker入门实践二:Docker服务基本操作 和 测试Hello World
操作环境 操作系统:CentOS7.2 内存:1GB CPU:2核 Docker服务常用命令 docker服务操作命令如下 service docker start #启动服务 service doc ...
- [WCF编程]1.WCF入门示例
一.WCF是什么? Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,整合了原有的windows通讯的 .net Remotin ...
- 1.【转】spring MVC入门示例(hello world demo)
1. Spring MVC介绍 Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,基于 ...
随机推荐
- SpringBoot学习6:springboot文件上传
1.编写页面uploadFile.html <!DOCTYPE html> <html lang="en"> <head> <meta c ...
- 轻量级自动化工具 pssh
pssh应用场景 pssh是一个用python编写的可以并发在多台服务器上批量执行命令的工具,它支持文件并行复制,远程并行执行命令,其中文件并行复制是pssh的核心功能,也是同类工具中的一个亮点. 要 ...
- linux 基本命令笔记
nohup [process] & 后台挂起命令nohup 挂起& 后台运行 python3 manage.py runserver 0.0.0.0:8080 python -r 递 ...
- 描述linux目录结构以及目录结构命名规定
FHS全称(Filesystem Hierarchy Standard),中文意思是目录层次标准,是linux的目录规范标准. 详情点击查看 FHS定义了两层规范: 第一层:“/”目录下的各个目录应该 ...
- Sublime Text3的快捷键和插件
今天重装了一下Sublime Text3,发现了一个不错的网站,关于Sublime Text3的插件安装介绍的很详细,还有右键增强菜单和浏览器打开快捷键的创建.奉上链接 http://www.cnbl ...
- Redis ---------- Sort Set排序集合类型
sortset是(list)和(set)的集中体现 与set的相同点: string类型元素的集合 不同点: sortset的元素:值+权 适合场合 获得最热门前5个帖子的信息 例如 select * ...
- html5中的progress兼容ie,制作进度条样式
html5新增的progress标签用处很大,它可以制作进度条,不用像以前那样用css来制作进度条! 一.progress使用方法 progress标签很好使用,他有两个属性,value和max,va ...
- 时间轮算法的定时器(Delphi)
源码下载 http://files.cnblogs.com/lwm8246/uTimeWheel.rar D7,XE2 编译测试OK //时间轮算法的定时器 //-- : QQ unit uTimeW ...
- 02 mysql 基础二 (进阶)
mysql 基础二 阶段一 表约束 1.not null 非空约束 例子: create table tb1( id int, name varchar(20) not null ); 注意 空字符不 ...
- Flask初学者:视图函数/方法返回值(HTML模板/Response对象)
返回HTML模板:使用“from flask import render_template”,在函数中传入相对于文件夹“templates”HTML模板路径名称字符串即可(默认模板路径),flask会 ...