我们一般都会用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风格)的更多相关文章

  1. Spring整合CXF webservice restful 实例

    webservice restful接口跟soap协议的接口实现大同小异,只是在提供服务的类/接口的注解上存在差异,具体看下面的代码,然后自己对比下就可以了. 用到的基础类 User.java @Xm ...

  2. springMVC中添加restful 风格

    RESTful架构:是一种设计的风格,并不是标准,只是提供了一组设计原则和约束条件,也是目前比较流行的一种互联网软件架构.它结构清晰.符合标准.易于理解.扩展方便,所以正得到越来越多网站的采用. 关于 ...

  3. 使用SpringBoot编写Restful风格接口

    一.简介    Restful是一种对url进行规范的编码风格,通常一个网址对应一个资源,访问形式类似http://xxx.com/xx/{id}/{id}. 举个栗子,当我们在某购物网站上买手机时会 ...

  4. Spring Boot 中 10 行代码构建 RESTful 风格应用

    RESTful ,到现在相信已经没人不知道这个东西了吧!关于 RESTful 的概念,我这里就不做过多介绍了,传统的 Struts 对 RESTful 支持不够友好 ,但是 SpringMVC 对于 ...

  5. SpringMVC实现Restful风格的WebService

    1.环境 JDK7 MyEclipse2014 tomcat8 maven 3.3.3 spring4.1.4 2.创建maven工程 使用MyEclipse创建maven工程的方式可以参考这篇博文( ...

  6. 用cxf开发restful风格的WebService

    我们都知道cxf还可以开发restful风格的webService,下面是利用maven+spring4+cxf搭建webService服务端和客户端Demo 1.pom.xml <projec ...

  7. 【Spring学习笔记-MVC-18.1】Spring MVC实现RESTful风格-同一资源,多种展现:xml-json-html

    概要 要实现Restful风格,主要有两个方面要讲解,如下: 1. 同一个资源,如果需要返回不同的形式,如:json.xml等: 不推荐的做法: /user/getUserJson /user/get ...

  8. spring boot / cloud (十四) 微服务间远程服务调用的认证和鉴权的思考和设计,以及restFul风格的url匹配拦截方法

    spring boot / cloud (十四) 微服务间远程服务调用的认证和鉴权的思考和设计,以及restFul风格的url匹配拦截方法 前言 本篇接着<spring boot / cloud ...

  9. restful风格接口和spring的运用

    Restful风格的API是一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件.它主要用于客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机 ...

随机推荐

  1. 如何在 Ubuntu 15.04 上安装带 JSON 支持的 SQLite 3.9

    欢迎阅读我们关于SQLite 的文章,SQLite 是当今世界上使用最广泛的 SQL 数据库引擎,它基本不需要配置,不需要设置或管理就可以运行.SQLite 是一个是公开领域(public-domai ...

  2. EF架构~扩展一个分页处理大数据的方法

    回到目录 最近总遇到大数据的问题,一次性处理几千万数据不实际,所以,我们需要对大数据进行分块处理,或者叫分页处理,我在EF架构里曾经写过类似的,那是在进行BulkInsert时,对大数据批量插入时候用 ...

  3. Atitit python3.0 3.3 3.5 3.6 新特性 Python2.7新特性1Python 3_x 新特性1python3.4新特性1python3.5新特性1值得关注的新特性1Pyth

    Atitit python3.0 3.3 3.5 3.6 新特性 Python2.7新特性1 Python 3_x 新特性1 python3.4新特性1 python3.5新特性1 值得关注的新特性1 ...

  4. 关于WPF中RichTextBox失去焦点后如何保持高亮显示所选择的内容

    其实很简单,只要将容器控件中的附加属性FocusManager.IsFocusScope设为True就可以了 下面是个简单的用例: <Window x:Class="WpfApplic ...

  5. 遍历后台的List,让前台的多选宽被选中

    后端代码: /** * 获取优惠卷分页信息 * * * @param ph * 包括查询条件以及分页查询条件 * */ @Override public DataGrid<AppCmsCoupo ...

  6. 转载:Spring AOP (下)

    昨天记录了Spring AOP学习的一部分(http://www.cnblogs.com/yanbincn/archive/2012/08/13/2635413.html),本来是想一口气梳理完的.但 ...

  7. Leetcode 35 Search Insert Position 二分查找(二分下标)

    基础题之一,是混迹于各种难题的基础,有时会在小公司的大题见到,但更多的是见于选择题... 题意:在一个有序数列中,要插入数target,找出插入的位置. 楼主在这里更新了<二分查找综述>第 ...

  8. 移动端IM开发需要面对的技术问题

    1.前言 这两年多一直从事网易云信 iOS 端 IM SDK的开发,期间不断有兄弟部门的同事和合作伙伴过来问各种技术细节,干脆统一介绍下一个IM APP的方方面面,包括技术选型(包括通讯方式,网络连接 ...

  9. 浅谈attr()和prop()

    刚开始学JQ的时候 ,看到attr()和prop()这两个属性的时候感觉很迷茫,而且配合官方给出的推荐使用图: prop()可以做到的attr()完全都可以,而且做不到的attr()也可以做到.何用? ...

  10. 本机搭建zookeeper集群

    3个 clientPort分别设置为2181,2182,2083 server.1=127.0.0.1:2888:3888 server.2=127.0.0.2:2889:3889 server.3= ...