【Spring】构建Springboot项目 实现restful风格接口

项目代码如下:

 1 package hello;
 2
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5
 6 @SpringBootApplication  // same as @Configuration @EnableAutoConfiguration @ComponentScan
 7
 8 public class Application {
 9
10     public static void main(String[] args) {
11          SpringApplication.run(Application.class, args);
12     }
13
14 }
 1 package hello;
 2
 3 public class Greeting {
 4 private  long id;
 5 private  String content;
 6 public Greeting(long id, String content) {
 7     super();
 8     this.id = id;
 9     this.content = content;
10 }
11 public long getId() {
12     return id;
13 }
14 public void setId(long id) {
15     this.id = id;
16 }
17 public String getContent() {
18     return content;
19 }
20 public void setContent(String content) {
21     this.content = content;
22 }
23
24 }
 1 package hello;
 2
 3 import java.util.concurrent.atomic.AtomicLong;
 4
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 import org.springframework.web.bind.annotation.RequestParam;
 7 import org.springframework.web.bind.annotation.RestController;
 8
 9 @RestController // shorthand for @Controller and @ResponseBody rolled together
10 public class GreetingController {
11
12     private static final String template="Hello,%s!";
13     private final AtomicLong counter=new AtomicLong();
14
15     @RequestMapping("/greeting")
16     public Greeting greeting(@RequestParam(value="name",defaultValue="World")String name){
17         System.out.println("-------------------------");
18         return new Greeting(counter.incrementAndGet(),String.format(template, name));
19     }
20 }
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 4     <modelVersion>4.0.0</modelVersion>
 5
 6     <groupId>com.slp</groupId>
 7     <artifactId>restSpringDemo1</artifactId>
 8     <version>0.1.0</version>
 9
10     <parent>
11         <groupId>org.springframework.boot</groupId>
12         <artifactId>spring-boot-starter-parent</artifactId>
13         <version>1.4.1.RELEASE</version>
14     </parent>
15
16     <dependencies>
17         <dependency>
18             <groupId>org.springframework.boot</groupId>
19             <artifactId>spring-boot-starter-web</artifactId>
20         </dependency>
21         <dependency>
22             <groupId>org.springframework.boot</groupId>
23             <artifactId>spring-boot-starter-test</artifactId>
24             <scope>test</scope>
25         </dependency>
26         <dependency>
27             <groupId>com.jayway.jsonpath</groupId>
28             <artifactId>json-path</artifactId>
29             <scope>test</scope>
30         </dependency>
31     </dependencies>
32
33     <properties>
34         <java.version>1.8</java.version>
35     </properties>
36
37
38     <build>
39         <plugins>
40             <plugin>
41                 <groupId>org.springframework.boot</groupId>
42                 <artifactId>spring-boot-maven-plugin</artifactId>
43             </plugin>
44         </plugins>
45     </build>
46
47     <repositories>
48         <repository>
49             <id>spring-releases</id>
50             <url>https://repo.spring.io/libs-release</url>
51         </repository>
52     </repositories>
53     <pluginRepositories>
54         <pluginRepository>
55             <id>spring-releases</id>
56             <url>https://repo.spring.io/libs-release</url>
57         </pluginRepository>
58     </pluginRepositories>
59 </project>

在Application.java中run as java application 出现:

 1  .   ____          _            __ _ _
 2  /\\ / ___‘_ __ _ _(_)_ __  __ _ \ \ \  3 ( ( )\___ | ‘_ | ‘_| | ‘_ \/ _` | \ \ \  4  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
 5   ‘  |____| .__|_| |_|_| |_\__, | / / / /
 6  =========|_|==============|___/=/_/_/_/
 7  :: Spring Boot ::        (v1.4.1.RELEASE)
 8
 9 2016-10-13 11:19:16.510  INFO 9864 --- [           main] hello.Application                        : Starting Application on QH-20160418YQMB with PID 9864 (started by sanglp in D:\rest风格的apring项目\restSpringDemo1)
10 2016-10-13 11:19:16.525  INFO 9864 --- [           main] hello.Application                        : No active profile set, falling back to default profiles: default
11 2016-10-13 11:19:16.713  INFO 9864 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot[email protected]72f926e6: startup date [Thu Oct 13 11:19:16 CST 2016]; root of context hierarchy
12 2016-10-13 11:19:19.691  INFO 9864 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
13 2016-10-13 11:19:19.710  INFO 9864 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
14 2016-10-13 11:19:19.710  INFO 9864 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.35
15 2016-10-13 11:19:20.148  INFO 9864 --- [ost-startStop-1] org.apache.jasper.servlet.TldScanner     : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
16 2016-10-13 11:19:20.148  INFO 9864 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
17 2016-10-13 11:19:20.148  INFO 9864 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3451 ms
18 2016-10-13 11:19:20.382  INFO 9864 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: ‘dispatcherServlet‘ to [/]
19 2016-10-13 11:19:20.398  INFO 9864 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: ‘characterEncodingFilter‘ to: [/*]
20 2016-10-13 11:19:20.398  INFO 9864 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: ‘hiddenHttpMethodFilter‘ to: [/*]
21 2016-10-13 11:19:20.398  INFO 9864 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: ‘httpPutFormContentFilter‘ to: [/*]
22 2016-10-13 11:19:20.398  INFO 9864 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: ‘requestContextFilter‘ to: [/*]
23 2016-10-13 11:19:20.866  INFO 9864 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot[email protected]72f926e6: startup date [Thu Oct 13 11:19:16 CST 2016]; root of context hierarchy
24 2016-10-13 11:19:20.986  INFO 9864 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)
25 2016-10-13 11:19:20.986  INFO 9864 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
26 2016-10-13 11:19:20.986  INFO 9864 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
27 2016-10-13 11:19:21.033  INFO 9864 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
28 2016-10-13 11:19:21.033  INFO 9864 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
29 2016-10-13 11:19:21.095  INFO 9864 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
30 2016-10-13 11:19:21.307  INFO 9864 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
31 2016-10-13 11:19:21.463  INFO 9864 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
32 2016-10-13 11:19:21.479  INFO 9864 --- [           main] hello.Application                        : Started Application in 6.497 seconds (JVM running for 7.83)
33 2016-10-13 11:21:46.570  INFO 9864 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet ‘dispatcherServlet‘
34 2016-10-13 11:21:46.570  INFO 9864 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet ‘dispatcherServlet‘: initialization started
35 2016-10-13 11:21:46.622  INFO 9864 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet ‘dispatcherServlet‘: initialization completed in 51 ms

表示启动成功,这是就可以访问了 http://localhost:8080/greeting?name=xxb

会出现如下结果:

{"id":3,"content":"Hello,xuxiaobo!"}

这是一个纯java的项目,不需要启动tomcat也可以执行访问

First you set up a basic build script. You can use any build system you like when building apps with Spring, but the code you need to work with Maven is included here. If you’re not familiar with Maven, refer to Building Java Projects with Maven.

Create the directory structure

In a project directory of your choosing, create the following subdirectory structure; for example, with mkdir -p src/main/java/hello on *nix systems:

└── src
    └── main
        └── java
            └── hello

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>org.springframework</groupId>
    <artifactId>gs-rest-service</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <scope>test</scope>
        </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-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>
</project>

The Spring Boot Maven plugin provides many convenient features:

  • It collects all the jars on the classpath and builds a single, runnable "über-jar", which makes it more convenient to execute and transport your service.
  • It searches for the public static void main() method to flag as a runnable class.
  • It provides a built-in dependency resolver that sets the version number to match Spring Boot dependencies. You can override any version you wish, but it will default to Boot’s chosen set of versions.
时间: 2024-10-08 20:05:27

【Spring】构建Springboot项目 实现restful风格接口的相关文章

SpringBoot2.0基础案例(01):环境搭建和RestFul风格接口

一.SpringBoot 框架的特点 1.SpringBoot2.0 特点 1)SpringBoot继承了Spring优秀的基因,上手难度小 2)简化配置,提供各种默认配置来简化项目配置 3)内嵌式容器简化Web项目,简化编码 Spring Boot 则会帮助开发着快速启动一个 web 容器,在 Spring Boot 中,只需要在 pom 文件中添加如下一个 starter-web 依赖即可. <dependency> <groupId>org.springframework.b

spring boot 快速搭建 基于 Restful 风格的微服务

使用 spring boot 快速搭建 基于  Restful 风格的微服务, 无spring 配置文件,纯java 工程,可以快速发布,调试项目 1.创建一个maven 工程 2. 导入如下配置 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="htt

SpringBoot入门基础:构建SpringBoot项目及启动器讲解(二)

一. 使用Spring开发一个"HelloWorld"的web应用 创建一个web项目并且导入相关的jar包.SpringMVC Servlet 创建一个web.xml 编写一个控制类(Controller) 需要一个部署web应用的服务器,如tomcat 二. SpringBoot特点 SpringBoot设计目的是用来简化新Spring应用的初始搭建以及开发过程 嵌入的tomcat,无需部署war文件 SpringBoot并不是对Spring功能上的增强,而是提供了一种快速使用Sp

restful风格接口和spring的运用

Restful风格的API是一种软件架构风格,设计风格而不是标准,只是提供了一组设计原则和约束条件.它主要用于客户端和服务器交互类的软件.基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制. 在Restful风格中,用户请求的url使用同一个url而用请求方式:get,post,delete,put...等方式对请求的处理方法进行区分,这样可以在前后台分离式的开发中使得前端开发人员不会对请求的资源地址产生混淆和大量的检查方法名的麻烦,形成一个统一的接口. 在Restful风格中,现

linux服务器中Jenkins集成git、Gradle持续构建Springboot项目

Jenkins是用java编写的开源持续集成工具,目前被国内外各公司广泛使用.本章教大家如何在linux服务器中使用Jenkins自动发布一个可作为linux服务发布的Springboot项目. 自动构建需要经过如下步骤:从git仓库下载代码.使用Gradle进行构建.使用SSH推送到另一台linux服务器.项目作为linux服务启动.本章将逐条仔细讲解. 一.获得一台linux服务器 要在linux下搞持续构建,首先你得先有一台linux服务器,作为小白,手头的机器肯定都是windows的,搞

使用Maven插件构建SpringBoot项目,生成Docker镜像push到DockerHub上

一个用于构建和推送Docker镜像的Maven插件. 使用Maven插件构建Docker镜像,将Docker镜像push到DockerHub上,或者私有仓库,上一篇文章是手写Dockerfile,这篇文章借助开源插件docker-maven-plugin 进行操作 以下操作.默认你已经阅读过我上一篇文章: Docker 部署 SpringBoot 项目整合 Redis 镜像做访问计数Demo http://www.ymq.io/2018/01/11/Docker-deploy-spring-bo

thinkphp5设置项目为restful风格

我用的是thinkphp5.0.16 环境是 LAMP(linux+apache+mysql5.6+php5.6) 首先去官网下载一个thinkphp5.0.16的完整版,然后放到apache指定的项目运行目录下 然后下一步也就是第一步,我们先开启路由完整匹配模式,这个配置在config.php这个文件里. // 路由使用完整匹配'route_complete_match' => true, 设置成true就可以 下一步就开始创建你的restful风格的目录了比如我想设置的前台模块的登录路由为a

利用Jenkins实现jdk11+Maven构建springboot项目

目录 原理图 前期准备 Jdk11安装 Jenkins安装 Maven安装 Jenkins的设置 插件安装 变量配置 搭建项目 1.通用配置 2.源码管理 3.构建触发 4.Maven的构建选项 5.构建后操作 原理图 鉴于网上很多资料一上来直接就开干了,这里我先把这几天所经历的理解化成一张图,以便后续内容更加容易理解. 由上图可以清晰的看到,只要我们再本地的Idea提交代码到GitHub远程仓库,随后Github触发一个web hook(简单来说就是一个Http请求).随后Jenkins接收到

在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