如何在Rest Web服务中获取ServletContext [英] How to get the ServletContext in Rest web service

查看:279
本文介绍了如何在Rest Web服务中获取ServletContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jersey实现rest web服务。我需要有ServletContext的对象将文件保存在应用程序目录中。请帮助我获取上下文。

I am implementing rest web service using Jersey. I need to have object of ServletContext to save the file in the application directory. Please help me to get the context.

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

I am calling this webservice from android device.

提前致谢。

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


推荐答案

使用@Context,这里是Jersey 文档

Use @Context, here is Jersey documentation

@Context
private ServletContext context; 

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

UPDATED - you can also inject directly into methods if desired

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

这篇关于如何在Rest Web服务中获取ServletContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆