不同的地方在于,同样的代码【response.sendError(1);】

在Tomcat下,response.getResponseCode()的值是 1,而在Websphere下面则是 500。

而且500这个东西比较尴尬,一般的web框架都会在web.xml里面默认让它迁移到错误页面。

由此,对于调用远端服务器servlet进行验证,需要给出结果的时候,可以根据response.getResponseCode()

进行分支判断的想法就不能借助response.sendError()来实行。

解释下,web后台调用远端服务器的时候一般使用HttpURLConnection,调用完毕之后,需要进行分支处理的时候,

最好使用response.getResponseCode(),而不是通过

BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream(), CommonValue.CHAR_SET));

String line = "";

while ((line = rd.readLine()) != null) {

}

来读这个stream内容,为什么呢,因为有可能返回的stream内容不同,有的时候是字符串,有的时候是一个文件流。

而且InputStream十分不好备份,因为为了备份而提供的两个方法mark()和reset()也是需要先自己实现了之后才能用的。

远端servlet的response不能用刚才的sendError()那用什么呢,用setStatus();

下面给出例子:

本地Server

     public boolean downloadLogFromAp(String apNo) throws Exception {

         super.currentForm.set(WebConst.WS0120Form.CAN_DOWNLOAD_FLG, CommonValue.NULL_SPACE);
String filepath = CommonValue.NULL_SPACE;
String httpsURL = CommonValue.NULL_SPACE; if (CommonValue.STRING_ONE.equals(apNo)) { filepath = PropertyFileReader.getTachiaiProperties("AP01PATH") + super.currentForm.getString(WS0120Form.AP1LOGFILEPATH);
httpsURL = PropertyFileReader.getTachiaiProperties("AP01URL");
} else { filepath = PropertyFileReader.getTachiaiProperties("AP02PATH") + super.currentForm.getString(WS0120Form.AP2LOGFILEPATH);
httpsURL = PropertyFileReader.getTachiaiProperties("AP02URL");
} String logfileparam = "logfilepath" + ServletConst.SIGN_OF_EQUALITY + filepath;
URL myurl = new URL(httpsURL);
HttpURLConnection con;
if ("https".equals(httpsURL.substring(0, 5))) {
con = (HttpsURLConnection) myurl.openConnection();
} else {
con = (HttpURLConnection) myurl.openConnection();
} con.setRequestMethod("POST");
con.setConnectTimeout(60000);
con.setReadTimeout(60000);
con.setInstanceFollowRedirects(false);
con.setUseCaches(false);
con.setDoOutput(true); OutputStream out = con.getOutputStream();
Writer wout = new OutputStreamWriter(out);
wout.write(logfileparam);
//wout.flush();
wout.close(); if (con.getResponseCode() == 200) { HttpServletResponse response = super.currentResponse;
response.setHeader("Content-Type", "text/plain");
String zipfileName = getServerZipFileName(filepath);
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(zipfileName, "UTF-8"));
OutputStream os = response.getOutputStream();
InputStream is = con.getInputStream();
DownloadUtil.transfer(is, os);
con.disconnect();
return true;
} else if (con.getResponseCode() == 1) {
// ログファイルが存在しない場合、エラーメッセージを表示する。
super.dispatchAction.getActionMessages().add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(MessageId.MSG_E_001_082));
con.disconnect();
return false;
} else {
con.disconnect();
return false;
}
}

远端Servlet

 package jp.co.kentaku.kanri.tachiai.web.servlet;

 import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import jp.co.kentaku.common.tools.LogUtil;
import jp.co.kentaku.kanri.tachiai.common.TachiaiConst;
import jp.co.kentaku.kanri.tachiai.common.util.DownloadUtil;
import jp.co.kentaku.kanri.tachiai.renkei.common.ServletConst; import org.apache.commons.lang.StringUtils;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet; public class LogFileDownloadServlet extends HttpServlet { /** シリアル・バージョンID */
private static final long serialVersionUID = 1L; private static final String FILE_SEPARATOR = File.separator; /**
* GET方式でサーブレット主処理を行う。
*
* @param req リクエスト
* @param resp レスポンス
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp);
} /**
* POST方式でサーブレット主処理を行う。
*
* @param req リクエスト
* @param resp レスポンス
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { LogUtil.debug("jp.co.kentaku", "ログファイルダウンロードサーブレット開始。");
//ログファイルパスを取得する。
String filepath = null;
BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
String line = "";
if ((line = br.readLine()) != null) {
if (!StringUtils.isEmpty(line)) {
String[] arr = line.split(ServletConst.SIGN_OF_EQUALITY);
if (arr.length == 2) {
filepath = arr[1];
}
}
} //ログファイル名正確の場合、ログファイルをダウンロードする。
if (!StringUtils.isEmpty(filepath)) {
downloadZip(filepath, resp);
} else {
resp.setHeader("Content-Type", "text/plain;charset=Shift_JIS");
PrintWriter out = resp.getWriter();
out.print("ログファイルダウンロードサーブレットで、ログファイル" + filepath + "がNULLであるから、エラーとする。");
LogUtil.error("jp.co.kentaku", "ログファイルダウンロードサーブレットで、ログファイル" + filepath + "がNULLであるから、エラーとする。");
out.flush();
out.close();
} LogUtil.debug("jp.co.kentaku", "ログファイルダウンロードサーブレット終了。");
} /**
* ログファイルをダウンロードする
*
* @param filepath ダウンロードパス
* @param response レスポンス
* @throws IOException 例外
*/
private void downloadZip(String filepath, HttpServletResponse response) throws IOException { boolean isMultiFilesName = isMultiFilesName(filepath);
File zipfolder = null;
if (isTargetExists(filepath, isMultiFilesName)) {
zipfolder = getZipTargetDir(filepath, isMultiFilesName);
String zippath = zipfolder.getName() + ".zip";
zipFile(zippath, zipfolder);
response.setHeader("Content-Type", "application/zip");
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(zippath, "UTF-8"));
OutputStream os = response.getOutputStream();
File zipfile = new File(zippath);
InputStream is = new FileInputStream(zipfile);
DownloadUtil.transfer(is, os);
zipfile.delete();
for (File file : zipfolder.listFiles()) {
file.delete();
}
zipfolder.delete();
LogUtil.debug("jp.co.kentaku", "ログファイルダウンロードサーブレット経由し、ファイル" + filepath + "をダウンロードした。");
} else {
response.setHeader("Content-Type", "text/plain;charset=Shift_JIS");
response.setStatus(1);
LogUtil.error("jp.co.kentaku", "ログファイルダウンロードサーブレットで、ログファイル" + filepath + "が存在しないから、エラーとする。");
} } /**
* 圧縮対象フォルダを取得する
*
* @param filepath ダウンロードパス
* @param isMultiFilesName 複数件フラグ
* @return 圧縮対象フォルダ
* @throws IOException 例外
*/
private File getZipTargetDir(String filepath, boolean isMultiFilesName) throws IOException { File targetDir = null;
if (isMultiFilesName) {
int lastIndex = filepath.lastIndexOf(FILE_SEPARATOR) + 1;
String toFileName = filepath.substring(lastIndex, filepath.length() - 1);
File toFolder = new File(TachiaiConst.TachiaiProperties.TACHIAI_DATA_DIR + toFileName + ".log.all");
if (!toFolder.exists()) {
toFolder.mkdirs();
}
File fromFolder = new File(filepath.substring(0, lastIndex));
for (File file : fromFolder.listFiles()) {
if (file.isFile() && file.getName().startsWith(toFileName)) {
copyFile(new File(fromFolder, file.getName()), new File(toFolder, file.getName()));
}
}
targetDir = toFolder; } else {
File fromFile = new File(filepath);
File toFile = new File(TachiaiConst.TachiaiProperties.TACHIAI_DATA_DIR + fromFile.getName());
if (!toFile.exists()) {
toFile.mkdirs();
}
copyFile(fromFile, new File(toFile, fromFile.getName()));
targetDir = toFile; }
return targetDir;
} /**
* ログファイルを圧縮する
*
* @param zippath 圧縮先パス
* @param zipfolder 圧縮対象フォルダ
* @throws BuildException 例外
*/
private void zipFile(String zippath, File zipfolder) throws BuildException { //ログファイルをZIPに圧縮する。
ZipCompressor zc = new ZipCompressor(zippath);
zc.compress(zipfolder); } /**
* 複数件ダウンロードするかどうか
*
* @param filepath ダウンロードパス
* @return 複数件フラグ
*/
private boolean isMultiFilesName(String filepath) { boolean isMultiFiles = false;
isMultiFiles = !StringUtils.isEmpty(filepath) && filepath.matches("^.+\\*$");
return isMultiFiles;
} /**
* ログファイル存在チェック
*
* @param filepath ダウンロードパス
* @param isMultiFilesName 複数件フラグ
* @return チェック結果
*/
private boolean isTargetExists(String filepath, boolean isMultiFilesName) { boolean isTargetExists = false;
if (isMultiFilesName) {
int lastIndex = filepath.lastIndexOf(FILE_SEPARATOR);
String fileName = filepath.substring(lastIndex + 1, filepath.length() - 1);
File folder = new File(filepath.substring(0, lastIndex));
if (folder.exists()) {
for (File file : folder.listFiles()) {
if (file.getName().startsWith(fileName)) {
isTargetExists = true;
break;
}
}
}
} else {
File file = new File(filepath);
isTargetExists = file.exists();
}
return isTargetExists;
} /**
* ファイルをコピーする
*
* @param fromFile コピー元
* @param toFile コピー先
* @throws IOException 例外
*/
private void copyFile(File fromFile, File toFile) throws IOException { FileInputStream fis = new FileInputStream(fromFile);
FileOutputStream fos = new FileOutputStream(toFile);
try {
int byteRead = 0;
byte[] buffer = new byte[1024];
while ((byteRead = fis.read(buffer)) != -1) {
fos.write(buffer, 0, byteRead);
}
} finally {
fis.close();
fos.flush();
fos.close();
}
} /**
* CSVファイルをZIPに圧縮する用クラス
*
* @author zang_yuling
*
*/
private static class ZipCompressor { private File zipFile; /**
* コンストラクタ
*
* @param pathName zipファイアのファイアパス
*/
public ZipCompressor(String pathName) { zipFile = new File(pathName);
} /**
* ファイアを圧縮する
*
* @param file 圧縮されたファイア名
*/
public void compress(File file) { FileSet fileSet = new FileSet();
Project prj = new Project();
Zip zip = new Zip();
zip.setProject(prj);
zip.setDestFile(zipFile);
fileSet.setProject(prj);
fileSet.setDir(file);
zip.addFileset(fileSet);
zip.execute();
} } }

WebSphere中对response.sendError()的处理与Tomcat不同的更多相关文章

  1. python中各个response使用

    Python django中我们经常用的response有django中的 JsonResponse, HttpResponse,还有DRF中的Response 在使用的时候,经常会不知道如何什么时候 ...

  2. (转)WebSphere 中池资源调优 - 线程池、连接池和 ORB

    WebSphere 中池资源调优 - 线程池.连接池和 ORB 来自:https://www.ibm.com/developerworks/cn/websphere/library/techartic ...

  3. websphere中的会话超时设置 和 web应用中web.xml中session-timeout关系

    Tomcat默认的会话的超时时间设置 设置Tomcat session有效期的三种方式有: 1.在tomcat/conf/web.xml中修改session-timeout的值,该设置是TOMCAT全 ...

  4. WebSphere中数据源连接池太小导致的连接超时错误记录

    WebSphere中数据源连接池太小导致的连接超时错误记录. 应用连接超时错误信息: [// ::: CST] webapp E com.ibm.ws.webcontainer.webapp.WebA ...

  5. WebSphere中配置的数据源在Web应用中引用的写法

    WebSphere中配置的数据源在Web应用中引用时名称一定要和数据源的JNDI名称保持一致,否则会出现无法找到数据源的错误. 引用WAS的数据源时只需要与JNDI名称保持一致即可. 引用Tomcat ...

  6. Django中的response

    render_to_response render_to_response('index.html', locals(),context_instance=RequestContext(request ...

  7. Eclipse中的Web项目自动部署到Tomcat

    原因 很长时间没用Eclipse了,近期由于又要用它做个简单的JSP项目,又要重新学习了,虽然熟悉的很快,但记忆总是很模糊,偶尔犯错,以前很少写博客,现在感觉还是很有必要的,编程中每个人对于犯过的错误 ...

  8. [转]Eclipse中的Web项目自动部署到Tomcat

    原文地址:http://www.cnblogs.com/ywl925/p/3815173.html 原因 很长时间没用Eclipse了,近期由于又要用它做个简单的JSP项目,又要重新学习了,虽然熟悉的 ...

  9. paip.java 开发中web server的选择jboss resin tomcat比较..

    paip.java 开发中web server的选择jboss resin tomcat比较.. 作者Attilax  艾龙, EMAIL:1466519819@qq.com 来源:attilax的专 ...

随机推荐

  1. JSONObject与JSONArray的使用

    1.JAR包简介 要使程序可以运行必须引入JSON-lib包,JSON-lib包同时依赖于以下的JAR包: commons-lang.jar commons-beanutils.jar commons ...

  2. Java Bad version number in .class file

    错误信息: java.lang.UnsupportedClassVersionError: Bad version number in .class file at java.lang.ClassLo ...

  3. SharedPreference 存储小量数据,一般首次启动显示引导界面就用这个。

    写://添加一个SharedPreference并传入数据SharedPreference sharedPreferences = getSharedPreferences("share_d ...

  4. scrollView自动加载数据demo

    package combaidu.mylistsrollview; import java.util.ArrayList;import java.util.List; import com.baidu ...

  5. MySQL数据库远程连接

    12.00 MySQL数据库远程连接 参考: http://www.jb51.net/article/24508.htm http://www.linuxdiyf.com/viewarticle.ph ...

  6. JS图片加载失败显示默认图片

    代码如下: <div id='photo<%# Container.DataItemIndex+1%>' style="position: absolute; displa ...

  7. php的查询数据

    php中 连接数据库,通过表格形式输出,查询数据.全选时,下面的分选项都选中;子选项取消一个时,全选按钮也取消选中. <!DOCTYPE html PUBLIC "-//W3C//DT ...

  8. hdu4597 区间dp

    //Accepted 1784 KB 78 ms //区间dp //dp[l1][r1][l2][r2] 表示a数列从l1到r1,b数列从l2到r2能得到的最大分值 // #include <c ...

  9. linux基础命令学习(七)samba服务器配置

    samba有五种安全级别,它们分别是: share:不需要samba账户就可登陆samba服务器      user:需要添加samba账户才可以登陆samba服务器      server:由另外一 ...

  10. Git ~ 大杀器之一 远程仓库 ~ Git

    一般情况ixashi找一台电脑作为服务器的角色 , 每天24小时开机 , 其他扥每个人都从这个 “服务器” 仓库里面克隆一份到自己的电脑上面 并且将各自的提交推送到服务器仓库中 , 也可以从服务器仓库 ...