【接口】SpringBoot+接口开发(一)

时间:2023-02-16 09:41:38

一、接口的简单介绍

1.什么是接口:接口及服务;

2.接口的分类:(1)系统的内部接口;(2)第三方的外部接口;

3.简述接口原理图:

【接口】SpringBoot+接口开发(一)

4.接口协议:是指客户端跟服务器之间或者接口与接口间进行的通讯时必须要遵从的约定和要求;

互联网上 应用最为广泛的一种网络协议--http协议(超文本传输协议),因此最常见的就是http协议的接口.(webservice接口,dubbo接口等都是基于http协议)

5.http协议的组成

请求:
1.url统一资源定位符(接口地址)
2.请求方式(get,post,put,delete)
3.请求参数
4.请求格式
5.请求头:携带服务器关于客户端的一些信息
6.协议版本
响应:
1.响应的状态码
2.响应头:携带客关于服务器的一些信息给客户端
3.响应报文

6.接口的本质

(1) 接口就是服务,功能的实现,本质就是基于某协议下实现的一个函数,例如登录界面请求xxx/login.html地址的时候,通过路径
   映射,请求到login()函数进行处理.
  (2) 接口的传参对应了函数的参数(接口测试参数--函数参数),接口的响应报文对应了函数定义的返回值(接口响应报文--函数的返回值)

二、引入微服务架构Spring Boot,我们只需要导入我们本次需求需要的依赖包即可!

【接口】SpringBoot+接口开发(一)

【接口】SpringBoot+接口开发(一)

【接口】SpringBoot+接口开发(一)

 <!-- 引入springboot默认提供的一套依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
</parent>
<dependencies>
<!-- 提供了web模块的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
</dependencies>

注入:eclipse导入热部署依赖后需要勾选项

【接口】SpringBoot+接口开发(一)

导入mysql依赖:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>

三、代码实现简单接口功能如下:

1.get请求:http://IP:端口/user/login?username=xxx&password=123456
2.数据库验证,请求参数是否存在:username=xxx&password=123456,如果不存在提示检查信息,如果存在登录成功
2.json格式响应数据:{"status":"1","message":"登录成功"}

1.新建Application类,SpringBoot入口程序

package cn.bing.starter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan; /**Spring boot 入口启动程序,sprint boot内置了tomcat
* @author Administrator
*/
@ComponentScan(basePackages= {"cn.bing.api"})//扫描组件
@SpringBootApplication//定义sprintboot入口程序
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}

2.实现SQL数据库查询工具类

(1)请根据自己实现情况,配置连接数据库参数jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/my_test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
jdbc.username=sql-name
jdbc.password=sql-password

(2)实现SQlUtil工具类

package cn.bing.util;

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Properties; import cn.bing.pojo.User; public class SQLUtil {
/**
* 静态代码块加载后,用map来存储jdbc连接数据库的信息
*/
public static HashMap<String, String> map = new HashMap<String, String>();
static {
//加载properties文件获取连接SQL数据库的参数
Properties properties = new Properties();
try {
properties.load(new FileInputStream(new File("src/test/resources/jdbc.properties")));
} catch (Exception e) {
e.printStackTrace();
}
map.put("url", properties.getProperty("jdbc.url"));
map.put("name", properties.getProperty("jdbc.username"));
map.put("pwd", properties.getProperty("jdbc.password"));
} /**传入user进入数据库查询是否存在,返回大于1存在,返回0则不存在
* @param user
*/
public static int findSQL(User user) {
//根据SQL查询结果为数量num,假设没有查到为0
int num =0;
//取出需要查询的数据username和password
String username = user.getUsername();
String password = user.getPassword();
String sql ="select count(*) as number from user_test where name='"+username+"'"+"and password='"+password+"'";
Connection connection =null;
try {
//1.创建连接
connection = DriverManager.getConnection(map.get("url"),map.get("name"),map.get("pwd"));
//2.获得一个statement对象,将要执行的sql脚本封装到此对象中
PreparedStatement statement =connection.prepareStatement(sql);
ResultSet ResultSet = statement.executeQuery();
while(ResultSet.next()) {
num =ResultSet.getInt("number");
} } catch (SQLException e) {
e.printStackTrace();
}finally {
try {
connection.close();//关闭连接
} catch (SQLException e) {
e.printStackTrace();
}
}
return num;
}
}

3.新建user对象

package cn.bing.pojo;

public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
public User() {
super();
}
}

4.新建Result对象,响应时=>序列化为json格式返回

package cn.bing.pojo;
public class Result {
//接口返回状态标志:1:代表接口正常处理,返回成功; 0:代表处理异常,返回失败
private String status;
private String message;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Result(String status, String message) {
super();
this.status = status;
this.message = message;
}
public Result() {
super();
}
@Override
public String toString() {
return "Result [status=" + status + ", message=" + message + "]";
}
}

5.*控制器的实现类

package cn.bing.api;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import cn.bing.pojo.Result;
import cn.bing.pojo.User;
import cn.bing.util.SQLUtil; /**controller:控制器(实现请求分发,一般会在控制器当中定义接口)
* @author Administrator
*
*/
@RestController//控制器类
@RequestMapping("/user")//映射路径
public class UserController {
//登录接口 http://ip:端口/user/login
@RequestMapping(value="/login")
public Result login(User user) {
String username = user.getUsername();
String password = user.getPassword();
//1.用户名为空提示"用户名不能为空"
if(username==null || username.trim().length()==0) {
return new Result("0","用户名不能为空");
}
//2.密码为空,提示"密码不能为空"
if(password==null || password.trim().length()==0) {
return new Result("0","密码不能为空");
}
//3.用户名密码不为空的情况下jdbc完成数据库查询验证
if(username != null && password!=null) {
int num = SQLUtil.findSQL(user);
System.out.println("-------------------------"+num+"--------------------------------");
if(num>0) {
return new Result("1", "登录成功");
}
}
return new Result("0","请核对账密信息!");
}
}

四.运行Application类,启动SpringBoot程序,访问接口结果如下:

【接口】SpringBoot+接口开发(一)

【接口】SpringBoot+接口开发(一)

【接口】SpringBoot+接口开发(一)

【接口】SpringBoot+接口开发(一)

补充:数据库保存用户名及密码截图

【接口】SpringBoot+接口开发(一)

五、扩展:

1.如果@RequestMapping(value="/login",method=RequestMethod.GET,仅支持get访问

@RestController//控制器类
@RequestMapping("/user")//映射路径
public class UserController {
@RequestMapping(value="/login",method=RequestMethod.GET")
public Result login(User user) {
    ... ...
}
}

【接口】SpringBoot+接口开发(一)

2.如果@RequestMapping(value="/login",method=RequestMethod.POST),仅支持post访问

@RestController//控制器类
@RequestMapping("/user")//映射路径
public class UserController {
@RequestMapping(value="/login",method=RequestMethod.POST")
public Result login(User user) {
    ... ...
}
}

【接口】SpringBoot+接口开发(一)

3.规定传参格式:consumes="application/json"

4. @RequestBody需要把所有请求参数作为json解析,因此,不能包含key=value这样的写法在请求url中,所有的请求参数都是一个json

//@RequestBody(required=false)
Whether body content is required.
Default is true, leading to an exception thrown in case there is no body content. Switch this to false if you prefer null to be passed when the body content is null.
百度翻译:默认值为true,在没有正文内容的情况下会引发异常。如果您希望在正文内容为null时传递null,请将其切换为false。
@RestController//控制器类
@RequestMapping("/user")//映射路径
public class UserController {
@RequestMapping(value="/login",method=RequestMethod.POST,consumes="application/json")
public Result login(@RequestBody(required=false)User user) {
    ... ...
  }
}

六、未完待优化。。。。。

【接口】SpringBoot+接口开发(一)的更多相关文章

  1. 2、SpringBoot接口Http协议开发实战8节课(1-6)

    1.SpringBoot2.xHTTP请求配置讲解 简介:SpringBoot2.xHTTP请求注解讲解和简化注解配置技巧 1.@RestController and @RequestMapping是 ...

  2. 小D课堂【SpringBoot】接口Http协议开发实战

    ---恢复内容开始--- ====================2.SpringBoot接口Http协议开发实战 ============================= 1.SpringBoot ...

  3. Springboot接口简单实现生成MySQL插入语句

    Springboot接口简单实现调用接口生成MySQL插入语句 在实际测试中,有这样一个需求场景,比如:在性能压力测试中,可能需要我们事先插入数据库中一些相关联的数据. 我们在实际测试中,遇到问题,需 ...

  4. SpringBoot接口服务处理Whitelabel Error Page&lpar;转&rpar;

    To switch it off you can set server.error.whitelabel.enabled=false http://*.com/question ...

  5. 早期MyBatis开发与接口式Mybatis开发的简介

    早期MyBatis开发与接口式Mybatis开发的简介 一.早期版本的myBatis使用 导jar包            1.配置mybatis.xml的配置文件                1) ...

  6. PHP九大接口视频教程&lpar; 支付宝,QQ,短信接口&comma;微信接口开发&comma; 支付宝即时到账接口开发三级分销全套&rpar;

    PHP九大接口视频教程(  支付宝,QQ,短信接口,微信接口开发, 支付宝即时到账接口开发三级分销全套) 需要的联系我:QQ: 1844912514 PHP九大接口视频教程(  支付宝,QQ,短信接口 ...

  7. SpringBoot接口服务处理Whitelabel Error Page

    转载请注明来源:http://blog.csdn.net/loongshawn/article/details/50915979 <SpringBoot接口服务处理Whitelabel Erro ...

  8. Jmeter实时监控&plus;SpringBoot接口性能实战

    性能测试 Jmeter实时监控+SpringBoot接口性能实战 自动化 SpringBoot Java Jmeter实时监控+SpringBoot接口性能实战 一.实验目的及实验环境 1.1.实验目 ...

  9. springboot接口:CommandLineRunner

    springBoot接口:CommandLineRunner 一.作用: 在使用SpringBoot构建项目时,我们通常有一些预先数据的加载.那么SpringBoot提供了一个简单的方式来实现–Com ...

随机推荐

  1. scope&period;&dollar;apply是干嘛的

    开始用angular做项目的时候,一定碰到过$scope.$apply()方法,表面上看,这像是一个帮助你进行数据更新的方法,那么,它为何存在,我们又该如何使用它呢. JavaScript执行顺序 J ...

  2. 「thunar」给thunar增加搜索文件功能

    1.安装catfish sudo apt-get install catfish 2.配置thunar,添加[自定义动作] 打开 Thunar 后,点击 Edit -> Configure cu ...

  3. JSTL标签库中fmt标签,日期,数字的格式化

    首先介绍日期的格式化:(不要嫌多哦) JSTL格式化日期(本地化) 类似于数字和货币格式化,本地化环境还会影响生成日期和时间的方式. <%@ page pageEncoding="UT ...

  4. swift 2&period;0 与 OC 相比较,标签栏和导航栏书写的差别

    下面是swift书写的时候的两个方法,其实这里不是教大家怎么样写的这个问题,我是想通过这两个不同语言的进行的一个比较,向大家找他们之间“想法”上的一些相同点,这样子我们学习swift的时候,就可以更加 ...

  5. JavaScript配合button&period;onclick&lpar;&rpar;使用总结

    Html加载顺序是从上往下加载,如果script中含有引用js脚本,则应该将此script放在head标签里面,这样可是保证此页面都可以引用js脚本内容.如果想在script中设置button.onc ...

  6. &period;NET微服务调查结果

    .NET Core就是专门针对模块化的微服务架构而设计, 在2018年国庆时间展开.NET微服务的使用情况,本次调查我们总计收到了来自378个开发者的调查.从落地现状.架构体系.未来趋势等方面对微服务 ...

  7. Hadoop学习笔记(三):java操作Hadoop

    1. 启动hadoop服务. 2. hadoop默认将数据存储带/tmp目录下,如下图: 由于/tmp是linux的临时目录,linux会不定时的对该目录进行清除,因此hadoop可能就会出现意外情况 ...

  8. Windows 环境搭建Redis集群&lpar;win 64位&rpar;

    转: http://blog.csdn.net/zsg88/article/details/73715947 参考:https://www.cnblogs.com/tommy-huang/p/6240 ...

  9. freemarker时间转换

    Freemarker日期函数处理[转] (2012-08-01 14:32:13)   string(当和一个日期值一起使用) 这个内置标签用指定的格式把日期转换成字符串,(把默认的格式用FreeMa ...

  10. Docker Swarm学习教程

    原创作品,转载请注明出处:点我 Swarm介绍 Swarm是Docker公司在2014年12月初发布的一套较为简单的工具,用来管理Docker集群,它将一群Docker宿主机变成一个单一的,虚拟的主机 ...