不同的地方在于,同样的代码【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. BAT文件执行完成后如何删除自身的解决办法

    在BAT文件的最后加上一句 del %0,就可以在处理完后,删除自己了

  2. 基于Lumisoft.NET组件的POP3邮件接收和删除操作

    From: http://www.cnblogs.com/wuhuacong/archive/2013/05/06/3063093.html Lumisoft.NET组件是一个非常强大的邮件发送.邮件 ...

  3. iOS中Block使用探索

    Block介绍 Block在ios 4.0之后加入,并大量使用在新的ios api中.block是一个匿名的代码块,可以传递给其他对象的参数,并得到返回值.从本质上讲,block同其他普通的变量类似, ...

  4. ODI 11g & 12c中缓慢变化维(SCD)的处理机制

    缓慢变化维(Slowly changing Dimensions)指的是维表中的维度字段值会随着时间或业务调整,而在后续的分析中,历史数据仍然要使用旧的维度值,新的数据会使用当前维度值.在数据仓库建设 ...

  5. xampp笔记

    1.XAMPP添加VirtualHost以支持多个站点 服务器有1个ip,但多个网站通过dns都可以指到这台服务器上,这时候要配置虚拟主机(单一系统上运行多个网站) 用顶级域名 访问方式 来访问你本地 ...

  6. K-Anonymous Sequence(poj 3709)

    http://poj.org/problem?id=3709 给定一个长度为n的非严格单调递增数列a1,...,an.每一次操作可以使数列中的任何一项的值减小1.现在要使数列中的每一项都满足其他项中至 ...

  7. poj3126 筛素数+bfs

    //Accepted 212 KB 16 ms //筛素数+bfs #include <cstdio> #include <cstring> #include <iost ...

  8. hdoj-2019

    #include "stdio.h"void sort(int number[],int n,int m);int main(){ int n,m,i,number[100]; s ...

  9. Combination Sum 和Combination Sum II

    这两道题的基本思路和combination那一题是一致的,也是分治的方法. 其中combination Sum复杂一点,因为每个数可能用多次.仔细分析下,本质上也是一样的.原来是每个数仅两种可能.现在 ...

  10. Python 类的一些BIF

    issubclass issubclass(cls, class_or_tuple, /) Return whether 'cls' is a derived from another class o ...