不同的地方在于,同样的代码【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. Linux 常用

    1,解决ssh登录慢的问题记录 vim /etc/ssh/ssh_config    #   GSSAPIAuthentication no  把下面这一行的注释去掉 2,Linux查看当前是什么系统 ...

  2. tomcat http 文件下载

    tomcat作为http的下载服务器,网上有很多办法 但我认为最简单的是: 1.直接把文件放在 tomcat6/webapps/ROOT 目录下, 2.然后在网址中访问: http://120.194 ...

  3. Visual studio 2013安装及单元测试

    vs安装过程 单元测试: 创建c#类库 创建单元测试 测试结果

  4. [C/C++]C++声明

    [注]本文是Declarations的翻译和注解版. https://msdn.microsoft.com/en-us/library/f432x8c6.aspx 1.声明: 我们通过声明往C++程序 ...

  5. 100个iOS开发/设计面试题汇总

    常见问题 你昨天/这周学习了什么? 你为什么热衷于软件开发? 你对哪一种控制系统比较熟悉? 是否参与过GitHub项目? 是否参与过GitHub或其他同类型网站的iOS开源项目? 请描述一下你的iOS ...

  6. 更新安装xcode7插件

    mkdir -p ~/Library/Application\ Support/Developer/Shared/Xcode/Plug-inscurl -fsSL https://raw.github ...

  7. 《day18_String练习_基本类型包装类_集合入门》

    package cn.itcast.api.String.test; public class StringTest_1 { public static void main(String[] args ...

  8. alpha,hidden,opaque的一些认识

    如果opaque设置为YES,那么视图会被当做全视图来对待,系统会重绘整个视图 如果opaque设置为NO,那么系统会减少开销,以其中的内容来判定重绘的视图 如果把视图的背景色设置为透明那个,那么op ...

  9. json_decode 与 json_encode 的区别

    1.json_decode对JSON格式的字符串进行编码 2.json_encode对变量进行 JSON 编码 3.unset()是注销定义的变量 4.urlencode()函数原理就是首先把中文字符 ...

  10. TCP同步传送数据示例(简洁、清楚)

    转自:http://www.2cto.com/kf/201206/134841.html 本例子写了个简单的TCP数据传送功能.没有使用BinaryWriter,BinaryReader,而是使用Ne ...