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层进行职责解耦,基于 ...
随机推荐
- Oracle Like、Instr以及正则表达式
查看测试数据 select * from student; 1. like 在where字句中使用like可以达到模糊查询的效果,常用通配符如下 ▶ %: 使用 % 有三种情况 ① 字段 like ‘ ...
- chisel(安装)
github地址 先安装homeBrew ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/m ...
- vue中登录模块的插件封装
一个电商城的项目,场景是:在未登录的情况下点击收藏或者加入购物车等操作,执行一个方法如this.$login()来动态插入登录组件. 第一步:写好关于这个登录弹窗的单文件组件 loginBox.vue ...
- 51nod 1298 圆与三角形——计算几何
题目链接:http://www.51nod.com/Challenge/Problem.html#!#problemId=1298 转化成判断三条线段和圆是否
- MySQL(mariadb)主从复制模式与复制过滤
在前一篇文章<mysql多实例与复制应用>中只对mysql的复制做了简单的介绍,本篇内容专门介绍一下mysql的复制. MySQL复制 mysql复制是指将主数据库的DDL和DML操作通过 ...
- datatable行内内容太长,有时不自动换行解决方法
加一个css属性即可 style = "word-wrap:break-word;" js代码: "render": function (data, type, ...
- Java OOP——JAVA关键字与保留字说明及使用
1.abstract abstract 关键字可以修改类或方法. abstract 类可以扩展(增加子类),但不能直接实例化. abstract 方法不在声明它的类中实现,但必须在某个子类中重写. - ...
- 区分js中的null,undefined,"",0和false
console.log(typeof null);//object console.log(typeof undefined);//undefined console.log(typeof " ...
- HTML中body相关标签-03
今日主要内容: 列表标签 <ul>.<ol>.<dl> 表格标签 <table> 表单标签 <fom> 一.列表标签 列表标签分为三种. 1 ...
- P3819 松江1843路(洛谷月赛)
P3819 松江1843路 题目描述 涞坊路是一条长L米的道路,道路上的坐标范围从0到L,路上有N座房子,第i座房子建在坐标为x[i]的地方,其中住了r[i]人. 松江1843路公交车要在这条路上建一 ...