当前位置: 首页 > news >正文

假期别闲着:REST API实战演练之创建Rest API

1、创建实体类,模拟实体对象

创建一个类,模拟数据数据库来存储数据,这个类就叫Person。

其代码如下:

package com.restful;public class Person {private String name;private String about;private int birthYear;public Person(String name, String about, int birthYear) {this.name = name;this.about = about;this.birthYear = birthYear;}public String getName() {return name;}public String getAbout() {return about;}public int getBirthYear() {return birthYear;}
}

2、创建数据类,模型数据库存储

再创建一个类,假设能够访问我们的数据库,类名字就叫DataStore。

编写如下代码:

package com.restful;import java.util.HashMap;
import java.util.Map;public class DataStore {//Map of names to Person instances.private Map<String, Person> personMap = new HashMap<>();//this class is a singleton and should not be instantiated directly!private static DataStore instance = new DataStore();public static DataStore getInstance(){return instance;}//private constructor so people know to use the getInstance() function insteadprivate DataStore(){//dummy datapersonMap.put("Ada", new Person("Ada", "Ada Lovelace was the first programmer.", 1815));personMap.put("Kevin", new Person("Kevin", "Kevin is the author of HappyCoding.io.", 1986));personMap.put("Stanley", new Person("Stanley", "Stanley is Kevin's cat.", 2007));}public Person getPerson(String name) {return personMap.get(name);}public void putPerson(Person person) {personMap.put(person.getName(), person);}
}

3、创建Servlet,接收请求并访问数据对象

接下来,我们创建一个Servlet类,类名就叫做PersonServlet。

修改代码如下:

package com.servlet;import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;import com.restful.DataStore;
import com.restful.Person;
/*** Servlet implementation class PersonServlet*/
@WebServlet("/PersonServlet")
public class PersonServlet extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public PersonServlet() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubString requestUrl = request.getRequestURI();String name = requestUrl.substring(requestUrl.lastIndexOf("/")+1);System.out.println(name);Person person = DataStore.getInstance().getPerson(name);if(person != null){String json = "{\n";json += "\"name\": " +"\""+ person.getName() +"\""+ ",\n";json += "\"about\": " + "\""+ person.getAbout() + "\""+",\n";json += "\"birthYear\": " + "\""+ person.getBirthYear() + "\""+"\n";json += "}";response.getOutputStream().println(json);}else{//That person wasn't found, so return an empty JSON object. We could also return an error.response.getOutputStream().println("{}");}}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubString name = request.getParameter("name");String about = request.getParameter("about");int birthYear = Integer.parseInt(request.getParameter("birthYear"));DataStore.getInstance().putPerson(new Person(name, about, birthYear));}}

上述创建的Servlet类包含了doGet函数和doPost函数。

4、配置一个Servlet映射

创建servlet后,我们修改一下我们的web.xml,做一个映射,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0"><display-name>HelloJSP</display-name><welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.jsp</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>default.html</welcome-file><welcome-file>default.jsp</welcome-file><welcome-file>default.htm</welcome-file></welcome-file-list><servlet><servlet-name>PersonServlet</servlet-name><servlet-class>com.servlet.PersonServlet</servlet-class></servlet><servlet-mapping><servlet-name>PersonServlet</servlet-name><url-pattern>/people/*</url-pattern></servlet-mapping></web-app>

doGet()函数从 URL 中获取一个人的姓名,然后使用DataStore类来获取那个人。接着它从该人的数据中创建一个 JSON 字符串,并将该 JSON 作为对请求的响应返回GET。请记住,JSON 使用用引号括起来的键和值,如下所示:

{
"name": "Ada",
"about": "Ada Lovelace was the first programmer.",
"birthYear": 1815
}

5、测试

接下来我们启动服务加载该servlet,在浏览器输入如下地址:localhost:8080/HelloJSP/people/Kevin

结果显示如下:

今天就先把怎么写一个简单的rest api介绍到这儿,后面说一下客户端怎么使用rest api访问数据。

参考资料:https://blog.csdn.net/allway2/article/details/123375541

https://happycoding.io/tutorials/java-server/rest-api

http://www.lryc.cn/news/335463.html

相关文章:

  • C++模仿qq界面
  • 3D模型在线轻量化工具
  • 去中心化社交媒体:分析 Facebook 在区块链平台上的角色
  • 实现多租户JAVA支付(微信拉起支付):一个简单而强大的解决方案
  • 万字长文:FineBI面试题及参考答案详解
  • Python爬虫:为什么你爬取不到网页数据
  • NLP在搜索召回领域中的应用场景
  • 2. Django配置信息
  • 【Web】纯萌新的BUUCTF刷题日记Day1
  • 【51单片机入门记录】RTC(实时时钟)-DS1302概述
  • Lua热更新(AssetBundle)
  • 互联网人才现状分析
  • 高级IO——多路转接
  • TypeScript常用知识点整理
  • 【Unity实战100例】Unity入门小地图位置同步(第一第三人称)
  • 蓝桥杯简单模板
  • 单例模式(饿汉模型,懒汉模型)
  • torchvision中的数据集使用
  • linux 迁移home目录以及修改conda中pip的目录,修改pip安装路径
  • 解析大语言模型训练三阶段
  • 知识图谱的最新进展与未来趋势
  • Facebook直播延迟过高是为什么?
  • CentOS 7.9 额外安装一个Python3.x版本详细教程
  • uml时序图中,消息箭头和消息调用箭头有什么区别
  • 12.C++常用的算法_遍历算法
  • hadoop:案例:将顾客在京东、淘宝、多点三家平台的消费金额汇总,然后先按京东消费额排序,再按淘宝消费额排序
  • 2024年华为OD机试真题-孙悟空吃蟠桃-Python-OD统一考试(C卷)
  • vue3 开发中遇到的问题
  • Vue input密码输入框自定义密码眼睛icon
  • 【LAMMPS学习】八、基本知识的讨论(1.4)多副本模拟