Ответ 1
Используйте @Context, вот Джерси documentation
@Context
private ServletContext context;
ОБНОВЛЕНО - вы можете также непосредственно вводить в методы
public String uploadNotices(@Context ServletContext context, ...)
Я использую веб-сервис для отдыха с использованием Джерси. Мне нужно иметь объект ServletContext для сохранения файла в каталоге приложения. Пожалуйста, помогите мне получить контекст.
Я вызываю этот веб-сервис с устройства Android.
Спасибо заранее.
@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, вот Джерси documentation
@Context
private ServletContext context;
ОБНОВЛЕНО - вы можете также непосредственно вводить в методы
public String uploadNotices(@Context ServletContext context, ...)
используйте аннотацию @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();
}