章节目录

前置技能

使用maven来管理java项目

这个技能必须点一级,以便快速配置项目。

本文实际上是我学习Spring的过程中搬的官网上的demo,使用maven配置项目。

② jdk 1.8+   该服务demo需要在jdk1.8+的环境下运行

新建项目,配置依赖文件

① 安装好eclipse的maven插件后,使用file——new——other——maven——maven project 新建一个空的maven项目。

② 访问Spring官网demo http://spring.io/guides/gs/rest-service/

将Build With Maven 模块中提供的pom内容复制到我们自己的pom文件中,注意将项目坐标替换成上图中的配置。

最终得到pom文件:

<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sogou.testspring</groupId>
<artifactId>testspring-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
</parent> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies> <properties>
<java.version>1.8</java.version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestone</id>
<url>https://repo.spring.io/libs-release</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestone</id>
<url>https://repo.spring.io/libs-release</url>
</pluginRepository>
</pluginRepositories>
</project>

编写Model和Controller

在source目录 src/main/java下新建hello包,在hello包下新建

① Greeting.java

package hello;

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;
}
}

② GreetingController.java

package hello;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; @RestController
public class GreetingController { private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong(); @RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
@RequestMapping(value="/greeting2")
public String Greeting2(@RequestParam(value="name",defaultValue="meiyou") String name){
return name;
}
@RequestMapping("/greeting3")
public List<Greeting> greeting3(@RequestParam(value="name", defaultValue="World") String name) {
List<Greeting> list=new ArrayList<Greeting>();
list.add(new Greeting(counter.incrementAndGet(),
String.format(template, name)));
list.add(new Greeting(counter.incrementAndGet(),
String.format(template, name)));
return list;
}
}

③ 启动服务  Application.java

package hello;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class Application { public static void main(String[] args) {
SpringApplication.run(Application.class, args);
} }

官网的demo至此为止,可以发现这个demo并不需要配置web.xml或者spring dispatherServlet的xml文件,也需要依赖web容器就可以运行。 看起来这更像是一个普通的Java应用程序。

启动服务&访问

① 因为在pom中配置了插件

 <plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

所以我们可以直接 runAs——maven build,target输入 spring-boot:run  来启动服务

② 通过maven package打包项目,生成jar包,然后在target目录下  java -jar  jar包名称,即可启动项目

但是

原搬原官网的demo,启动的时候会报错,顺着报错信息找下去,发现

spring-boot-autoconfigure-1.2.5.RELEASE.jar包下

org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties 类中

有这么一段代码

public static final String DEFAULT_PREFIX = "classpath:/templates/";

public static final String DEFAULT_SUFFIX = ".html";

看样子需要一个templates的目录,于是在resources目录下新建一个templates目录,再次启动成功。

在浏览器中访问:

http://localhost:8080/greeting

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

http://localhost:8080/greeting2 meiyou

http://localhost:8080/greeting3 [{"id":3,"content":"Hello, World!"},{"id":4,"content":"Hello, World!"}]

其他

注意到demo的控制器中使用了一个注解 @RestController ,这个在spring3.x里边是没有的。

/*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.springframework.web.bind.annotation; import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; import org.springframework.stereotype.Controller; /**
* A convenience annotation that is itself annotated with {@link Controller @Controller}
* and {@link ResponseBody @ResponseBody}.
* <p>
* Types that carry this annotation are treated as controllers where
* {@link RequestMapping @RequestMapping} methods assume
* {@link ResponseBody @ResponseBody} semantics by default.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
* @since 4.0
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController { /**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any
* @since 4.0.1
*/
String value() default ""; }

可以看到该注解是一个类注解,其功能相当于同时应用了  @Controller 和 @ResponseBody

http://www.cnblogs.com/tzyy/p/4837701.html

5分钟用Spring4 搭建一个REST WebService(转)的更多相关文章

  1. 5分钟用Spring4 搭建一个REST WebService

    前置技能 ① 使用maven来管理java项目 这个技能必须点一级,以便快速配置项目. 本文实际上是我学习Spring的过程中搬的官网上的demo,使用maven配置项目. ② jdk 1.8+   ...

  2. 5分钟使用docker搭建一个WordPress

    环境为已安装Docker Destop的Windows系统. 过程 使用Docker拉去官方WordPress镜像再进行简单配置是可行的, 但是这里我们使用docker-compose,它会自动根据你 ...

  3. 三分钟使用webpack-dev-sever搭建一个服务器

    webpack-dev-server是一个小型的Node.js Express服务器,我们可以通过它搭建一个本地服务器,并且实现文件热更新; 1.切换到你的目录下对项目进行初始化 npm init 一 ...

  4. 使用Hugo,只需5分钟,轻松搭建一个自己的博客

    前面跟大家介绍过hexo这款静态博客系统,功能强大,基本能满足博客的各种需求.今天,我再跟大家介绍一款优秀的静态博客系统,那就是Hugo. Hugo是由Go语言实现的静态网站生成器.简单.易用.高效. ...

  5. 搭建一个超好用的 cmdb 系统

    10 分钟为你搭建一个超好用的 cmdb 系统 CMDB 是什么,作为 IT 工程师的你想必已经听说过了,或者已经烂熟了,容我再介绍一下,以防有读者还不知道.CMDB 的全称是 Configurati ...

  6. 10分钟搭建一个小型网页(python django)(hello world!)

    10分钟搭建一个小型网页(python django)(hello world!) 1.安装django pip install django 安装成功后,在Scripts目录下存在django-ad ...

  7. 3分钟搭建一个网站?腾讯云Serverless开发体验

    作为一个开发者,应该都能理解一个网站从开发到上线,要经过很多繁琐的步骤. 编写代码,部署应用,部署数据库,申请域名,申请SSL证书,域名备案,到最终上线起码要几天时间. 作为一个不精通代码的业务玩家, ...

  8. 基于hexo+github搭建一个独立博客

    一直听说用hexo搭建一个拥有自己域名的博客是很酷炫的事情~,在这十一花上半个小时整个hexo博客岂不美哉. 使用Hexo吸引我的是,其简单优雅, 而且风格多变, 适合程序员搭建个人博客,而且支持多平 ...

  9. 搭建一个免费的,无限流量的Blog----github Pages和Jekyll入门

    喜欢写Blog的人,会经历三个阶段. 第一阶段,刚接触Blog,觉得很新鲜,试着选择一个免费空间来写. 第二阶段,发现免费空间限制太多,就自己购买域名和空间,搭建独立博客. 第三阶段,觉得独立博客的管 ...

随机推荐

  1. LXD 2.0 系列(一):LXD 入门

    LXD是提供了RESTAPI的LXC 容器管理器,主要是管理linux容器的第三方管理器.也许现在您还没有听说过,下面我们就来入门——介绍一下LXD 什么是 LXD ? 简单地说,LXD 就是一个提供 ...

  2. C++ 相关面试题汇总

    多态性与虚函数 (陈维兴教材) (1)所谓多态性就是不同对象在收到相同的消息时,产生不同的动作.直观的说,多态性是指用一个名字定义不同的函数,这些函数执行不同但又类似的操作,从而可以使用相同的方式来调 ...

  3. [Ext JS 4] 实战之 带week(星期)的日期选择控件

    前言 Ext JS 3 和 Ext JS 4中都有提供日期选择的组件(当然早期版本也有). 但是有一些日期选择的需求是要看到星期,就是日期中的哪一天是这一年的第几周. 遗憾的是Ext js 并没有提供 ...

  4. AVAudioPlayer播放在线音频文件

    AVAudioPlayer播放在线音频文件 一:原里: AVAudioPlayer是不支持播放在线音频的,但是AVAudioPlayer有一个 initWithData的方法:我们可以把在线音频转换为 ...

  5. 对hadoop 执行mapreduce时发生异常Illegal partition for的解决过程

    来自:http://blog.csdn.net/hezuoxiang/article/details/6878026 写了个mapreduce的JAVA程序,自定义了个partition class ...

  6. grid control 11.1.0.1 安装指南

    grid control 11.1.0.1 安装指南 废话少说,进入正题 系统版本号 [root@gridcontrol ~]# lsb_release -a LSB Version:    :bas ...

  7. js 向上取整、向下取整、四舍五入

      js 向上取整.向下取整.四舍五入 CreateTime--2018年4月14日11:31:21 Author:Marydon // 1.只保留整数部分(丢弃小数部分) parseInt(5.12 ...

  8. Python-搭建Nginx+Django环境

    1.安装 flup 模块 下载:http://projects.unbit.it/downloads/uwsgi-latest.tar.gz 安装:python setup.py install 2. ...

  9. mysql(表类型的选择)

    1.查询mysql所支持的存储引擎 第一种方法:show engines \G

  10. [翻译] C# 8.0 新特性 Redis基本使用及百亿数据量中的使用技巧分享(附视频地址及观看指南) 【由浅至深】redis 实现发布订阅的几种方式 .NET Core开发者的福音之玩转Redis的又一傻瓜式神器推荐

    [翻译] C# 8.0 新特性 2018-11-13 17:04 by Rwing, 1179 阅读, 24 评论, 收藏, 编辑 原文: Building C# 8.0[译注:原文主标题如此,但内容 ...