使用rest将表单数据存储到文件中?

时间:2016-05-14 06:36:52

标签: java rest jax-rs

我正在学习如何编写REST API!如何使用其余调用将表单值存储到文本文件中?

的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();  
    }  
}  

我想将idnameprice的值添加到文件中。我在哪里需要编写将数据添加到文件的功能?

2 个答案:

答案 0 :(得分:0)

将代码写入

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以保存到文件

答案 1 :(得分:0)

执行此操作的最佳方法是创建另一个可以写入和读取文件的类。并在此休息端点中注入该类。

因为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();  
    }  
}    

使用jackson将Map Object转换为JSON文件,反之亦然 map to / from json file