2013-06-29 9 views
10

मैं जर्सी का उपयोग कर बाकी वेब सेवा को कार्यान्वित कर रहा हूं। फ़ाइल निर्देशिका में फ़ाइल को सहेजने के लिए मुझे ServletContext की ऑब्जेक्ट की आवश्यकता है। कृपया संदर्भ प्राप्त करने में मेरी मदद करें।बाकी वेब सेवा में ServletContext कैसे प्राप्त करें

मैं एंड्रॉइड डिवाइस से इस 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 मेरा मानना ​​है कि इसे पैरामीटर के रूप में तरीकों से इंजेक्शन दिया जा सकता है (कम से कम रीस्टेसी में यह संभव है, जर्सी एक जैसा होना चाहिए)। – acdcjunior

+0

आप इसे सही कर सकते हैं, मैंने इसे शामिल नहीं किया क्योंकि इसे ओपी प्रश्न में स्पष्ट रूप से नहीं पूछा गया था - लेकिन मैं इसे शामिल करूंगा। – 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(); 
} 
संबंधित मुद्दे