在spring中使用webservice(Restful风格)
我们一般都会用webservice来做远程调用,大概有两种方式,其中一种方式rest风格的简单明了。
记录下来作为笔记:
开发服务端:
具体的语法就不讲什么了,这个网上太多了,而且只要看一下代码基本上都懂,下面是直接贴代码:
package com.web.webservice.rs; import java.util.Iterator;
import java.util.List; import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import com.google.common.collect.Lists;
import com.web.module.index.model.dao.UserDao;
import com.web.module.index.model.entity.User; /**
*
* @author Hotusm
*
*/
@Path("/test")
public class UserService { private static final Logger logger=LoggerFactory.getLogger(UserService.class); public static final String APPLICATION_XML_UTF_8 = "application/xml; charset=UTF-8";
@Autowired
private UserDao userDao; /**
*
* @Produces 表示返回的数据格式
* @Consumes 表示接受的格式类型
* @GET 表示请求的类型
* @return
*
* <a href="http://www.ibm.com/developerworks/cn/web/wa-jaxrs/"> BLOG</a>
*/
@GET
@Path("/list")
@Produces("application/json")
public List<User> list(){
List<User> users=Lists.newArrayList();
Iterable<User> iters = userDao.findAll();
Iterator<User> iterator = iters.iterator();
while(iterator.hasNext()){
users.add(iterator.next());
} return users;
} /**
*
* 在网页上显示链接
* @return
*/
@GET
@Path("/page")
@Produces("text/html")
public String page(){ return "<a href='http://www.baidu.com'>百度</a>";
} }
这个风格和springmvc实在太像了,所以一看基本上就懂了。
下面是配置文件:
<?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:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> <import resource="classpath*:META-INF/cxf/cxf.xml" />
<import resource="classpath*:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath*:META-INF/cxf/cxf-servlet.xml" /> <jaxrs:server id="rsService" address="/jaxrs">
<!--在其中可以添加一些配置,比如拦截器等等的-->
<jaxrs:serviceBeans>
<ref bean="iuserService"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider"/>
</jaxrs:providers>
</jaxrs:server> <bean id="iuserService" class="com.web.webservice.rs.UserService"></bean> </beans>
写好这些之后,启动发现并不能够使用,这是因为我们还需要在web.xml中配置发现ws:
web.xml
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- 这样设置在rs下面才能看到ws的界面,所以的服务都在这个后面 -->
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/rs/*</url-pattern>
</servlet-mapping>
注意我们现在这样做以后,我们只要输入$ctx/rs那么下面所以的ws服务都能看到了。
其实使用spring的话,是非常的简单的。我们只需要配置一下上面的文件,最难的还是逻辑部分。
开发ws的服务端:
1:配置xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<!--设置一些属性,具体的可以看源码-->
<property name="requestFactory">
<bean class="org.springframework.http.client.SimpleClientHttpRequestFactory">
<property name="readTimeout" value="30000"/>
</bean>
</property>
</bean> </beans>
配置好了客户端的配置文件以后,我们就可以直接将restTemplate注入到我们需要使用的地方中去,这个类是spring帮我抽象出来的,里面有很多方法供我们的使用,其实就是封装了一层,如果不喜欢,完成可以自己封装一个,然后注入:
源码:
protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
ResponseExtractor<T> responseExtractor) throws RestClientException { Assert.notNull(url, "'url' must not be null");
Assert.notNull(method, "'method' must not be null");
ClientHttpResponse response = null;
try {
ClientHttpRequest request = createRequest(url, method);
if (requestCallback != null) {
requestCallback.doWithRequest(request);
}
response = request.execute();
if (!getErrorHandler().hasError(response)) {
logResponseStatus(method, url, response);
}
else {
handleResponseError(method, url, response);
}
if (responseExtractor != null) {
return responseExtractor.extractData(response);
}
else {
return null;
}
}
catch (IOException ex) {
throw new ResourceAccessException("I/O error on " + method.name() +
" request for \"" + url + "\":" + ex.getMessage(), ex);
}
finally {
if (response != null) {
response.close();
}
}
}
下面是一个客户端调用的例子(用的是springtest)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:/spring-context.xml","classpath*:/spring-mq-provider.xml","classpath*:/spring-mq-consumer.xml","classpath*:/spring-jaxrs-service.xml","classpath*:/spring-jaxrs-client.xml"})
public class RestTest { @Autowired
private RestTemplate restTemplate; @Value("${rest.service.url}")
String url;
@Test
public void test(){
//restTemplate=new RestTemplate();
String str = restTemplate.getForObject(url+"test/list", String.class); }
}
基本上这些就能购我们使用了。
下次有空吧soap方法的也总结一下。
在spring中使用webservice(Restful风格)的更多相关文章
- Spring整合CXF webservice restful 实例
webservice restful接口跟soap协议的接口实现大同小异,只是在提供服务的类/接口的注解上存在差异,具体看下面的代码,然后自己对比下就可以了. 用到的基础类 User.java @Xm ...
- springMVC中添加restful 风格
RESTful架构:是一种设计的风格,并不是标准,只是提供了一组设计原则和约束条件,也是目前比较流行的一种互联网软件架构.它结构清晰.符合标准.易于理解.扩展方便,所以正得到越来越多网站的采用. 关于 ...
- 使用SpringBoot编写Restful风格接口
一.简介 Restful是一种对url进行规范的编码风格,通常一个网址对应一个资源,访问形式类似http://xxx.com/xx/{id}/{id}. 举个栗子,当我们在某购物网站上买手机时会 ...
- Spring Boot 中 10 行代码构建 RESTful 风格应用
RESTful ,到现在相信已经没人不知道这个东西了吧!关于 RESTful 的概念,我这里就不做过多介绍了,传统的 Struts 对 RESTful 支持不够友好 ,但是 SpringMVC 对于 ...
- SpringMVC实现Restful风格的WebService
1.环境 JDK7 MyEclipse2014 tomcat8 maven 3.3.3 spring4.1.4 2.创建maven工程 使用MyEclipse创建maven工程的方式可以参考这篇博文( ...
- 用cxf开发restful风格的WebService
我们都知道cxf还可以开发restful风格的webService,下面是利用maven+spring4+cxf搭建webService服务端和客户端Demo 1.pom.xml <projec ...
- 【Spring学习笔记-MVC-18.1】Spring MVC实现RESTful风格-同一资源,多种展现:xml-json-html
概要 要实现Restful风格,主要有两个方面要讲解,如下: 1. 同一个资源,如果需要返回不同的形式,如:json.xml等: 不推荐的做法: /user/getUserJson /user/get ...
- spring boot / cloud (十四) 微服务间远程服务调用的认证和鉴权的思考和设计,以及restFul风格的url匹配拦截方法
spring boot / cloud (十四) 微服务间远程服务调用的认证和鉴权的思考和设计,以及restFul风格的url匹配拦截方法 前言 本篇接着<spring boot / cloud ...
- restful风格接口和spring的运用
Restful风格的API是一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件.它主要用于客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机 ...
随机推荐
- Atitit. Api 设计 原则 ---归一化
Atitit. Api 设计 原则 ---归一化 1.1. 叫做归一化1 1.2. 归一化的实例:一切对象都可以序列化/toString 通过接口实现1 1.3. 泛文件概念.2 1.4. 游戏行业 ...
- Atitit 编程语言知识点tech tree v2 attilax大总结
Atitit 编程语言知识点tech tree v2 attilax大总结 大分类中分类小分类知识点原理与规范具体实现(javac#里面的实现phpjsdsl(自己实现其他语言实现 类与对象实现对象实 ...
- Atitit vod ver 12 new feature v12 pb2 影吧 视频 电影 点播 播放系统v12新特性
Atitit vod ver 12 new feature v12 pb2 影吧 视频 电影 点播 播放系统v12新特性 项目分离从独立的se ver Run mode from brow ex to ...
- Atitit 从 RGB 到 HSL 或 HSV 的转换
Atitit 从 RGB 到 HSL 或 HSV 的转换 1.1. 从 RGB 到 HSL 或 HSV 的转换公式与原理1 1.2. public static HSV RGB2HSV(Color ...
- CI Weekly #1 | 这份周刊,带你了解 CI/CD 、DevOps、自动化测试
原文首次发布与 flow.ci Blog >> 链接,转载请联系:) 准备了很久,CI Weekly 第一期终于来了. CI Weekly 围绕『 软件工程效率提升』 进行一系列技术内容分 ...
- Win7系统.net framework 4.0没有注册导致部署在IIS的站点跑不起来怎么办
win7装了VS再装IIS,结果IIS里面有.NET4.0,但是程序始终是跑不起来,怎么办呢? 分析觉得可能是因为4.0没有注册到IIS,在win7下如果先安装vs2010 (附带会安装Microso ...
- js中NAN、NULL、undefined的区别
NaN:保留字(表明数据类型不是数字) undefined:对象属性或方法不存在,或声明了变量但从未赋值.即当你使用了对象未定的属性或者未定义的方法时或当你声明一个变量,但你确从未对其进行赋值,便对其 ...
- React(三)组件的生命周期
Component Specs and LifeCycle <div id="app"></div> <script src="bower_ ...
- leancloud 用户登录(调用API) 教程
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 14.0px Menlo } p.p2 { margin: 0.0px 0.0px 0.0px 0.0px; ...
- VS报错:The build tools for v140 (Platform Toolset = 'v140') cannot be found
VS低版本打开高版本常会出现的错: The build tools for v140 (Platform Toolset = 'v140') cannot be found. To build usi ...