Restful接口开发(2):RestController详解-基础

2024-05-24 10:48

本文主要是介绍Restful接口开发(2):RestController详解-基础,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、日志级别

使用commons.logging记录日志
1.日志级别

 TRACE<DEBUG<INFO<WARN<ERROR<FATAL

2.配置文件..demo\src\main\resources\application.yml配置日志输出级别为TRACE


spring:jackson:date-format: yyyy-MM-dd #如果使用字符串型表示,用这行设置timezone: GMT+8serialization:write-dates-as-timestamps: false #使用数值timestamp表示日期,false表示不用这数字;true表示用数字
logging:file: target/app.loglevel:ROOT: WARNcom.example.demo: TRACE

备注:
(1)配置日志级别:TRACE<DEBUG<INFO<WARN<ERROR<FATAL
(2)com.example.demo 为对应包的名称,这个依据自己包名修改

3.代码

package com.example.demo;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.*;@RestController
public class HelloworldController {//创建日志静态对象private static final Log log= LogFactory.getLog(HelloworldController.class);//    @GetMapping@RequestMapping("/helloworld")public Map<String,Object> sayHelloworld(){Map<String,Object> result=new HashMap<>();result.put("message","hello world!");result.put("message2","hello world 2!");result.put("message3","hello world 3!");return result;}/*** 获取所有电视节目列表* @return*/@RequestMapping("/getall")public List<TvSeriesDto> getAll(){//TRACEif(log.isTraceEnabled()){log.trace("getAll函数被调用了!");}//ERRORtry{}catch (Exception e){if(log.isErrorEnabled()){log.error("出错了:"+e);}}List<TvSeriesDto> list=new ArrayList<>();Calendar calendar=Calendar.getInstance();calendar.set(2016,Calendar.OCTOBER,12,2,0);list.add( new TvSeriesDto(1,"WestWorld",1,calendar.getTime()));return list;}}


备注:

(1)输出日志,先判断是否需要输出;
(2)日志输出结果:
2019-09-03 00:53:20.585 TRACE 9352 --- [nio-8080-exec-1] com.example.demo.HelloworldController    : getAll函数被调用了!

(3)日志输出位置:target/app.log
 
4.    修改日志级别为WARN
 
访问网站http://localhost:8080/getall,结果日志什么也没有出。

二、API测试工具postman

1.下载地址https://www.getpostman.com/apps

2.安装
 
3.测试
选择post,输入url然后点击发送,会返回服务器数据。
 

三、RestController获取各种数据(增删改查)

1.get(查询)
 (1)代码

    /*** 1.GET获取所有电视节目列表* @return*/
//    @RequestMapping("/getall")@GetMapping()public List<TvSeriesDto> getAll(){//TRACEif(log.isTraceEnabled()){log.trace("getAll函数被调用了!");}//ERRORtry{}catch (Exception e){if(log.isErrorEnabled()){log.error("出错了:"+e);}}List<TvSeriesDto> list=new ArrayList<>();Calendar calendar=Calendar.getInstance();calendar.set(2016,Calendar.OCTOBER,12,2,0);list.add( new TvSeriesDto(1,"WestWorld",1,calendar.getTime()));return list;}/*** 创建返回Person of Interest* @return*/
private TvSeriesDto createPoi(){Calendar calendar=Calendar.getInstance();calendar.set(2016,Calendar.OCTOBER,12,2,0);return new TvSeriesDto(1,"Person of Interest",1,calendar.getTime());}/*** 创建返回WestWorld实例* @return*/
private TvSeriesDto createWestWorld(){Calendar calendar=Calendar.getInstance();calendar.set(2015,Calendar.OCTOBER,2,2,0);return new TvSeriesDto(2,"WestWorld",1,calendar.getTime());}

(2)测试
 

2.post(插入)

 (1)代码

/*** 2.post方法* @param tvSeriesDto* @return*/
@PostMapping
private TvSeriesDto insertOne(@RequestBody TvSeriesDto tvSeriesDto){if(log.isTraceEnabled()){log.trace("适应post添加TvSeriesDto对象到数据库代码,传进来的参数是:"+tvSeriesDto);}//TODO:传递数据tvSeriesDto.setId(99999);return tvSeriesDto;
}

(2)修改类TvSeriesDto.java,重写方法toString

(3)点击测试通过!
-》配置HEADER
 
-》配置body

-》结果

3.Put(更新)
 (1)代码

    /*** 3.更新* @param id* @param tvSeriesDto 输入参数类* @return*/@PutMapping("/{id}")public TvSeriesDto updateOne(@PathVariable int id,@RequestBody TvSeriesDto tvSeriesDto){if(log.isTraceEnabled()){log.trace("updateOne"+id);}if(id==101||id ==102){//todo: 根据tvSeriesDto的内容更新数据库,更新后返回新值return createPoi();}else {
//            throw new ResourceNotFoundException("404",new Re);return null;}}

(2)测试

-》更新id=101

-》更新id=103

4. delete类似get(删除)
(1)代码

/*** 4.删除* @param id* @param request* @param deleteReason* @return* @throws Exception*/
@DeleteMapping("/{id}")
public Map<String,String> deleteOne(@PathVariable int id, HttpServletRequest request,@RequestParam(value="delete_reason",required = false) String deleteReason) throws Exception{if(log.isTraceEnabled()){log.trace("deleteOne:"+id);}Map<String,String> result=new HashMap<>();if(id==101){//TODO:执行删除的代码result.put("message","#101被"+request.getRemoteAddr()+"删除。(原因:"+deleteReason+")");}else if(id ==102){throw new RuntimeException("#102不能删除");}else{//不存在}return result;}


(2)测试结果,删除101
 

 

这篇关于Restful接口开发(2):RestController详解-基础的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/998191

相关文章

SpringBoot3.4配置校验新特性的用法详解

《SpringBoot3.4配置校验新特性的用法详解》SpringBoot3.4对配置校验支持进行了全面升级,这篇文章为大家详细介绍了一下它们的具体使用,文中的示例代码讲解详细,感兴趣的小伙伴可以参考... 目录基本用法示例定义配置类配置 application.yml注入使用嵌套对象与集合元素深度校验开发

Python中的Walrus运算符分析示例详解

《Python中的Walrus运算符分析示例详解》Python中的Walrus运算符(:=)是Python3.8引入的一个新特性,允许在表达式中同时赋值和返回值,它的核心作用是减少重复计算,提升代码简... 目录1. 在循环中避免重复计算2. 在条件判断中同时赋值变量3. 在列表推导式或字典推导式中简化逻辑

Java Stream流使用案例深入详解

《JavaStream流使用案例深入详解》:本文主要介绍JavaStream流使用案例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录前言1. Lambda1.1 语法1.2 没参数只有一条语句或者多条语句1.3 一个参数只有一条语句或者多

SpringBoot整合mybatisPlus实现批量插入并获取ID详解

《SpringBoot整合mybatisPlus实现批量插入并获取ID详解》这篇文章主要为大家详细介绍了SpringBoot如何整合mybatisPlus实现批量插入并获取ID,文中的示例代码讲解详细... 目录【1】saveBATch(一万条数据总耗时:2478ms)【2】集合方式foreach(一万条数

Python装饰器之类装饰器详解

《Python装饰器之类装饰器详解》本文将详细介绍Python中类装饰器的概念、使用方法以及应用场景,并通过一个综合详细的例子展示如何使用类装饰器,希望对大家有所帮助,如有错误或未考虑完全的地方,望不... 目录1. 引言2. 装饰器的基本概念2.1. 函数装饰器复习2.2 类装饰器的定义和使用3. 类装饰

MySQL 中的 JSON 查询案例详解

《MySQL中的JSON查询案例详解》:本文主要介绍MySQL的JSON查询的相关知识,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录mysql 的 jsON 路径格式基本结构路径组件详解特殊语法元素实际示例简单路径复杂路径简写操作符注意MySQL 的 J

Go语言开发实现查询IP信息的MCP服务器

《Go语言开发实现查询IP信息的MCP服务器》随着MCP的快速普及和广泛应用,MCP服务器也层出不穷,本文将详细介绍如何在Go语言中使用go-mcp库来开发一个查询IP信息的MCP... 目录前言mcp-ip-geo 服务器目录结构说明查询 IP 信息功能实现工具实现工具管理查询单个 IP 信息工具的实现服

Python ZIP文件操作技巧详解

《PythonZIP文件操作技巧详解》在数据处理和系统开发中,ZIP文件操作是开发者必须掌握的核心技能,Python标准库提供的zipfile模块以简洁的API和跨平台特性,成为处理ZIP文件的首选... 目录一、ZIP文件操作基础三板斧1.1 创建压缩包1.2 解压操作1.3 文件遍历与信息获取二、进阶技

一文详解Java异常处理你都了解哪些知识

《一文详解Java异常处理你都了解哪些知识》:本文主要介绍Java异常处理的相关资料,包括异常的分类、捕获和处理异常的语法、常见的异常类型以及自定义异常的实现,文中通过代码介绍的非常详细,需要的朋... 目录前言一、什么是异常二、异常的分类2.1 受检异常2.2 非受检异常三、异常处理的语法3.1 try-

Java中的@SneakyThrows注解用法详解

《Java中的@SneakyThrows注解用法详解》:本文主要介绍Java中的@SneakyThrows注解用法的相关资料,Lombok的@SneakyThrows注解简化了Java方法中的异常... 目录前言一、@SneakyThrows 简介1.1 什么是 Lombok?二、@SneakyThrows