2013-06-29 4 views
10

Sto implementando il servizio web di resto utilizzando Jersey. Devo avere l'oggetto di ServletContext per salvare il file nella directory dell'applicazione. Per favore aiutami a ottenere il contesto.Come ottenere il servizio web ServletContext in Rest

Sto chiamando questo webservice dal dispositivo Android.

Grazie in anticipo.

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

risposta

28

Usa @Context, ecco Jersey documentation

@Context 
private ServletContext context; 

AGGIORNAMENTO - è anche possibile iniettare direttamente nelle metodi se desiderate

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

+1 Credo che possa essere iniettato anche nei metodi come parametri (almeno in RESTEasy questo è possibile, Jersey dovrebbe essere lo stesso). – acdcjunior

+0

Hai ragione, non l'ho incluso poiché non è stato chiesto esplicitamente nella domanda OP, ma lo includerò. – ikumen

+0

+1. Bello ... è utile. –

3

usare l'annotazione @context (iniezione livello di metodo)

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