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

相关文章

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

HTML5 搜索框Search Box详解

《HTML5搜索框SearchBox详解》HTML5的搜索框是一个强大的工具,能够有效提升用户体验,通过结合自动补全功能和适当的样式,可以创建出既美观又实用的搜索界面,这篇文章给大家介绍HTML5... html5 搜索框(Search Box)详解搜索框是一个用于输入查询内容的控件,通常用于网站或应用程

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

C++ 函数 strftime 和时间格式示例详解

《C++函数strftime和时间格式示例详解》strftime是C/C++标准库中用于格式化日期和时间的函数,定义在ctime头文件中,它将tm结构体中的时间信息转换为指定格式的字符串,是处理... 目录C++ 函数 strftipythonme 详解一、函数原型二、功能描述三、格式字符串说明四、返回值五

LiteFlow轻量级工作流引擎使用示例详解

《LiteFlow轻量级工作流引擎使用示例详解》:本文主要介绍LiteFlow是一个灵活、简洁且轻量的工作流引擎,适合用于中小型项目和微服务架构中的流程编排,本文给大家介绍LiteFlow轻量级工... 目录1. LiteFlow 主要特点2. 工作流定义方式3. LiteFlow 流程示例4. LiteF

使用Python开发一个现代化屏幕取色器

《使用Python开发一个现代化屏幕取色器》在UI设计、网页开发等场景中,颜色拾取是高频需求,:本文主要介绍如何使用Python开发一个现代化屏幕取色器,有需要的小伙伴可以参考一下... 目录一、项目概述二、核心功能解析2.1 实时颜色追踪2.2 智能颜色显示三、效果展示四、实现步骤详解4.1 环境配置4.

CSS3中的字体及相关属性详解

《CSS3中的字体及相关属性详解》:本文主要介绍了CSS3中的字体及相关属性,详细内容请阅读本文,希望能对你有所帮助... 字体网页字体的三个来源:用户机器上安装的字体,放心使用。保存在第三方网站上的字体,例如Typekit和Google,可以link标签链接到你的页面上。保存在你自己Web服务器上的字

MySQL存储过程之循环遍历查询的结果集详解

《MySQL存储过程之循环遍历查询的结果集详解》:本文主要介绍MySQL存储过程之循环遍历查询的结果集,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言1. 表结构2. 存储过程3. 关于存储过程的SQL补充总结前言近来碰到这样一个问题:在生产上导入的数据发现