網頁

2020/9/5

Servlet simple Restful API

Servlet實現Restful API簡單範例。

最近碰到沒用框架單用Servlet硬幹Restful API的老舊專案,已經好久沒碰Servet這Java Web底層的東西,所以試驗一下。

範例環境:

  • Eclipse
  • Java 1.8
  • Servlet 4.0
  • Maven

首先使用maven-archetype-webapp建立一個Maven Web專案servlet-demo。context path預設為專案名稱。

WEB-INF/web.xml設定DemoServlet<servlet-mapping>,將context path下/demo開頭的請求都導向給DemoServlet處理。

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
        http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    version="4.0">

    <display-name>Servlet Web Application</display-name>
    <servlet>
        <servlet-name>DemoServlet</servlet-name>
        <servlet-class>com.abc.demo.DemoServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>DemoServlet</servlet-name>
        <url-pattern>/demo/*</url-pattern>
    </servlet-mapping>
</web-app>

建立DemoServlet繼承HttpServlet,負責處理請求的Restful API。

DemoServlet

package com.abc.demo;

import java.io.IOException;
import java.io.PrintWriter;

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

import org.apache.commons.lang3.StringUtils;

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;

    public DemoServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();

        if (StringUtils.isEmpty(pathInfo)) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = "";
        PrintWriter writer = response.getWriter();

        if ("/employee".equalsIgnoreCase(pathInfo)) {
            EmployeeDto employeeDto = new EmployeeDto(1L, "john", "john@abc.com", 28);
            ApiResposne apiResposne = new ApiResposne("success", employeeDto);
            jsonString = objectMapper.writeValueAsString(apiResposne);
            writer.write(jsonString);
            return;
        }

        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

}

DemoServlet.doGet()程式中用到的值類別。

EmployeeDto

package com.abc.demo.dto;

public class EmployeeDto {

    private Long id;
    private String name;
    private String email;
    private Integer age;

    public EmployeeDto(Long id, String name, String email, Integer age) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.age = age;
    }
    
    // getters and setters 
}

ApiResposne

package com.abc.demo.dto;

public class ApiResposne {

    private String message;
    private Object data;

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

    // getters and setters 
}

以上邏輯建立的API為GET|/demo/employeedoGet()是用來處理HTTP GET請求的方法。若url輸入正確會把EmployeeDto轉為json字串回應出去。

設定完以上後啟動專案。

使用Postman測試,在url欄位使用GET,位址輸入http://localhost:8080/servlet-demo/demo/employee送出請求。

回應結果如下。

{"message":"success","data":{"id":1,"name":"john","email":"john@abc.com","age":28}}

參考github


沒有留言:

張貼留言