如何在 Rest Web 服务中获取 ServletContext

2022-09-03 17:24:16

我正在使用泽西岛实现休息Web服务。我需要有ServletContext的对象才能将文件保存在应用程序目录中。请帮我了解背景。

我从Android设备调用此Web服务。

提前致谢。

@Path("notice")
public class NoticeResources {

    @Resource
    private ServletContext context;


    @POST
    @Path("uploadphoto")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces("text/plain")
    public String uploadNotices(@FormDataParam("file") InputStream uploadedInputStream) {

        File photoDirectory = new File("\\photo");

        // if the directory does not exist, create it
        if (!photoDirectory.exists()) {
            boolean result = photoDirectory.mkdir();  
            if(result){
                System.out.println("DIR created");
            }
        }

        String rootPath = photoDirectory.getAbsolutePath();

        String uploadedFileLocation = rootPath + "\\photo.jpg";
        // save it
        try {
            writeToFile(uploadedInputStream, uploadedFileLocation);
        } catch(Exception e) {
            return "no" + rootPath;
        }
        return "yes" + rootPath;
    }

    // save uploaded file to new location
    private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) throws Exception {
        OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
        int read = 0;
        byte[] bytes = new byte[1024];

        out = new FileOutputStream(new File(uploadedFileLocation));
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
    }   
}

答案 1

使用@Context,这里是泽西岛文档

@Context
private ServletContext context; 

已更新 - 如果需要,您也可以直接注入到方法中

public String uploadNotices(@Context ServletContext context, ...)

答案 2

使用注释@context(方法级别注入)

public Response getContext(@Context HttpServletRequest req, @Context HttpServletResponse res)throws Exception
{   
    System.out.println("Context Path is:"+req.getRequestURL().toString());
    result=req.getRequestURL().toString();
    return Response.status(200).entity(result).build();
}

推荐