![](/img/trans.png)
[英]Transferring files between web applications running in the same Tomcat Instance
[英]Saving files to another web application running in the same Tomcat Instance (Not working)
我在同一個tomcat實例上運行了3個Web應用程序,一個應用程序( ZaapMartAdmin )供管理員將文件上傳到另一個應用程序的( ImageUploads )目錄,而第三個應用程序( ROOT )只是讀取上傳到( ImageUploads )的文件並從那里顯示圖像文件。 我從這里 , 這里 , 這里和這里得到一些想法。
這是我的servlet中的相關代碼(請注意:servlet在ZaapMartAdmin上運行):
//...
String fileName = generateFileName(request);//Generate the image file name
byte[] imageBytes = getByteArray(request);//Generate the image bytes
//Where to save the image part
ServletContext adminContext = request.getServletContext();//ZaapMartAdmin context
ServletContext rootContext = adminContext.getContext("/");//ROOT context
ServletContext uploadsContext = rootContext.getContext("/ImageUploads");//ImageUploads context
String absolutePath = uploadsContext.getRealPath("");
File imagesDirectory = new File(absolutePath + File.separator + "images");
if(!imagesDirectory.exists())
imagesDirectory.mkdir();
try(FileOutputStream fos = new FileOutputStream(absolutePath + File.separator + "images" + File.separator + fileName);)
{
fos.write(imageBytes);//<-- store the image in the directory
//... store file name to database ...
}
//...
從服務器端,我的目錄結構如下所示:
現在的問題是,當我運行此servlet時,文件將保存在“ ZaapMartAdmin ”目錄中,而不是“ ImageUploads ”目錄中。 而且它不會拋出任何異常。
另外,我crossContext="true"
每個應用程序的context.xml中添加了crossContext="true"
。
請問我在這里做錯了什么?
在對有關Context的tomcat文檔進行了更多研究之后,我可以推斷出該問題的解決方案是在tomcat / conf / server.xml文件中的Host標記中添加一個新的Context標記:
<Host name="admin.zaapmart.com" appBase="webapps/zaapmart.com/ZaapMartAdmin"
unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false">
<Alias>www.admin.zaapmart.com</Alias>
<Context path="" reloadable="true" docBase="/home/royalsee/tomcat/webapps/zaapmart.com/ZaapMartAdmin" crossContext="true"/>
<!-- next line of code did the trick -->
<Context path="/ImageUploads" reloadable="true" docBase="/home/royalsee/tomcat/webapps/zaapmart.com/ImageUploads" crossContext="true"/>
</Host>
並且我將servlet代碼修改為:
//...
String fileName = generateFileName(request);//Generate the image file name
byte[] imageBytes = getByteArray(request);//Generate the image bytes
//Where to save the image part
ServletContext adminContext = request.getServletContext();//ZaapMartAdmin context
ServletContext uploadsContext = adminContext.getContext("/ImageUploads");//ImageUploads context
String absolutePath = uploadsContext.getRealPath("");
File imagesDirectory = new File(absolutePath + File.separator + "images");
if(!imagesDirectory.exists())
imagesDirectory.mkdir();
try(FileOutputStream fos = new FileOutputStream(absolutePath + File.separator + "images" + File.separator + fileName);)
{
fos.write(imageBytes);//<-- store the image in the directory
//... store file name to database ...
}
//...
之后,我重新啟動了tomcat服務器,一切都按照我想要的方式運行!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.