Spring Boot - RESTful Web服务

Spring Boot - RESTful Web服务 首页 / Spring Boot入门教程 / Spring Boot - RESTful Web服务

创建一个简单的Spring Boot Web应用程序并编写一个控制器类文件,该文件用于重定向到HTML文件以使用RESTful Web服务。

无涯教程需要在构建配置文件中添加Spring Boot启动器Thymeleaf和Web依赖项。

对于Maven用户,在pom.xml文件中添加以下依赖项。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

对于Gradle用户,将以下依赖项添加到build.gradle文件中-

compile group: org.springframework.boot', name: spring-boot-starter-thymeleaf'
compile(‘org.springframework.boot:spring-boot-starter-web')

@Controller类文件的代码在下面给出-

无涯教程网

@Controller
public class ViewController {
}

您可以定义Request URI方法以重定向到HTML文件,如下所示-

@RequestMapping(“/view-products”)
public String viewProducts() {
   return view-products”;
}
@RequestMapping(“/add-products”)
public String addProducts() {
   return add-products”;
}

此API http:// localhost:9090/products 应该返回以下JSON作为响应,如下所示-

[
   {
      "id": "1",
      "name": "Honey"
   },
   {
      "id": "2",
      "name": "Almond"
   }
]

现在,在类路径的模板目录下创建一个view-products.html文件。

在HTML文件中,无涯教程添加了jQuery库并编写了代码以在页面加载时使用RESTful Web服务。

<script src = "https://ajax.Learnfkapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script>
$(document).ready(function(){
   $.getJSON("http://localhost:9090/products", function(result){
      $.each(result, function(key,value) {
         $("#productsJson").append(value.id+" "+value.name+" ");
      }); 
   });
});
</script>

POST方法和此URL http:// localhost:9090/products 应该包含以下"请求正文"和"响应正文"。

请求主体的代码如下-

{
   "id":"3",
   "name":"Ginger"
}

响应主体的代码如下-

Product is created successfully

现在,在类路径的模板目录下创建add-products.html文件。

在HTML文件中,无涯教程添加了jQuery库,并编写了单击该按钮将表单提交到RESTful Web服务的代码。

<script src = "https://ajax.Learnfkapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
   $(document).ready(function() {
      $("button").click(function() {
         var productmodel = {
            id : "3",
            name : "Ginger"
         };
         var requestJSON = JSON.stringify(productmodel);
         $.ajax({
            type : "POST",
            url : "http://localhost:9090/products",
            headers : {
               "Content-Type" : "application/json"
            },
            data : requestJSON,
            success : function(data) {
               alert(data);
            },
            error : function(data) {
            }
         });
      });
   });
</script>

完整的代码如下。

Maven-pom.hml

<?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>com.learnfk</groupId>
   <artifactId>demo</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>demo</name>
   <description>Demo project for Spring Boot</description>

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

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <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>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>
   </dependencies>

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

下面给出了Gradle – build.gradle的代码-

buildscript {
   ext {
      springBootVersion = 1.5.8.RELEASE'
   }
   repositories {
      mavenCentral()
   }
   dependencies {
      classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
   }
}

apply plugin: java'
apply plugin: eclipse'
apply plugin: org.springframework.boot'

group = com.learnfk'
version = 0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
   mavenCentral()
}

dependencies {
   compile(‘org.springframework.boot:spring-boot-starter-web')
   compile group: org.springframework.boot', name: spring-boot-starter-thymeleaf'
   testCompile(‘org.springframework.boot:spring-boot-starter-test')
}

下面给出的控制器类文件– ViewController.java在下面给出-

package com.learnfk.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ViewController {
   @RequestMapping(“/view-products”)
   public String viewProducts() {
      return view-products”;
   }
   @RequestMapping(“/add-products”)
   public String addProducts() {
      return add-products”;   
   }   
}

下面给出了view-products.html文件-

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "ISO-8859-1"/>
      <title>View Products</title>
      <script src = "https://ajax.Learnfkapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      
      <script>
         $(document).ready(function(){
            $.getJSON("http://localhost:9090/products", function(result){
               $.each(result, function(key,value) {
                  $("#productsJson").append(value.id+" "+value.name+" ");
               }); 
            });
         });
      </script>
   </head>
   
   <body>
      <div id = "productsJson"> </div>
   </body>
</html>

add-products.html文件在下面给出-

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "ISO-8859-1" />
      <title>Add Products</title>
      <script src = "https://ajax.Learnfkapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      
      <script>
         $(document).ready(function() {
            $("button").click(function() {
               var productmodel = {
                  id : "3",
                  name : "Ginger"
               };
               var requestJSON = JSON.stringify(productmodel);
               $.ajax({
                  type : "POST",
                  url : "http://localhost:9090/products",
                  headers : {
                     "Content-Type" : "application/json"
                  },
                  data : requestJSON,
                  success : function(data) {
                     alert(data);
                  },
                  error : function(data) {
                  }
               });
            });
         });
      </script>
   </head>
   
   <body>
      <button>Click here to submit the form</button>
   </body>
</html>

下面给出了主要的Spring Boot Application类文件-

package com.learnfk.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

现在,您可以创建一个可执行的JAR文件,并使用以下Maven或Gradle命令运行Spring Boot应用程序。

对于Maven,请使用以下命令-

mvn clean install

在" BUILD SUCCESS"之后,您可以在目标目录下找到JAR文件。

对于Gradle,请使用以下命令-

gradle clean build

在" BUILD SUCCESSFUL"之后,您可以在build/libs目录下找到JAR文件。

使用以下命令运行JAR文件-

java jar <JARFILE> 

现在,该应用程序已在Tomcat端口8080上启动。

Started Application on Tomcat Port_8080

现在在您的Web浏览器中点击URL,您可以看到如下所示的输出-

http:// localhost:8080/view-products

1Honey_2Almond

http:// localhost:8080/add-products

Submit Form Spring Boot

现在,单击按钮单击此处提交表单,您将看到如下所示的结果-

Submit Form Spring Boot Output Window

现在,点击查看产品URL并查看创建的产品。

http:// localhost:8080/view-products

1Honey 2Almond 3Ginger

Angular JS

要使用Angular JS来使用API​​,可以使用下面给出的示例-使用以下代码创建使用GET API的Angular JS控制器-http:// localhost:9090/products-

angular.module('demo', [])
.controller('Hello', function($scope, $http) {
   $http.get('http://localhost:9090/products').
   then(function(response) {
      $scope.products = response.data;
   });
});

使用以下代码创建Angular JS控制器以使用POST API-http:// localhost:9090/products-

angular.module('demo', [])
.controller('Hello', function($scope, $http) {
   $http.post('http://localhost:9090/products',data).
   then(function(response) {
      console.log("Product created successfully");
   });
});

注意-Post方法数据代表JSON格式的Request主体,用于创建产品。

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

趣谈网络协议 -〔刘超〕

邱岳的产品实战 -〔邱岳〕

性能工程高手课 -〔庄振运〕

Java业务开发常见错误100例 -〔朱晔〕

OAuth 2.0实战课 -〔王新栋〕

快手 · 音视频技术入门课 -〔刘歧〕

现代C++20实战高手课 -〔卢誉声〕

深入拆解消息队列47讲 -〔许文强〕

结构思考力 · 透过结构看思考 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)