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 instead
private DataStore(){
//dummy data
personMap.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 stub
String 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 stub
String 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