1、SpringBoot2.xHTTP请求配置讲解

简介:SpringBoot2.xHTTP请求注解讲解和简化注解配置技巧

1、@RestController and @RequestMapping是springMVC的注解,不是springboot特有的

2、@RestController = @Controller+@ResponseBody

3、@SpringBootApplication = @Configuration+@EnableAutoConfiguration+@ComponentScan

localhost:8080

Demo1:

SampleControler.java

 package net.xdclass.demo.controller;

 import java.util.HashMap;
import java.util.Map; import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.*;
import org.springframework.web.bind.annotation.*; @RestController
public class SampleControler { @RequestMapping("/")
String home() {
return "Hello World!";
} /*public static void main(String[] args) throws Exception {
SpringApplication.run(SampleControler.class, args);
}*/ @RequestMapping("/test")
public Map<String, String> testMap(){
Map<String,String> map = new HashMap<>();
map.put("name", "xdclass");
return map;
} }

XdClassApplication.java

 package net.xdclass.demo;

 import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan; @SpringBootApplication //一个注解顶下面三个注解
/*@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan*/ //启动类
public class XdClassApplication { public static void main(String[] args) {
SpringApplication.run(XdClassApplication.class, args);
}
}

访问:http://localhost:8080/test

2、开发接口必备工具之PostMan接口调试工具介绍和使用

简介:模拟Http接口测试工具PostMan安装和讲解

1、接口调试工具安装和基本使用

2、下载地址:https://www.getpostman.com/

说明:

History可以保存历史请求

Collections:测试的请求没有问题后,可以保存到此处

点击save

同时可以使用Download方式将内容以json形式导出

3、SpringBoot基础HTTP接口GET请求实战

简介:讲解springboot接口,http的get请求,各个注解使用

1、GET请求

1、单一参数@RequestMapping(path = "/{id}", method = RequestMethod.GET)

1) public String getUser(@PathVariable String id ) {}

2)@RequestMapping(path = "/{depid}/{userid}", method = RequestMethod.GET) 可以同时指定多个提交方法

getUser(@PathVariable("depid") String departmentID,@PathVariable("userid") String userid)

3)一个顶俩

@GetMapping = @RequestMapping(method = RequestMethod.GET)

@PostMapping = @RequestMapping(method = RequestMethod.POST)

@PutMapping = @RequestMapping(method = RequestMethod.PUT)

@DeleteMapping = @RequestMapping(method = RequestMethod.DELETE)

4)@RequestParam(value = "name", required = true)

可以设置默认值,比如分页

4)@RequestBody 请求体映射实体类

需要指定http头为 content-type为application/json charset=utf-8

5)@RequestHeader 请求头,比如鉴权

@RequestHeader("access_token") String accessToken

6)HttpServletRequest request自动注入获取参数

例:GetController.java

 package net.xdclass.demo.controller;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import net.xdclass.demo.domain.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; //测试http协议的get请求
@RestController
public class GetController { private Map<String,Object> params = new HashMap<>(); /**
* 功能描述:测试restful协议,从路径中获取字段
* (协议的命名通常用字母组合和下划线方式,不用驼峰式命名)
* @param cityId
* @param userId
* @return
*/
@RequestMapping(path = "/{city_id}/{user_id}", method = RequestMethod.GET)
public Object findUser(@PathVariable("city_id") String cityId,
@PathVariable("user_id") String userId ){
params.clear(); params.put("cityId", cityId);
params.put("userId", userId); return params; } /**
* 功能描述:测试GetMapping
* @param from
* @param size
* @return
*/
@GetMapping(value="/v1/page_user1")
public Object pageUser(int from, int size ){
params.clear();
params.put("from", from);
params.put("size", size); return params; } /**
* 功能描述:默认值(defaultValue),是否必须的参数
* @param from
* @param size
* @return
*/
@GetMapping(value="/v1/page_user2")
public Object pageUserV2(@RequestParam(defaultValue="0",name="page") int from, int size ){ params.clear();
params.put("from", from);
params.put("size", size); return params; } /**
* 功能描述:bean对象传参
* 注意:1、注意需要指定http头为 content-type为application/json
* 2、使用body传输数据
* @param user
* @return
*/
@RequestMapping("/v1/save_user")
public Object saveUser(@RequestBody User user){
params.clear();
params.put("user", user);
return params;
} /**
* 功能描述:测试获取http头信息
* @param accessToken
* @param id
* @return
*/
@GetMapping("/v1/get_header")
public Object getHeader(@RequestHeader("access_token") String accessToken, String id){
params.clear();
params.put("access_token", accessToken);
params.put("id", id);
return params;
} @GetMapping("/v1/test_request")
public Object testRequest(HttpServletRequest request){
params.clear();
String id = request.getParameter("id");
params.put("id", id);
return params;
} }

User.java

 package net.xdclass.demo.domain;

 public class User {

     private int age;

     private String pwd;

     private String phone;

     public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getPwd() {
return pwd;
} public void setPwd(String pwd) {
this.pwd = pwd;
} public String getPhone() {
return phone;
} public void setPhone(String phone) {
this.phone = phone;
} public User() {
super();
} public User(int age, String pwd, String phone) {
super();
this.age = age;
this.pwd = pwd;
this.phone = phone;
} }

4、SpringBoot基础HTTP接口POST,PUT,DELETE请求实战

简介:讲解http请求post,put, delete提交方式

代码示例:

 package net.xdclass.demo.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController; //测试http协议的post,del,put请求
@RestController
public class OtherHttpController { private Map<String,Object> params = new HashMap<>(); /**
* 功能描述:测试PostMapping
* @param accessToken
* @param id
* @return
*/
@PostMapping("/v1/login")
public Object login(String id, String pwd){
params.clear();
params.put("id", id);
params.put("pwd", pwd);
return params;
} @PutMapping("/v1/put")//常用于更新
public Object put(String id){
params.clear();
params.put("id", id);
return params;
} @DeleteMapping("/v1/del")//删除操作
public Object del(String id){
params.clear();
params.put("id", id);
return params;
} }

5、常用json框架介绍和Jackson返回结果处理

简介:介绍常用json框架和注解的使用,自定义返回json结构和格式

1、常用框架 阿里 fastjson,谷歌gson等

JavaBean序列化为Json,性能:Jackson > FastJson > Gson > Json-lib 同个结构

Jackson、FastJson、Gson类库各有优点,各有自己的专长

空间换时间,时间换空间

2、jackson处理相关自动

指定字段不返回:@JsonIgnore

User.java

测试:

前台返回信息:

指定日期格式:@JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8")

空字段不返回:@JsonInclude(Include.NON_NUll)

指定别名:@JsonProperty

代码示例:

User.java

 package net.xdclass.demo.domain;

 import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty; public class User { private int age; @JsonIgnore//前台不返回该字段信息,保护数据安全
private String pwd; @JsonProperty("account")
@JsonInclude(Include.NON_NULL)
private String phone; @JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8")
private Date createTime; public Date getCreateTime() {
return createTime;
} public void setCreateTime(Date createTime) {
this.createTime = createTime;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getPwd() {
return pwd;
} public void setPwd(String pwd) {
this.pwd = pwd;
} public String getPhone() {
return phone;
} public void setPhone(String phone) {
this.phone = phone;
} public User() {
super();
} public User(int age, String pwd, String phone, Date createTime) {
super();
this.age = age;
this.pwd = pwd;
this.phone = phone;
this.createTime = createTime;
}
}

测试代码:

     @GetMapping("/testjson")
public Object testjson(){ return new User(11, "abc123", "1001000", new Date());
}

前台返回结果:

6、SpringBoot2.x目录文件结构讲解

简介:讲解SpringBoot目录文件结构和官方推荐的目录规范

1、目录讲解

src/main/java:存放代码

src/main/resources

static: 存放静态文件,比如 css、js、image, (访问方式 http://localhost:8080/js/main.js)

templates:存放静态页面jsp,html,tpl

config:存放配置文件,application.properties

resources:

2、引入依赖 Thymeleaf

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

注意:如果不引入这个依赖包,html文件应该放在默认加载文件夹里面,

比如resources、static、public这个几个文件夹,才可以访问(这三个文件夹中的内容可以直接访问)

例如,要访问templates下的index.html

index.html:

访问:http://localhost:8080/api/v1/gopage

浏览器结果:

3、同个文件的加载顺序,静态资源文件

Spring Boot 默认会挨个从

META/resources > resources > static > public  里面找是否存在相应的资源,如果有则直接返回。

4、默认配置

1)官网地址:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-static-content

2)spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

自定义文件夹代码示例:

在src/main/resources文件夹下创建application.properties

spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/test/

访问test文件夹下的test3.js

在配置文件中,加入classpath:/test/,访问:http://localhost:8080/test3.js

浏览器结果:

若不加入该内容,浏览器会提示错误信息,无法访问

5、静态资源文件存储在CDN

面试题:如何加快网站的访问速度?

答:大型公司通常将静态资源文件存储在CDN,响应快。SpringBoot搭建的项目通常会前后端分离。

2、SpringBoot接口Http协议开发实战8节课(1-6)的更多相关文章

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

    7.SpringBoot2.x文件上传实战 简介:讲解HTML页面文件上传和后端处理实战 1.讲解springboot文件上传 MultipartFile file,源自SpringMVC 1)静态页 ...

  2. 小D课堂 - 零基础入门SpringBoot2.X到实战_第2节 SpringBoot接口Http协议开发实战_6、SpringBoot2.xHTTP请求配置讲解

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

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

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

  4. centos mysql 实战 第一节课 安全加固 mysql安装

    centos mysql  实战  第一节课   安全加固  mysql安装 percona名字的由来=consultation 顾问+performance 性能=per  con  a mysql ...

  5. 11、Logback日志框架介绍和SpringBoot整合实战 2节课

    1.新日志框架LogBack介绍     简介:日志介绍和新日志框架Logback讲解 1.常用处理java的日志组件 slf4j,log4j,logback,common-logging 等     ...

  6. SpringBoot整合定时任务和异步任务处理 3节课

    1.SpringBoot定时任务schedule讲解   定时任务应用场景: 简介:讲解什么是定时任务和常见定时任务区别 1.常见定时任务 Java自带的java.util.Timer类        ...

  7. SpringBoot2.x整合Redis实战 4节课

    1.分布式缓存Redis介绍      简介:讲解为什么要用缓存和介绍什么是Redis,新手练习工具 1.redis官网 https://redis.io/download          2.新手 ...

  8. SpringBoot微服务电商项目开发实战 --- api接口安全算法、AOP切面及防SQL注入实现

    上一篇主要讲了整个项目的子模块及第三方依赖的版本号统一管理维护,数据库对接及缓存(Redis)接入,今天我来说说过滤器配置及拦截设置.接口安全处理.AOP切面实现等.作为电商项目,不仅要求考虑高并发带 ...

  9. SpringBoot微服务电商项目开发实战 --- Redis缓存雪崩、缓存穿透、缓存击穿防范

    最近已经推出了好几篇SpringBoot+Dubbo+Redis+Kafka实现电商的文章,今天再次回到分布式微服务项目中来,在开始写今天的系列五文章之前,我先回顾下前面的内容. 系列(一):主要说了 ...

随机推荐

  1. BZOJ2199[Usaco2011 Jan]奶牛议会——2-SAT+tarjan缩点

    题目描述 由于对Farmer John的领导感到极其不悦,奶牛们退出了农场,组建了奶牛议会.议会以“每头牛 都可以获得自己想要的”为原则,建立了下面的投票系统: M只到场的奶牛 (1 <= M ...

  2. BZOJ2716 [Violet]天使玩偶(cdq分治+树状数组)

    非常裸的KD-tree.然而我没学啊. 考虑如何离线求一个点在平面中的曼哈顿最近点. 绝对值显得有点麻烦,于是把绝对值拆开分情况讨论一波.对于横坐标小于该点的,记录对于纵坐标的前缀x+y最大值和后缀x ...

  3. ACG图片站\python爬虫\LAMP环境

    最近突然对web很感兴趣,碰巧看到阿里云服务器学生价十块钱一个月,果断买了一个自己搭建了一个网站. 网址 这里 LAMP环境就搭建了好久,linux+apache2+mysql+php,都是开源的软件 ...

  4. day25 面向对象引子

    面向对象编程所谓模子就是 类 抽象的,能知道什么属性,但是不知道属性具体值一切都是对象 有具体值 属性和技能都是根据类 模子来规范 # 人狗大战 # 角色模型 # 人的模型 def Person(na ...

  5. 超越LLMNR /NBNS欺骗 - 利用Active Directory集成的DNS

    利用名称解析协议中的缺陷进行内网渗透是执行中间人(MITM)攻击的常用技术.有两个特别容易受到攻击的名称解析协议分别是链路本地多播名称解析(LLMNR)和NetBIOS名称服务(NBNS).攻击者可以 ...

  6. Java:终于找到了在alloy中的JFileChooser中的弹出式菜单不显示文字的解决办法

    alloy界面可以说是我写过的最漂亮的一种JAVA界面. 可惜不知为什么,至从几年前推出1.4版后,就再也没有更新了. 随着java版本的升级,一直很担心alloy有一天不再适用于java的最新版. ...

  7. javascript:location.reload()和location.replace()的区别,及对图片缓存的影响。

    有段时间没有清理IE的临时文件(缓存文件),在我清理的时候,我突然发现一个问题. 我打开的一个网站,图片默认缓存一个月的,但我发现,当我上传图片或删除图片之后,图片重新缓存,也就意味着,在我上传新图片 ...

  8. Linux下,根据FHS定义出来的每个目录的作用

    (下表摘自<鸟哥的Linux的私房菜>) 在Linux下,根据FHS定义出来的每个目录应该放置的档案内容为: 目录 应放置档案内容 / 根目录 root (/),一般建议在根目录底下只接目 ...

  9. Educational Codeforces Round 42 (Rated for Div. 2) D. Merge Equals

    http://codeforces.com/contest/962/problem/D D. Merge Equals time limit per test 2 seconds memory lim ...

  10. 通过纯真IP地址实现根据用户地址显示信息

    为了实现中关村在线商品报价中通过用户的地理位置信息显示相应的报价. 示例地址:http://detail.zol.com.cn/lens/index224693.shtml 现把我做的使用asp.ne ...