java实现REST方式的webService
此文章是基于 搭建Jquery+SpringMVC+Spring+Hibernate+MySQL平台
一. 简介
WebService有两种方式,一是SOAP方式,二是REST方式。SOAP是基于XML的交互,WSDL也是一个XML文档,可以使用WSDL作为SOAP的描述文件;REST是基于HTTP协议的交互,支持JSON、XML等交互,不需要WSDL。
二. jar包介绍
1. 点击此下载 apache-cxf-3.0.3,并在 lib 文件夹下得到:
commons-codec-1.9.jar
cxf-core-3.0.3.jar
cxf-rt-frontend-jaxrs-3.0.3.jar
cxf-rt-transports-http-3.0.3.jar
javax.ws.rs-api-2.0.1.jar
2. commons-httpclient-3.1.jar
三. 相关程序代码
1. applicationInterface.xml:spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> <!-- cxf发布rest服务 -->
<import resource="classpath:META-INF/cxf/cxf.xml"/>
<!-- 这里是cxf2.x版本的配置,3.0没有了要去掉 -->
<!-- <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" /> -->
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" /> <bean id="receiver" class="com.ims.test.webService.cxf.Receiver" /> <jaxrs:server id="serviceContainer" address="/">
<jaxrs:serviceBeans>
<ref bean="receiver" />
</jaxrs:serviceBeans>
</jaxrs:server>
<!-- cxf发布rest服务 --> </beans>
2. web.xml:web工程配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_4.xsd
http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.4"> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationInterface.xml
</param-value>
</context-param> <servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping> </web-app>
3. 基础服务
a. BaseService.java:接口
package com.ims.interfaces.webService.cxf; import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; public interface BaseService {
@POST
@Consumes(MediaType.TEXT_HTML)
@Produces(MediaType.TEXT_HTML)
public void execute(@QueryParam("type") String type);
}
b. BaseServiceImpl.java:实现
package com.ims.interfaces.webService.cxf; import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType; /**
* 基础服务接口
*/
public abstract class BaseServiceImpl implements BaseService{
@Context
protected HttpServletRequest request;
@Context
protected HttpServletResponse response; @Override
@POST
@Consumes(MediaType.TEXT_HTML)
@Produces(MediaType.TEXT_HTML)
public void execute(@QueryParam("type") String type) {
try {
// 获取请求类型
RequestType reqType = RequestType.getTypeByCode(Integer.valueOf(type)); // 获取HTTP请求体XML字符输入流
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new BufferedInputStream(request.getInputStream()), "gb2312")); // 业务处理
ResponseResult result = process(reqType, reader);
// 设置响应编码
response.setStatus(result.getStatus().getCode()); // 输出响应体
response.setCharacterEncoding("gb2312");
OutputStream outputStream = response.getOutputStream();
outputStream.write(result.getResult().getBytes("gb2312"));
}
catch (IOException ioe) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} public abstract ResponseResult process(RequestType reqType, BufferedReader reader);
}
4. Receiver.java:接收端类
package com.ims.test.webService.cxf; import java.io.BufferedReader; import javax.ws.rs.Path; import com.ims.interfaces.webService.cxf.BaseServiceImpl;
import com.ims.interfaces.webService.cxf.RequestType;
import com.ims.interfaces.webService.cxf.ResponseResult;
import com.ims.interfaces.webService.cxf.ResponseStatus; @Path(value = "/receive.do")
public class Receiver extends BaseServiceImpl { @Override
public ResponseResult process(RequestType reqType, BufferedReader reader) {
ResponseResult result = null; switch(reqType){
case UNKNOWN:
result = new ResponseResult(ResponseStatus.CODE400, "");
break;
default:
break;
} return result;
} }
5. Sender.java:发送端类
package com.ims.test.webService.cxf; import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity; public class Sender { public static void main(String[] args) {
String url = "http://localhost:8090/ims/service/receive.do?type=0";
String xmlString = "<?xml version=\"1.0\" encoding=\"gbk\"?>";
post(url, xmlString);
} /**
* 发送xml数据请求到server端
* @param url xml请求数据地址
* @param xmlString 发送的xml数据流
* @return null发送失败,否则返回响应内容
*/
public static boolean post(String url,String xmlString){
boolean result = false;
//创建httpclient工具对象
HttpClient client = new HttpClient();
//创建post请求方法
PostMethod myPost = new PostMethod(url);
//设置请求超时时间
client.getHttpConnectionManager().getParams().setConnectionTimeout(300*1000); try{
//设置请求头部类型
myPost.setRequestHeader("Content-Type","text/html");
myPost.setRequestEntity(new StringRequestEntity(xmlString,"text/html","gbk"));
int statusCode = client.executeMethod(myPost);
if(statusCode == HttpStatus.SC_OK){
result = true;
}
}catch (Exception e) {
e.printStackTrace();
}finally{
myPost.releaseConnection();
}
return result;
}
}
四. 测试
eclipse上启动ims工程(webService接收端),以java执行Sender类,eclipse上调试查看Receive类是否收到xml文件
五. 备注
1. cxf 是支持多线程的,默认的线程池配置可查看 org.apache.cxf.workqueue.AutomaticWorkQueueImpl 源文件:
static final int DEFAULT_MAX_QUEUE_SIZE = 256; 。。。。。。。。。 public AutomaticWorkQueueImpl() {
this(DEFAULT_MAX_QUEUE_SIZE);
}
public AutomaticWorkQueueImpl(String name) {
this(DEFAULT_MAX_QUEUE_SIZE, name);
}
public AutomaticWorkQueueImpl(int max) {
this(max, "default");
}
public AutomaticWorkQueueImpl(int max, String name) {
this(max,
0,
25,
5,
2 * 60 * 1000L,
name);
}
public AutomaticWorkQueueImpl(int mqs,
int initialThreads,
int highWaterMark,
int lowWaterMark,
long dequeueTimeout) {
this(mqs, initialThreads, highWaterMark, lowWaterMark, dequeueTimeout, "default");
}
public AutomaticWorkQueueImpl(int mqs,
int initialThreads,
int highWaterMark,
int lowWaterMark,
long dequeueTimeout,
String name) {
this.maxQueueSize = mqs == -1 ? DEFAULT_MAX_QUEUE_SIZE : mqs;
this.initialThreads = initialThreads;
this.highWaterMark = -1 == highWaterMark ? Integer.MAX_VALUE : highWaterMark;
this.lowWaterMark = -1 == lowWaterMark ? Integer.MAX_VALUE : lowWaterMark;
this.dequeueTimeout = dequeueTimeout;
this.name = name;
this.changeListenerList = new ArrayList<PropertyChangeListener>();
} 。。。。。。。。。 protected synchronized ThreadPoolExecutor getExecutor() {
if (executor == null) {
threadFactory = createThreadFactory(name);
executor = new ThreadPoolExecutor(lowWaterMark,
highWaterMark,
TimeUnit.MILLISECONDS.toMillis(dequeueTimeout),
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(maxQueueSize),
threadFactory) {
@Override
protected void terminated() {
ThreadFactory f = executor.getThreadFactory();
if (f instanceof AWQThreadFactory) {
((AWQThreadFactory)f).shutdown();
}
if (watchDog != null) {
watchDog.shutdown();
}
}
};
2. 若要配置线程池参数,可配置 cxf-core-3.0.3.jar\META-INF\cxf\cxf.xml 文件:
<bean id="default-wq" class="org.apache.cxf.workqueue.AutomaticWorkQueueImpl">
<constructor-arg index="0">
<!-- Max number of elements in the queue -->
<value>20000</value>
</constructor-arg>
<constructor-arg index="1">
<!-- name -->
<value>default</value>
</constructor-arg>
<property name="name" value="default" />
<property name="highWaterMark" value="30" />
</bean>
java实现REST方式的webService的更多相关文章
- Java调用WebService方法总结(9,end)--Http方式调用WebService
Http方式调用WebService,直接发送soap消息到服务端,然后自己解析服务端返回的结果,这种方式比较简单粗暴,也很好用:soap消息可以通过SoapUI来生成,也很方便.文中所使用到的软件版 ...
- salesforce 零基础学习(三十三)通过REST方式访问外部数据以及JAVA通过rest方式访问salesforce
本篇参考Trail教程: https://developer.salesforce.com/trailhead/force_com_dev_intermediate/apex_integration_ ...
- FineReport中以jws方式调用WebService数据源方案
在使用WebService作为项目的数据源时,希望报表中也是直接调用这个WebService数据源,而不是定义数据连接调用对应的数据库表,这样要怎么实现呢? 在程序中访问WebService应用服务, ...
- 使用ajax和urlconnection方式调用webservice服务
<html> <head> <title>使用ajax方式调用webservice服务</title> <script> var xhr = ...
- 使用CXF实现基于Rest方式的WebService(转)
转自:https://www.cnblogs.com/zjm701/p/6845813.html原文更清晰 本文介绍使用CXF实现基于Rest方式的WebService(CXF的版本是3.0.0) 一 ...
- 使用CXF实现基于Rest方式的WebService
本文介绍使用CXF实现基于Rest方式的WebService(CXF的版本是3.0.0) 一. 前言 Java有三种WebService规范:Jax-WS,Jax-RS,Jaxm 1. Jax-WS( ...
- 使用Axis2方式发布webService的三种方式
1.Axis2的下载和安装 首先可以下载如下两个zip包:axis2-1.6.1-bin.zipaxis2-1.6.1-war.zip其中 axis2-1.6.1-bin.zip文件中包含了Axis2 ...
- Java 使用线程方式Thread和Runnable,以及Thread与Runnable的区别
一. java中实现线程的方式有Thread和Runnable Thread: public class Thread1 extends Thread{ @Override public void r ...
- java通过jni方式获取硬盘序列号(windows,linux)
linux系统java通过jni方式获取硬盘序列号 http://blog.csdn.net/starter110/article/details/8186788 使用jni在windows下读取硬盘 ...
随机推荐
- CSS3知识点整理&&一些demo
css3能做什么 响应式开发的基础,然后能实现一些酷炫的效果咯. 以下案例纯css3实现,一点都没用js (入门简单,但是水很深) 叮当猫纯用css3做出 http://codepen ...
- VS2013预览版安装 体验截图
支持与msdn帐号链接: 不一样的团队管理: 新建项目:
- [Java 基础]数据类型
基本类型和引用类型 Java中的数据类型有两类: l 基本类型(又叫内置数据类型,或理解为值类型) l 引用类型 基本类型和引用类型的区别 1. 从概念方面来说 基本类型:变量名指向具体的数值 ...
- jQuery-1.9.1源码分析系列(十三) 位置大小操作
先列一下这些个api jQuery.fn.css (propertyName [, value ]| object )(函数用于设置或返回当前jQuery对象所匹配的元素的css样式属性值.如果需要删 ...
- 为.NET搭建Linux的开发环境,鄙视那些将简单事情复杂化的人
写在前面的吐槽 原本跨平台开发很容易的事情, 很多人把它弄得很麻烦,给外人的感觉:你们.NET跨平台开发好不成熟,好麻烦哦. ..................................... ...
- .NET Core New csproj 如何发布可执行文件
一.前言 .NET工具链在最新的Preview3版本中,引入了新的MSBuild项目系统,项目文件又回归了.csproj的XML文件来管理,项目文件.包引用.程序集引用..NET Core工具集.发布 ...
- linux下命令行操作快捷键及技巧
历史相关命令 !!:执行上一条命令 !num:执行历史命令中第num条命令 !-num:执行历史命令中倒数第num条命令 !?string?:执行最近一条包含有string字符串的命令 Ctrl+ ...
- 基于sticky组件,实现带sticky效果的tab导航和滚动导航
上文提供了一个改进版的sticky组件,并将演示效果应用到了自己的博客.有了类似sticky的这种简单组件,我们就可以在利用它开发更丰富的效果,比如本文要介绍的tab导航和滚动导航.实现简单,演示效果 ...
- 7.2 数据注解属性--TimeStamp特性【Code-First 系列】
TimeStamp特性可以应用到领域类中,只有一个字节数组的属性上面,这个特性,给列设定的是tiemStamp类型.在并发的检查中,Code-First会自动使用这个TimeStamp类型的字段. 下 ...
- jquery如何判断checkbox(复选框)是否被选中 ...
<script type="text/javascript" src="../lib/jQuery1.11.1.js"></script> ...