2013-06-29 46 views
10

我正在使用Jersey實現其他Web服務。我需要將ServletContext的對象保存在應用程序目錄中。請幫我弄清楚背景。如何獲取其餘Web服務中的ServletContext

我從android設備調用此webservice。

在此先感謝。

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

回答

28

使用@Context,這裏是澤西documentation

@Context 
private ServletContext context; 

更新 - 您也可以直接如果需要

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

+1我相信它也可以作爲參數注入方法(至少在RESTEasy中這是可能的,Jersey應該是相同的)。 – acdcjunior

+0

你說的沒錯,我沒有包括它,因爲它沒有在OP問題中明確提出 - 但我會包括它。 – ikumen

+0

+1。尼斯..很有幫助。 –

3

使用註釋@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(); 
}