網頁

2020/9/5

Servlet 接收POST請求傳入的json資料 read POST request json body

Java Servlet接收POST傳入的json的方法如下。

例如在Postman以POST傳送json請求如下。

{
    "id": 2,
    "name": "mary",
    "email": "mary@abc.com",
    "age": 22
}

負責接收的DemoServlet。從HttpServletRequest取得輸入串流ServletInputStream,然後用Apache Commons IO的IOUtils.toString(InputStream input, Charset charset)讀取成字串。再用jackson轉json字串為物件

package com.abc.demo;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.abc.demo.dto.ApiResposne;
import com.abc.demo.dto.EmployeeDto;
import com.fasterxml.jackson.databind.ObjectMapper;

public class DemoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    public DemoServlet() {
        super();
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String body = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
        EmployeeDto employeeDto = objectMapper.readValue(body, EmployeeDto.class);
        
        ApiResposne apiResposne = new ApiResposne("success", employeeDto);
        String jsonString = objectMapper.writeValueAsString(apiResposne);
        response.getWriter().write(jsonString);
        
    }
    
}

json字串轉成的值物件實作Serializable並提供無參數建構子,否則jackson轉換json成物件時會拋InvalidDefinitionException錯誤。

EmployeeDto

package com.abc.demo.dto;

import java.io.Serializable;

public class EmployeeDto implements Serializable {
    private static final long serialVersionUID = 1L;
    
    private Long id;
    private String name;
    private String email;
    private Integer age;
    
    public EmployeeDto() { // 無參數建構子
    }

    // getters and setters

}

寫出的回應物件

ApiResposne

package com.abc.demo.dto;

import java.io.Serializable;

public class ApiResposne {
    private static final long serialVersionUID = 1L;

    private String message;
    private Object data;

    public ApiResposne() {
    }

    public ApiResposne(String message, Object data) {
        this.message = message;
        this.data = data;
    }

    // getters and setters

}

回應結果。

{
    "message": "success",
    "data": {
        "id": 2,
        "name": "mary",
        "email": "mary@abc.com",
        "age": 22
    }
}

參考github


沒有留言:

張貼留言