美文网首页
HttpServletRequest和HttpServletRe

HttpServletRequest和HttpServletRe

作者: 吃猫的鱼0 | 来源:发表于2018-01-17 17:50 被阅读0次

    HttpServletRequest

    获取参数列表

    request.getParameterMap(); 
    

    获取路径中参数的值

    Map< String, String>urlMap=(Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
    

    获取请求的路径

    request.getRequestURI().replace(request.getContextPath(), "");
    

    HttpServletResponse

    添加返回的文件

    //添加文件名称
    String name="悠果聚1.1"+".apk";
    if(request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0){
        name = URLEncoder.encode(name, "UTF-8");//IE浏览器
       }else {
        name = new String(name.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器||gool
    }
        response.reset();//如果有换行,对于文本文件没有什么问题,但是对于其它格
    response.setContentType("application/x-msdownload");
    response.setHeader("Content-Disposition", "attachment;filename="+name);
    

    写入文件流

    方法一:
    outputStream= response.getOutputStream();
    /**
     * 将文件写到outputStream中
     * 
     * @param outputStream
     *            写入的outstream
     * @param localpath
     *            本地地址
     * @throws IOException
     */
    private void getFile(OutputStream outputStream, String localpath)
            throws IOException {
        File file = new File(localpath);
        FileInputStream fileInputStream = null;
        fileInputStream = new FileInputStream(file);
        byte[] cotent = new byte[1024 * 1024];
        int readsize;
        boolean err = false;
        while ((readsize = fileInputStream.read(cotent)) != -1) {
            try {
                outputStream.write(cotent, 0, readsize);
            } catch (Exception e) {
                err = true;
                break;
            }
        }
        // 防止出现Connection reset by peer: socket write error
        // 出现这个原因是客户端的请求突然关闭引起的
        if (err) {
            // System.out.println("下载出错了哦");
            // outputStream.flush();
            // outputStream.close();
            fileInputStream.close();
            System.gc();
        } else {
            // System.out.println("下载没有错误");
            outputStream.flush();
            outputStream.close();
            fileInputStream.close();
        }
    }
    方法二:
    response.getOutputStream().write(bytes);//将文件写入 response

    相关文章

      网友评论

          本文标题:HttpServletRequest和HttpServletRe

          本文链接:https://www.haomeiwen.com/subject/fwvuoxtx.html