最近項目上做了一個移動辦公項目,開始客戶預訂是在內網使用。做完後,客戶又想可以連接外網使用該平臺。麻煩就出現了,本來將該系統服務端發佈到外網上就可以了,但在實際評估中發現客戶端很多的下載、新聞、圖片展示等功能都是使用的其它應用系統上的鏈接。而這些系統都是在內網中,無法在外網中使用。如果要改造使之可以正常下載展示這些內容,改動量就會很大。經過考慮,我想最好的辦法,是將這些鏈接的內容在服務端(服務端是內外網都可以訪問的)做轉換,使它可以直接下載內網中其它系統的文件。原理是java下載時將下載服務器端文件改爲下載網絡文件。聽起來是有些拗口,那就讓我把實現後的原代碼貼出來吧:
下載實現
servlet配置:
<!-- 下載servlet start--> <servlet> <servlet-name>DownloadFile</servlet-name> <servlet-class>com.gygs.cportalsend.servlet.DownloadServlet</servlet-class> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DownloadFile</servlet-name> <url-pattern>/downloadFile</url-pattern> </servlet-mapping> <!-- 下載servlet end-->
類:
package com.gygs.cportalsend.servlet; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 初始化 * @author ziwen */ public class DownloadServlet extends HttpServlet { //http://localhost:8080/gygsmobile/downloadFile?fileUrl=http://g.hiphotos.baidu.com/image/pic/item/e7cd7b899e510fb3d9b14f9ada33c895d1430c16.jpg protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException{ System.out.println("調用doGet方法"); // 下載網絡文件 int bytesum = 0; int byteread = 0; try { // URL url = new URL("http://g.hiphotos.baidu.com/image/pic/item/e7cd7b899e510fb3d9b14f9ada33c895d1430c16.jpg"); String fileUrl=request.getParameter("fileUrl"); String fileUrlName=request.getParameter("fileUrlName"); System.out.println("URLURLURLURLURLfileUrl:"+fileUrl); System.out.println("URLURLURLURLURLfileUrlName:"+fileUrlName); // fileUrl=URLDecoder.decode(fileUrl, "UTF-8"); // System.out.println("URLURLURLURLURL2:"+fileUrl); if(fileUrlName==null || "".equals(fileUrlName)){ fileUrlName=getRandomString(8); String ext = fileUrl.substring(fileUrl.lastIndexOf(".") + 1); fileUrlName=fileUrlName+"."+ext; // .toUpperCase(); } byte[] buffer = getUrlFileData(fileUrl); // fis.read(buffer); // fis.close(); // 清空response response.reset(); // 設置response的Header response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileUrlName)); // response.addHeader("Content-Length", ""); OutputStream toClient = new BufferedOutputStream( response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (Exception e) { e.printStackTrace(); } } protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException{ System.out.println("調用doPost方法"); doGet(request,response); } //獲取鏈接地址文件的byte數據 public static byte[] getUrlFileData(String fileUrl) throws Exception { URL url = new URL(fileUrl); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.connect(); InputStream cin = httpConn.getInputStream(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = cin.read(buffer)) != -1) { outStream.write(buffer, 0, len); } cin.close(); byte[] fileData = outStream.toByteArray(); outStream.close(); return fileData; } public String getRandomString(int length) { StringBuffer buffer = new StringBuffer("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); StringBuffer sb = new StringBuffer(); Random r = new Random(); int range = buffer.length(); for (int i = 0; i < length; i ++) { sb.append(buffer.charAt(r.nextInt(range))); } return sb.toString(); } }
2.新聞中圖片展示
package com.isoftstone.service;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.sql.DataSource;
import oracle.sql.CLOB;
import com.gygs.cportalsend.common.DataSourceGetor;
import com.isoftstone.service.pojo.InformationBean;
import com.isoftstone.service.pojo.InformationContent;
import com.jfinal.plugin.activerecord.Db;
public class NewShowService {
public InformationBean newDetail(String new_id){
StringBuffer sql=new StringBuffer();
sql.append("select title,sub_title,author_name,modify_date,view_num,promulgation_charge from portal_information i where i.id="+new_id);
DataSource dataSource=null;
dataSource=DataSourceGetor.getDataSourceGetorInstence().getDataSource("BGMH");
// sql.append("select orgid,name from sys_user where id='"+creatorid+"' and status='1'");
InformationBean informationBean=new InformationBean();
List<Object[]> list=Db.query(dataSource,sql.toString());
if(list!=null && list.size()>0){
Object[] res=list.get(0);
informationBean.setTitle(res[0].toString());
informationBean.setSubTitle(res[1]==null?"":res[1].toString());
informationBean.setAuthorName(res[2]==null?"":res[2].toString());
informationBean.setModifyDateCn(res[3]==null?"":res[3].toString());
informationBean.setViewNum(Integer.parseInt(res[4]==null?"":res[4].toString()));
informationBean.setPromulgationCharge(res[5]==null?"":res[5].toString());
}
informationBean.setContent(findInformationContentByInformationId(Integer.parseInt(new_id)).getContent());
return informationBean;
}
//http://localhost:8080/gygsmobile/newsDetail_mobile.jsp?NEWID=4581
public InformationContent findInformationContentByInformationId(int informationId) {
// TODO Auto-generated method stub
StringBuffer sql=new StringBuffer();
sql.append("select content from portal_information_content i where i.information_id="+informationId);
DataSource dataSource=null;
dataSource=DataSourceGetor.getDataSourceGetorInstence().getDataSource("XXXX");
InformationContent informationContent=new InformationContent();
List list=Db.query(dataSource,sql.toString());
if(list!=null && list.size()>0){
System.out.println("KKKK:"+list.get(0));
byte[] res=((CLOB)list.get(0)).getBytes();
System.out.println("KKKK:"+res);
try {
String newStr=new String(res, "utf-16");
System.out.println("KKKK1:"+newStr);
String newStr2="";
//將新聞源代碼中的圖片鏈接替換
newStr2=newStr.replace("/yidongbangong/", "http://localhost:8080/smobile/downloadFile?fileUrl=http://192.168.0.40:9081/ygbg/");
// if(newStr.indexOf("/gyygbg/")>=0){
//
// }
System.out.println("KKKK2:"+newStr2);
informationContent.setContent(newStr2);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return informationContent;
}
}