WebSphere中对response.sendError()的处理与Tomcat不同
不同的地方在于,同样的代码【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不同的更多相关文章
- python中各个response使用
Python django中我们经常用的response有django中的 JsonResponse, HttpResponse,还有DRF中的Response 在使用的时候,经常会不知道如何什么时候 ...
- (转)WebSphere 中池资源调优 - 线程池、连接池和 ORB
WebSphere 中池资源调优 - 线程池.连接池和 ORB 来自:https://www.ibm.com/developerworks/cn/websphere/library/techartic ...
- websphere中的会话超时设置 和 web应用中web.xml中session-timeout关系
Tomcat默认的会话的超时时间设置 设置Tomcat session有效期的三种方式有: 1.在tomcat/conf/web.xml中修改session-timeout的值,该设置是TOMCAT全 ...
- WebSphere中数据源连接池太小导致的连接超时错误记录
WebSphere中数据源连接池太小导致的连接超时错误记录. 应用连接超时错误信息: [// ::: CST] webapp E com.ibm.ws.webcontainer.webapp.WebA ...
- WebSphere中配置的数据源在Web应用中引用的写法
WebSphere中配置的数据源在Web应用中引用时名称一定要和数据源的JNDI名称保持一致,否则会出现无法找到数据源的错误. 引用WAS的数据源时只需要与JNDI名称保持一致即可. 引用Tomcat ...
- Django中的response
render_to_response render_to_response('index.html', locals(),context_instance=RequestContext(request ...
- Eclipse中的Web项目自动部署到Tomcat
原因 很长时间没用Eclipse了,近期由于又要用它做个简单的JSP项目,又要重新学习了,虽然熟悉的很快,但记忆总是很模糊,偶尔犯错,以前很少写博客,现在感觉还是很有必要的,编程中每个人对于犯过的错误 ...
- [转]Eclipse中的Web项目自动部署到Tomcat
原文地址:http://www.cnblogs.com/ywl925/p/3815173.html 原因 很长时间没用Eclipse了,近期由于又要用它做个简单的JSP项目,又要重新学习了,虽然熟悉的 ...
- paip.java 开发中web server的选择jboss resin tomcat比较..
paip.java 开发中web server的选择jboss resin tomcat比较.. 作者Attilax 艾龙, EMAIL:1466519819@qq.com 来源:attilax的专 ...
随机推荐
- JavaScript中字符串转Json方法小记
例如: JSON字符串:var str1 = '{ "name": "cxh", "sex": "man" }'; JS ...
- ASP.NET MVC学习之路由篇(1)
1.基本路由 RouteConfig.cs: 1 public class RouteConfig 2 { 3 public static void RegisterRoutes(RouteColle ...
- node cheerio
所谓工欲善其事,必先利其器,所以通读了cheerio的API,顺便翻译了一遍,有些地方因为知道的比较少,不知道什么意思,保留了英文,希望各位不吝告诉我,然后一起把这个翻译完成. ###cheerio ...
- Git是目前世界上最先进的分布式版本控制系统
一:Git是什么? Git是目前世界上最先进的分布式版本控制系统. 二:SVN与Git的最主要的区别? SVN是集中式版本控制系统,版本库是集中放在中央服务器的,而干活的时候,用的都是自己的电脑,所以 ...
- svm特征
svm特征格式:<label><index1>:<value1><index1>:<value1>.... 其中<label> ...
- struts中获取域
在struts的Action中,有三种方法可以得到request.session.servletContext域. 1.通过ServletActionContext类获取对象 HttpServletR ...
- Android学习参考教程和工具及常见问题解决
参考教程: 1.菜鸟教程:http://www.runoob.com/w3cnote/android-tutorial-intro.html 2.Android初學特訓班(第五版) 使用工具: 1.A ...
- Problem A CodeForces 556A
Description Andrewid the Android is a galaxy-famous detective. In his free time he likes to think ab ...
- iOS 端的 UI 聊天组件ChatKit及代码实现
ChatKit 是一个免费且开源的 UI 聊天组件,自带云服务器,自带推送,支持消息漫游,消息永久存储.底层聊天服务基于LeanCloud(原名 AVOS ) 的 IM 实时通信服务「LeanMess ...
- Java基础毕向东day02
1. 常量 null 等特殊 2.标识符 数字-字母-下划线,数字不能开头 3.二进制 1> 二进制计算方法. 2>常用二进制. 1 1 0 0 1 ...