[英]Storing Form data into file using rest?
我正在學習如何編寫REST API! 如何使用Rest調用將表單值存儲到文本文件中?
index.html
<form action="rest/product/adddata" method="post">
Enter Id:<input type="text" name="id"/><br/><br/>
Enter Name:<input type="text" name="name"/><br/><br/>
Enter Price:<input type="text" name="price"/><br/><br/>
<input type="submit" value="Add Product"/>
</form>
service.java
@Path("/product")
public class ProductService{
@POST
@Path("/adddata")
public Response addUser(
@FormParam("id") int id,
@FormParam("name") String name,
@FormParam("price") float price) {
return Response.status(200)
.entity(" Product added successfuly!<br> Id: "+id+"<br> Name: " + name+"<br> Price: "+price)
.build();
}
}
我想將id
, name
和price
值添加到文件中。 我需要在哪里編寫將數據添加到文件的功能?
將代碼寫入
public Response addUser(
@FormParam("id") int id,
@FormParam("name") String name,
@FormParam("price") float price) {
saveFile(id,name,price);
return Response.status(200)
.entity(" Product added successfuly!<br> Id: "+id+"<br> Name: " + name+"<br> Price: "+price)
.build();
}
將代碼寫入saveFile以保存到文件
最好的方法是創建另一個可以讀寫文件的類。 並在該其余端點中注入該類。
因為rest端點類中的直接代碼應用於處理不寫文件的請求
class FormSynchronizer {
public static final File FORM_BASE = new File(...); // The location of directory which will contain all these files
public void storeFile(Map map, String fileName){
File toStoreFile = new File(FORM_BASE, fileName);
/* Write code to store file */
}
}
將該類注入您的其余端點類
public class ProductService{
@Inject FormSynchronizer formSynchronizer;
@POST
@Path("/adddata")
public Response addUser(
@FormParam("id") int id,
@FormParam("name") String name,
@FormParam("price") float price) {
Map<String, Object> data = new HashMap<>();
data.put("id", id);
/* put all data you want to store in this map */
formSynchronizer.storeForm(data, "FORM_" + new Date().getTime()); // I used current time prefixed with 'FORM_' string as file name
return Response.status(200)
.entity(" Product added successfuly!<br> Id: "+id+"<br> Name: " + name+"<br> Price: "+price)
.build();
}
}
使用傑克遜將地圖對象轉換為JSON文件,反之亦然。
映射到/從json文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.