Spring Boot可以非常简单的发布和调用RESTful web service,下面参考官方指导体验一下

1.首先访问 http://start.spring.io/ 生成Spring Boot基础项目

或者使用git clone https://github.com/spring-guides/gs-rest-service.git

这里使用Maven导入IDEA如下:

此时项目已经可以启动,但是没有任何功能,可以看到启动日志中嵌入tomcat的信息:

2.添加代码:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Greeting { private final long id;
private final String content; public Greeting(long id, String content) {
this.id = id;
this.content = content;
} public long getId() {
return id;
} public String getContent() {
return content;
}
}

---

@RestController
public class GreetingController { private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong(); //@CrossOrigin(origins = "http://localhost:8081")
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
System.out.println("getName:"+name);
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}

---

此时再启动,然后使用浏览器访问 http://localhost:8080/greeting

浏览器显示

{"id":1,"content":"Hello, World!"}

可见Spring使用Jackson JSON自动将Greeting对象转为json

@RequestMapping注解将Http请求指向greeting()方法,可以通过@RequestMapping(method=GET)指定请求方式

@RequestParam注解将查询参数name绑定到greeting方法的name参数上,并指定了默认值。

@RestController注解相当于@Controller加@ResponseBody的效果。

接下来是调用WebService,通过Spring提供的RestTemplate类

添加代码:

public class Application {

    private static final Logger log = LoggerFactory.getLogger(Application.class);

    public static void main(String args[]) {
RestTemplate restTemplate = new RestTemplate();
for (int k = 0 ; k< 10;k++) {
Greeting greeting = restTemplate.getForObject("http://localhost:8080/greeting?name=luangeng"+k, Greeting.class);
System.out.println("getName "+greeting.toString());
}
} }

---

使用AJAX调用WebService

写一个简单的Html页面:

<!DOCTYPE html>
<html>
<head>
<title>ws test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head> <body>
<div>
<p class="greeting-id">The ID is: </p>
<p class="greeting-content">The content is: </p>
</div>
</body>
</html> <script>
$().ready(function() {
$.ajax({
url: "http://localhost:8080/greeting?name=luangeng"
}).then(function(data) {
$('.greeting-id').append(data.id);
$('.greeting-content').append(data.content);
});
});
</script>

---

添加到jetty的webapp中,在8081端口启动jetty :java -jar ../start.jar jetty.http.port=8081   ,使用浏览器访问  http://localhost:8081/test.html 可看到浏览器控制台如下报错信息:

可知报错原因为8080拒绝访问,8080和8081端口不同源导致的。

打开跨域访问:在greeting方法上加@CrossOrigin(origins = "http://localhost:8081")注解即可

再次尝试即可看到浏览器界面显示如下:

说明调用WS成功。

通过以上Spring官网的几个简单的例子可以看到使用SpringBoot发布和调用RESTful WebService是非常容易的。

常用注解:

@RestController :避免了每个方法都要添加@ResponseBody注解。@RestController 内部包含@ResponseBody注解,可以认为是 @Controller 和 @ResponseBody的组合。

@RequestBody : 如果方法参数被 @RequestBody注解,Spring将绑定HTTP请求体到那个参数上。Spring将根据请求中的ACCEPT或者 Content-Type header使用 HTTP Message converters 来将http请求体转化为domain对象。

@ResponseBody : 如果方法加上了@ResponseBody注解,Spring返回值到响应体。Spring将根据请求中的 Content-Type header(私下)使用 HTTP Message converters 来将domain对象转换为响应体。

ResponseEntity: HTTP响应(response)对象,可以指定状态码、头信息和响应体。包含要构建的HTTP Response 的全部信息。

@PathVariable: 参数注解,表示方法参数绑定到一个url变量中

end

Spring Boot发布和调用RESTful web service的更多相关文章

  1. 构建一个基于 Spring 的 RESTful Web Service

    本文详细介绍了基于Spring创建一个“hello world” RESTful web service工程的步骤. 目标 构建一个service,接收如下HTTP GET请求: http://loc ...

  2. Building a RESTful Web Service Using Spring Boot In Eclipse

    一.构建restful web service 创建Maven的java web工程,maven的pom文件加入依赖包 创建包hello Greeting.java package hello; pu ...

  3. Spring Boot 构建一个 RESTful Web Service

    1  项目目标: 构建一个 web service,接收get 请求 http://localhost:8080/greeting 响应一个json 结果: {"id":1,&qu ...

  4. 翻译-使用Spring调用SOAP Web Service

    原文链接: http://spring.io/guides/gs/consuming-web-service/ 调用SOAP web service 本指南将指导你使用Spring调用一个基于SOAP ...

  5. 用Spring Tools Suite(STS)开始一个RESTful Web Service

    spring.io官方提供的例子Building a RESTful Web Service提供了用Maven.Gradle.STS构建一个RESTFul Web Service,实际上采用STS构建 ...

  6. 如何使用 JMeter 调用你的 Restful Web Service?进行简单的压力测试和自动化测试

    表述性状态传输(REST)作为对基于 SOAP 和 Web 服务描述语言(WSDL)的 Web 服务的简单替代,在 Web 开发上得到了广泛的接受.能够充分证明这点的是主流 Web 2.0 服务提供商 ...

  7. Apache CXF实现Web Service(4)——Tomcat容器和Spring实现JAX-RS(RESTful) web service

    准备 我们仍然使用 Apache CXF实现Web Service(2)——不借助重量级Web容器和Spring实现一个纯的JAX-RS(RESTful) web service 中的代码作为基础,并 ...

  8. Apache CXF实现Web Service(3)——Tomcat容器和不借助Spring的普通Servlet实现JAX-RS(RESTful) web service

    起步 参照这一系列的另外一篇文章: Apache CXF实现Web Service(2)——不借助重量级Web容器和Spring实现一个纯的JAX-RS(RESTful) web service 首先 ...

  9. 【转】Spring 4.x实现Restful web service

    http://my.oschina.net/yuyidi/blog/352909 首先我们还是跟之前一样,创建一个maven项目,不过因为Spring Restful web service是基于Sp ...

随机推荐

  1. 数据结构与算法分析:C语言描述(原书第2版 简体中文版!!!) PDF+源代码+习题答案

    转自:http://www.linuxidc.com/Linux/2014-04/99735.htm 数据结构与算法分析:C语言描述(原书第2版中文版!!!) PDF+源代码+习题答案 数据结构与算法 ...

  2. poj 3080 Blue Jeans【字符串处理+ 亮点是:字符串函数的使用】

    题目:http://poj.org/problem?id=3080 Sample Input 3 2 GATACCAGATACCAGATACCAGATACCAGATACCAGATACCAGATACCA ...

  3. mysql里的ibdata1文件

    mysql大多数磁盘空间被 InnoDB 的共享表空间 ibdata1 使用.而你已经启用了 innodb_file_per_table,所以问题是: ibdata1存了什么? 当你启用了innodb ...

  4. Git使用http clone客户端保存用户名密码

    使用Git Bash时,用命令git pull或git push时总是要输入密码,很烦躁 解决办法 需要注意的是,这个方法是在Windows下使用 1. 新建环境变量   HOME 值为 %USERP ...

  5. js正则表达式验证(化繁为简)

    以前用js写正则表达式验证,每一个文本框后面都要添加一个onblur函数,验证的信息少,也没体会到有多繁琐,这次项目中的页面比较多,页面中的信息也比较多,如果每个文本框都加一个验证函数的话,js验证代 ...

  6. HBase-scan简介及优化(缓存与批量处理)

    扫描(scan) 这种技术类似于数据库系统中的游标(cursor),并利用到了HBase提供的底层顺序存储的数据结构. 扫描操作的使用跟get方法非常类似.由于扫描操作的工作方式类似于迭代器,所以用户 ...

  7. Codeforces Beta Round #61 (Div. 2) D. Petya and His Friends 想法

    D. Petya and His Friends time limit per test 2 seconds memory limit per test 256 megabytes input sta ...

  8. 初始化dataframe

    由字典生成dataframe: >>> d = {'col1': [1, 2], 'col2': [3, 4]} >>> df = pd.DataFrame(dat ...

  9. (转) Nova是如何统计OpenStack资源

    引言 运维的同事常常遇到这么四个问题: Nova 如何统计 OpenStack 计算资源? 为什么 free_ram_mb, free_disk_gb 有时会是负数? 即使 free_ram_mb, ...

  10. Java-集合类源码List篇(三)

    前言 前面分析了ArrayList和LinkedList的实现,分别是基于数组和双向链表的List实现.但看之前那张图,还有两个实现类,一个是Vector,另一个是Stack,接下里一起走进它们的源码 ...