package com.csnf.controller;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@WebServlet("/*")
public class StaticServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求的资源路径
        String path = request.getPathInfo();
///WEB-INF/res/css/bootstrap.min.css
        // 设置资源的相对路径
        String resourcePath = "/WEB-INF/res/" + path;

        // 获取ServletContext对象
        ServletContext context = getServletContext();

        // 获取资源的Servlet流
        InputStream inputStream = context.getResourceAsStream(resourcePath);
        if (inputStream == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 设置响应的类型
        String mimeType = context.getMimeType(resourcePath);
        if (mimeType != null) {
            response.setContentType(mimeType);
        }

        // 将资源内容写入响应
        try (OutputStream outputStream = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    }
}