• 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

     1     public boolean downloadLogFromAp(String apNo) throws Exception {
     2 
     3         super.currentForm.set(WebConst.WS0120Form.CAN_DOWNLOAD_FLG, CommonValue.NULL_SPACE);
     4         String filepath = CommonValue.NULL_SPACE;
     5         String httpsURL = CommonValue.NULL_SPACE;
     6 
     7         if (CommonValue.STRING_ONE.equals(apNo)) {
     8 
     9             filepath = PropertyFileReader.getTachiaiProperties("AP01PATH") + super.currentForm.getString(WS0120Form.AP1LOGFILEPATH);
    10             httpsURL = PropertyFileReader.getTachiaiProperties("AP01URL");
    11         } else {
    12 
    13             filepath = PropertyFileReader.getTachiaiProperties("AP02PATH") + super.currentForm.getString(WS0120Form.AP2LOGFILEPATH);
    14             httpsURL = PropertyFileReader.getTachiaiProperties("AP02URL");
    15         }
    16 
    17         String logfileparam = "logfilepath" + ServletConst.SIGN_OF_EQUALITY + filepath;
    18         URL myurl = new URL(httpsURL);
    19         HttpURLConnection con;
    20         if ("https".equals(httpsURL.substring(0, 5))) {
    21             con = (HttpsURLConnection) myurl.openConnection();
    22         } else {
    23             con = (HttpURLConnection) myurl.openConnection();
    24         }
    25 
    26         con.setRequestMethod("POST");
    27         con.setConnectTimeout(60000);
    28         con.setReadTimeout(60000);
    29         con.setInstanceFollowRedirects(false);
    30         con.setUseCaches(false);
    31         con.setDoOutput(true);
    32 
    33         OutputStream out = con.getOutputStream();
    34         Writer wout = new OutputStreamWriter(out);
    35         wout.write(logfileparam);
    36         //wout.flush();
    37         wout.close();
    38 
    39         if (con.getResponseCode() == 200) {
    40 
    41             HttpServletResponse response = super.currentResponse;
    42             response.setHeader("Content-Type", "text/plain");
    43             String zipfileName = getServerZipFileName(filepath);
    44             response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(zipfileName, "UTF-8"));
    45             OutputStream os = response.getOutputStream();
    46             InputStream is = con.getInputStream();
    47             DownloadUtil.transfer(is, os);
    48             con.disconnect();
    49             return true;
    50         } else if (con.getResponseCode() == 1) {
    51             // ログファイルが存在しない場合、エラーメッセージを表示する。
    52             super.dispatchAction.getActionMessages().add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(MessageId.MSG_E_001_082));
    53             con.disconnect();
    54             return false;
    55         } else {
    56             con.disconnect();
    57             return false;
    58         }
    59     }

    远端Servlet

      1 package jp.co.kentaku.kanri.tachiai.web.servlet;
      2 
      3 import java.io.BufferedReader;
      4 import java.io.File;
      5 import java.io.FileInputStream;
      6 import java.io.FileOutputStream;
      7 import java.io.IOException;
      8 import java.io.InputStream;
      9 import java.io.InputStreamReader;
     10 import java.io.OutputStream;
     11 import java.io.PrintWriter;
     12 import java.net.URLEncoder;
     13 
     14 import javax.servlet.ServletException;
     15 import javax.servlet.http.HttpServlet;
     16 import javax.servlet.http.HttpServletRequest;
     17 import javax.servlet.http.HttpServletResponse;
     18 
     19 import jp.co.kentaku.common.tools.LogUtil;
     20 import jp.co.kentaku.kanri.tachiai.common.TachiaiConst;
     21 import jp.co.kentaku.kanri.tachiai.common.util.DownloadUtil;
     22 import jp.co.kentaku.kanri.tachiai.renkei.common.ServletConst;
     23 
     24 import org.apache.commons.lang.StringUtils;
     25 import org.apache.tools.ant.BuildException;
     26 import org.apache.tools.ant.Project;
     27 import org.apache.tools.ant.taskdefs.Zip;
     28 import org.apache.tools.ant.types.FileSet;
     29 
     30 
     31 public class LogFileDownloadServlet extends HttpServlet {
     32 
     33     /** シリアル・バージョンID */
     34     private static final long   serialVersionUID = 1L;
     35 
     36     private static final String FILE_SEPARATOR   = File.separator;
     37 
     38 
     39     /**
     40      * GET方式でサーブレット主処理を行う。
     41      *
     42      * @param req リクエスト
     43      * @param resp レスポンス
     44      */
     45     @Override
     46     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     47 
     48         this.doPost(req, resp);
     49     }
     50 
     51 
     52     /**
     53      * POST方式でサーブレット主処理を行う。
     54      *
     55      * @param req リクエスト
     56      * @param resp レスポンス
     57      */
     58     @Override
     59     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     60 
     61         LogUtil.debug("jp.co.kentaku", "ログファイルダウンロードサーブレット開始。");
     62         //ログファイルパスを取得する。
     63         String filepath = null;
     64         BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream()));
     65         String line = "";
     66         if ((line = br.readLine()) != null) {
     67             if (!StringUtils.isEmpty(line)) {
     68                 String[] arr = line.split(ServletConst.SIGN_OF_EQUALITY);
     69                 if (arr.length == 2) {
     70                     filepath = arr[1];
     71                 }
     72             }
     73         }
     74 
     75         //ログファイル名正確の場合、ログファイルをダウンロードする。
     76         if (!StringUtils.isEmpty(filepath)) {
     77             downloadZip(filepath, resp);
     78         } else {
     79             resp.setHeader("Content-Type", "text/plain;charset=Shift_JIS");
     80             PrintWriter out = resp.getWriter();
     81             out.print("ログファイルダウンロードサーブレットで、ログファイル" + filepath + "がNULLであるから、エラーとする。");
     82             LogUtil.error("jp.co.kentaku", "ログファイルダウンロードサーブレットで、ログファイル" + filepath + "がNULLであるから、エラーとする。");
     83             out.flush();
     84             out.close();
     85         }
     86 
     87         LogUtil.debug("jp.co.kentaku", "ログファイルダウンロードサーブレット終了。");
     88     }
     89 
     90 
     91     /**
     92      * ログファイルをダウンロードする
     93      * 
     94      * @param filepath ダウンロードパス
     95      * @param response レスポンス
     96      * @throws IOException 例外
     97      */
     98     private void downloadZip(String filepath, HttpServletResponse response) throws IOException {
     99 
    100         boolean isMultiFilesName = isMultiFilesName(filepath);
    101         File zipfolder = null;
    102         if (isTargetExists(filepath, isMultiFilesName)) {
    103             zipfolder = getZipTargetDir(filepath, isMultiFilesName);
    104             String zippath = zipfolder.getName() + ".zip";
    105             zipFile(zippath, zipfolder);
    106             response.setHeader("Content-Type", "application/zip");
    107             response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(zippath, "UTF-8"));
    108             OutputStream os = response.getOutputStream();
    109             File zipfile = new File(zippath);
    110             InputStream is = new FileInputStream(zipfile);
    111             DownloadUtil.transfer(is, os);
    112             zipfile.delete();
    113             for (File file : zipfolder.listFiles()) {
    114                 file.delete();
    115             }
    116             zipfolder.delete();
    117             LogUtil.debug("jp.co.kentaku", "ログファイルダウンロードサーブレット経由し、ファイル" + filepath + "をダウンロードした。");
    118         } else {
    119             response.setHeader("Content-Type", "text/plain;charset=Shift_JIS");
    120             response.setStatus(1);
    121             LogUtil.error("jp.co.kentaku", "ログファイルダウンロードサーブレットで、ログファイル" + filepath + "が存在しないから、エラーとする。");
    122         }
    123 
    124     }
    125 
    126 
    127     /**
    128      * 圧縮対象フォルダを取得する
    129      * 
    130      * @param filepath ダウンロードパス
    131      * @param isMultiFilesName 複数件フラグ
    132      * @return 圧縮対象フォルダ
    133      * @throws IOException 例外
    134      */
    135     private File getZipTargetDir(String filepath, boolean isMultiFilesName) throws IOException {
    136 
    137         File targetDir = null;
    138         if (isMultiFilesName) {
    139             int lastIndex = filepath.lastIndexOf(FILE_SEPARATOR) + 1;
    140             String toFileName = filepath.substring(lastIndex, filepath.length() - 1);
    141             File toFolder = new File(TachiaiConst.TachiaiProperties.TACHIAI_DATA_DIR + toFileName + ".log.all");
    142             if (!toFolder.exists()) {
    143                 toFolder.mkdirs();
    144             }
    145             File fromFolder = new File(filepath.substring(0, lastIndex));
    146             for (File file : fromFolder.listFiles()) {
    147                 if (file.isFile() && file.getName().startsWith(toFileName)) {
    148                     copyFile(new File(fromFolder, file.getName()), new File(toFolder, file.getName()));
    149                 }
    150             }
    151             targetDir = toFolder;
    152 
    153         } else {
    154             File fromFile = new File(filepath);
    155             File toFile = new File(TachiaiConst.TachiaiProperties.TACHIAI_DATA_DIR + fromFile.getName());
    156             if (!toFile.exists()) {
    157                 toFile.mkdirs();
    158             }
    159             copyFile(fromFile, new File(toFile, fromFile.getName()));
    160             targetDir = toFile;
    161 
    162         }
    163         return targetDir;
    164     }
    165 
    166 
    167     /**
    168      * ログファイルを圧縮する
    169      * 
    170      * @param zippath 圧縮先パス
    171      * @param zipfolder 圧縮対象フォルダ
    172      * @throws BuildException 例外
    173      */
    174     private void zipFile(String zippath, File zipfolder) throws BuildException {
    175 
    176         //ログファイルをZIPに圧縮する。
    177         ZipCompressor zc = new ZipCompressor(zippath);
    178         zc.compress(zipfolder);
    179 
    180     }
    181 
    182 
    183     /**
    184      * 複数件ダウンロードするかどうか
    185      * 
    186      * @param filepath ダウンロードパス
    187      * @return 複数件フラグ
    188      */
    189     private boolean isMultiFilesName(String filepath) {
    190 
    191         boolean isMultiFiles = false;
    192         isMultiFiles = !StringUtils.isEmpty(filepath) && filepath.matches("^.+\*$");
    193         return isMultiFiles;
    194     }
    195 
    196 
    197     /**
    198      * ログファイル存在チェック
    199      * 
    200      * @param filepath ダウンロードパス
    201      * @param isMultiFilesName 複数件フラグ
    202      * @return チェック結果
    203      */
    204     private boolean isTargetExists(String filepath, boolean isMultiFilesName) {
    205 
    206         boolean isTargetExists = false;
    207         if (isMultiFilesName) {
    208             int lastIndex = filepath.lastIndexOf(FILE_SEPARATOR);
    209             String fileName = filepath.substring(lastIndex + 1, filepath.length() - 1);
    210             File folder = new File(filepath.substring(0, lastIndex));
    211             if (folder.exists()) {
    212                 for (File file : folder.listFiles()) {
    213                     if (file.getName().startsWith(fileName)) {
    214                         isTargetExists = true;
    215                         break;
    216                     }
    217                 }
    218             }
    219         } else {
    220             File file = new File(filepath);
    221             isTargetExists = file.exists();
    222         }
    223         return isTargetExists;
    224     }
    225 
    226 
    227     /**
    228      * ファイルをコピーする
    229      * 
    230      * @param fromFile コピー元
    231      * @param toFile コピー先
    232      * @throws IOException 例外
    233      */
    234     private void copyFile(File fromFile, File toFile) throws IOException {
    235 
    236         FileInputStream fis = new FileInputStream(fromFile);
    237         FileOutputStream fos = new FileOutputStream(toFile);
    238         try {
    239             int byteRead = 0;
    240             byte[] buffer = new byte[1024];
    241             while ((byteRead = fis.read(buffer)) != -1) {
    242                 fos.write(buffer, 0, byteRead);
    243             }
    244         } finally {
    245             fis.close();
    246             fos.flush();
    247             fos.close();
    248         }
    249     }
    250 
    251     /**
    252      * CSVファイルをZIPに圧縮する用クラス
    253      * 
    254      * @author zang_yuling
    255      *
    256      */
    257     private static class ZipCompressor {
    258 
    259         private File zipFile;
    260 
    261 
    262         /**
    263          * コンストラクタ
    264          * 
    265          * @param pathName zipファイアのファイアパス
    266          */
    267         public ZipCompressor(String pathName) {
    268 
    269             zipFile = new File(pathName);
    270         }
    271 
    272 
    273         /**
    274          * ファイアを圧縮する
    275          * 
    276          * @param file 圧縮されたファイア名
    277          */
    278         public void compress(File file) {
    279 
    280             FileSet fileSet = new FileSet();
    281             Project prj = new Project();
    282             Zip zip = new Zip();
    283             zip.setProject(prj);
    284             zip.setDestFile(zipFile);
    285             fileSet.setProject(prj);
    286             fileSet.setDir(file);
    287             zip.addFileset(fileSet);
    288             zip.execute();
    289         }
    290 
    291     }
    292 
    293 }
  • 相关阅读:
    Python冒泡算法和修改配置文件
    第五章:处理数据
    第四章:持久存储
    Python之打印99乘法表
    Python之编写登录接口
    Python之文件操作
    第三章:文件与异常
    FineUI 修改config表属性
    FineUI Grid中WindowField根据列数据决定是否Enalble
    表之间不同字段的数据复制
  • 原文地址:https://www.cnblogs.com/niutouzdq/p/3929268.html
Copyright © 2020-2023  润新知