Java Code Examples for javax.servlet.http.HttpServletResponse#reset()

The following examples show how to use javax.servlet.http.HttpServletResponse#reset() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebTest.java    From easyexcel with Apache License 2.0 6 votes vote down vote up
/**
 * 文件下载并且失败的时候返回json(默认失败了会返回一个有部分数据的Excel)
 *
 * @since 2.1.1
 */
@GetMapping("downloadFailedUsingJson")
public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {
    // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
    try {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        // 这里需要设置不关闭流
        EasyExcel.write(response.getOutputStream(), DownloadData.class).autoCloseStream(Boolean.FALSE).sheet("模板")
            .doWrite(data());
    } catch (Exception e) {
        // 重置response
        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        Map<String, String> map = new HashMap<String, String>();
        map.put("status", "failure");
        map.put("message", "下载文件失败" + e.getMessage());
        response.getWriter().println(JSON.toJSONString(map));
    }
}
 
Example 2
Source File: ExternalPriceModelDisplayHandler.java    From development with Apache License 2.0 6 votes vote down vote up
private void displayPDF() throws IOException {
    HttpServletResponse response = (HttpServletResponse) this.facesContext
            .getExternalContext().getResponse();

    response.reset();
    response.setContentType(this.contentType);
    response.setContentLength(this.content.length);

    response.addHeader("Content-Disposition",
            this.getDisplayType(this.displayType) + "; " + "filename="
                    + this.filename);
    response.addHeader("Accept-Ranges", "bytes");

    BufferedOutputStream outputStream = new BufferedOutputStream(
            response.getOutputStream());
    outputStream.write(this.content);
    outputStream.flush();
    outputStream.close();

    facesContext.responseComplete();
}
 
Example 3
Source File: FirstTimeEnrolmentDocuments.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
public ActionForward showSummaryFile(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) {
    CandidacySummaryFile file = ((StudentCandidacy) getDomainObject(request, "candidacyID")).getSummaryFile();

    response.reset();
    try {
        response.getOutputStream().write(file.getContent());
        response.setContentLength(file.getContent().length);
        response.setContentType("application/pdf");
        response.flushBuffer();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }

    return null;
}
 
Example 4
Source File: OSSInterface.java    From charging_pile_cloud with MIT License 6 votes vote down vote up
/**
 * 获取图片
 *
 * @param response   服务端
 * @param bucketName 存储区域
 * @param firstKey   文件key
 * @throws IOException
 */
public void getPhoto(HttpServletResponse response, String bucketName, String firstKey) throws IOException {
    if (bucketName == null || bucketName.equals("")) {
        bucketName = bucketName_user;
    }
    try {
        InputStream fis = ossClient.getObject(bucketName, firstKey).getObjectContent();
        // 设置输出的格式
        response.reset();
        response.setContentType("image/png");
        // 循环取出流中的数据
        byte[] b = new byte[100];
        int len;
        while ((len = fis.read(b)) > 0) {
            response.getOutputStream().write(b, 0, len);
        }
        fis.close();
        ossClient.shutdown();
    } catch (IOException c) {
        c.printStackTrace();
    }

}
 
Example 5
Source File: QuestionPoolBean.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public String exportPool() {
	String poolId= ContextUtil.lookupParam("poolId");
	log.debug("exporting as Excel: poolid = {}", poolId);

	QuestionPoolService delegate = new QuestionPoolService();
	QuestionPoolFacade qPool =
			delegate.getPool(new Long(poolId), AgentFacade.getAgentString());

	// changed from above by gopalrc - Jan 2008
	// to allow local customization of spreadsheet output
	FacesContext faces = FacesContext.getCurrentInstance();
	HttpServletResponse response = (HttpServletResponse)faces.getExternalContext().getResponse();
	response.reset();	// Eliminate the added-on stuff
	response.setHeader("Pragma", "public");	// Override old-style cache control
	response.setHeader("Cache-Control", "public, must-revalidate, post-check=0, pre-check=0, max-age=0");	// New-style
	writeDataToResponse(getSpreadsheetData(poolId), getDownloadFileName(qPool.getDisplayName()), response);
	faces.responseComplete();

	return "";
}
 
Example 6
Source File: GenController.java    From ruoyiplus with MIT License 5 votes vote down vote up
/**
 * 批量生成代码
 */
@RequiresPermissions("tool:gen:code")
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/batchGenCode")
@ResponseBody
public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
    String[] tableNames = Convert.toStrArray(tables);
    byte[] data = genService.generatorCode(tableNames);
    response.reset();
    response.setHeader("Content-Disposition", "attachment; filename=\"ruoyi.zip\"");
    response.addHeader("Content-Length", "" + data.length);
    response.setContentType("application/octet-stream; charset=UTF-8");

    IOUtils.write(data, response.getOutputStream());
}
 
Example 7
Source File: DownloadEventBean.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
private void responseSettings(String filename, String mimetype, HttpServletResponse response) {
	// Stop IE from misbehaving
	response.reset(); // Eliminate the added-on stuff
	response.setHeader("Pragma", "public"); // Override old-style cache
	// control
	response.setHeader("Cache-Control",
			"public, must-revalidate, post-check=0, pre-check=0, max-age=0"); // New-style
	// Standard headers
	response.setContentType(mimetype);
	response.setHeader("Content-disposition", "attachment; filename=" + filename);
}
 
Example 8
Source File: BaseController.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
/**
 * 客户端返回字符串
 * @param response
 * @param string
 * @return
 */
protected String renderString(HttpServletResponse response, String string, String type) {
	try {
		response.reset();
        response.setContentType(type);
        response.setCharacterEncoding("utf-8");
		response.getWriter().print(string);
		return null;
	} catch (IOException e) {
		return null;
	}
}
 
Example 9
Source File: ExportExcelUtil.java    From SpringBoot-Home with Apache License 2.0 5 votes vote down vote up
/**
 * 导出文件时为Writer生成OutputStream
 */
private static OutputStream getOutputStream(String fileName, HttpServletResponse response) {
    response.reset();
    response.setContentType("application/vnd.ms-excel");
    try {
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName  + ".xlsx");
        return response.getOutputStream();
    } catch (IOException e) {
        throw new ExcelException("创建文件失败!");
    }
}
 
Example 10
Source File: SignupUIBaseBean.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Send a file for download. 
 * 
 * @param filePath
 * 
 */
protected void sendDownload(String filePath, String mimeType) {

	FacesContext fc = FacesContext.getCurrentInstance();
	ServletOutputStream out = null;
	FileInputStream in = null;
	
	String filename = StringUtils.substringAfterLast(filePath, File.separator);
	
	try {
		HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
		
		response.reset();
		response.setHeader("Pragma", "public");
		response.setHeader("Cache-Control","public, must-revalidate, post-check=0, pre-check=0, max-age=0"); 
		response.setContentType(mimeType);
		response.setHeader("Content-disposition", "attachment; filename=" + filename);
		
		in = FileUtils.openInputStream(new File(filePath));
		out = response.getOutputStream();

		IOUtils.copy(in, out);

		out.flush();
	} catch (IOException ex) {
		log.warn("Error generating file for download:" + ex.getMessage());
	} finally {
		IOUtils.closeQuietly(in);
		IOUtils.closeQuietly(out);
	}
	fc.responseComplete();
	
}
 
Example 11
Source File: NetdiskController.java    From SimpleBBS with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/download")
public void download(Integer fileId, HttpServletResponse response, HttpSession session) {

    Object obj = session.getAttribute("user");
    if (null == obj)
        return;
    User user = (User) obj;
    try {
        File file = fileService.findFileById(fileId);
        if (file.getState() == 0 || file.getUser().getUid() != user.getUid())
            return;
        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getFileName(), "UTF-8"));
        response.setHeader("Connection", "close");
        response.setHeader("Content-Type", "application/octet-stream");

        OutputStream os = response.getOutputStream();
        java.io.File diskFile = new java.io.File(fileUploadProperteis.getUploadFolder()+"/"+file.getFilePath().split("/")[2]);
        FileInputStream fis = new FileInputStream(diskFile);
        response.setHeader("Content-Length", String.valueOf(diskFile.length()));
        byte[] buf = new byte[(int) diskFile.length()];
        fis.read(buf);
        os.write(buf);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 12
Source File: SysGeneratorController.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
/**
 * 生成代码FileUtil
 */
@GetMapping("/code")
public void makeCode(String tables, HttpServletResponse response) throws IOException {
    byte[] data = sysGeneratorService.generatorCode(tables.split(","));
    response.reset();
    response.setHeader("Content-Disposition", "attachment; filename=\"generator.zip\"");
    response.addHeader("Content-Length", "" + data.length);
    response.setContentType("application/octet-stream; charset=UTF-8");
    IOUtils.write(data, response.getOutputStream());
}
 
Example 13
Source File: SysGeneratorController.java    From smaker with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 生成代码
 */
@PostMapping("/code")
public void code(@RequestBody GenConfig genConfig, HttpServletResponse response) throws IOException {
	byte[] data = sysGeneratorService.generatorCode(genConfig);

	response.reset();
	response.setHeader("Content-Disposition", String.format("attachment; filename=%s.zip", genConfig.getTableName()));
	response.addHeader("Content-Length", "" + data.length);
	response.setContentType("application/octet-stream; charset=UTF-8");

	IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
}
 
Example 14
Source File: SignupUIBaseBean.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Send a file for download. 
 * 
 * @param filePath
 * 
 */
protected void sendDownload(String filePath, String mimeType) {

	FacesContext fc = FacesContext.getCurrentInstance();
	ServletOutputStream out = null;
	FileInputStream in = null;
	
	String filename = StringUtils.substringAfterLast(filePath, File.separator);
	
	try {
		HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
		
		response.reset();
		response.setHeader("Pragma", "public");
		response.setHeader("Cache-Control","public, must-revalidate, post-check=0, pre-check=0, max-age=0"); 
		response.setContentType(mimeType);
		response.setHeader("Content-disposition", "attachment; filename=" + filename);
		
		in = FileUtils.openInputStream(new File(filePath));
		out = response.getOutputStream();

		IOUtils.copy(in, out);

		out.flush();
	} catch (IOException ex) {
		log.warn("Error generating file for download:" + ex.getMessage());
	} finally {
		IOUtils.closeQuietly(in);
		IOUtils.closeQuietly(out);
	}
	fc.responseComplete();
	
}
 
Example 15
Source File: FileController.java    From DAFramework with MIT License 5 votes vote down vote up
@RequestMapping(value = "/download/{id}")
	public void downloadFile(@PathVariable Long id,HttpServletRequest request, HttpServletResponse response) throws Exception {
		try{
        	if(id != 0){
        		EFile fileInfo = fileDao.fetch(id);
        		if(fileInfo!= null){
        			String path = fileInfo.getPath();
//        			String suffix = path.split("\\.")[1];
					File file = new File(rootPath+path);
//                    String filename = fileInfo.getName()+"."+suffix;
                    InputStream fis = new BufferedInputStream(new FileInputStream(file));
                    byte[] buffer = new byte[fis.available()];
                    fis.read(buffer);
                    fis.close();
                    response.reset();
                    response.addHeader("Content-Disposition","attachment;filename="
                            + new String(java.net.URLEncoder.encode(fileInfo.getName(), "UTF-8")));
                    response.addHeader("Content-Length","" + file.length());
                    response.setContentType("application/octet-stream");
                    OutputStream toClient = new BufferedOutputStream(
                            response.getOutputStream());
                    toClient.write(buffer);
                    toClient.flush();
                    toClient.close();
        		}
        	}
        }catch(Exception e){
			LOG.error("下载失败,原因:"+e.getMessage());
		}
	}
 
Example 16
Source File: CodeGenController.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 生成代码
 */
@SneakyThrows
@PostMapping("")
public void generatorCode(@RequestBody GenConfig genConfig, HttpServletResponse response) {
    byte[] data = codeGenService.generatorCode(genConfig);

    response.reset();
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", genConfig.getTableName()));
    response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
    response.setContentType("application/octet-stream; charset=UTF-8");

    IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
}
 
Example 17
Source File: FileStreamingUtil.java    From hawkbit with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * <p>
 * Write response with target relation and publishes events concerning the
 * download progress based on given update action status.
 * </p>
 *
 * <p>
 * The request supports RFC7233 range requests.
 * </p>
 *
 * @param artifact
 *            the artifact
 * @param filename
 *            to be written to the client response
 * @param lastModified
 *            unix timestamp of the artifact
 * @param response
 *            to be sent back to the requesting client
 * @param request
 *            from the client
 * @param progressListener
 *            to write progress updates to
 *
 * @return http response
 *
 * @see <a href="https://tools.ietf.org/html/rfc7233">https://tools.ietf.org
 *      /html/rfc7233</a>
 * 
 * @throws FileStreamingFailedException
 *             if streaming fails
 */
public static ResponseEntity<InputStream> writeFileResponse(final AbstractDbArtifact artifact,
        final String filename, final long lastModified, final HttpServletResponse response,
        final HttpServletRequest request, final FileStreamingProgressListener progressListener) {

    ResponseEntity<InputStream> result;

    final String etag = artifact.getHashes().getSha1();
    final long length = artifact.getSize();

    response.reset();
    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + filename);
    response.setHeader(HttpHeaders.ETAG, etag);
    response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
    // set the x-content-type options header to prevent browsers from doing
    // MIME-sniffing when downloading an artifact, as this could cause a
    // security vulnerability
    response.setHeader(com.google.common.net.HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff");
    if (lastModified > 0) {
        response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModified);
    }

    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
    response.setBufferSize(BUFFER_SIZE);

    final ByteRange full = new ByteRange(0, length - 1, length);
    final List<ByteRange> ranges = new ArrayList<>();

    // Validate and process Range and If-Range headers.
    final String range = request.getHeader("Range");
    if (lastModified > 0 && range != null) {
        LOG.debug("range header for filename ({}) is: {}", filename, range);

        // Range header matches"bytes=n-n,n-n,n-n..."
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + length);
            LOG.debug("range header for filename ({}) is not satisfiable: ", filename);
            return new ResponseEntity<>(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE);
        }

        // RFC: if the representation is unchanged, send me the part(s) that
        // I am requesting in
        // Range; otherwise, send me the entire representation.
        checkForShortcut(request, etag, lastModified, full, ranges);

        // it seems there are valid ranges
        result = extractRange(response, length, ranges, range);
        // return if range extraction turned out to be invalid
        if (result != null) {
            return result;
        }
    }

    // full request - no range
    if (ranges.isEmpty() || ranges.get(0).equals(full)) {
        LOG.debug("filename ({}) results into a full request: ", filename);
        result = handleFullFileRequest(artifact, filename, response, progressListener, full);
    }
    // standard range request
    else if (ranges.size() == 1) {
        LOG.debug("filename ({}) results into a standard range request: ", filename);
        result = handleStandardRangeRequest(artifact, filename, response, progressListener, ranges);
    }
    // multipart range request
    else {
        LOG.debug("filename ({}) results into a multipart range request: ", filename);
        result = handleMultipartRangeRequest(artifact, filename, response, progressListener, ranges);
    }

    return result;
}
 
Example 18
Source File: CMSURLHandler.java    From fenixedu-cms with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void handleRequest(Site site, HttpServletRequest req, HttpServletResponse res, String pageSlug) throws IOException,
        ServletException {

    if (site.getCanViewGroup().isMember(Authenticate.getUser()) || PermissionEvaluation.canAccess(Authenticate.getUser(),site)) {
        if (site.getPublished()) {
            try {
                String baseUrl = "/" + site.getBaseUrl();
                if (pageSlug.startsWith(baseUrl)) {
                    pageSlug = pageSlug.substring(baseUrl.length());
                }
                if (pageSlug.endsWith("/") && !req.getRequestURI().equals(req.getContextPath() + "/")) {
                    handleLeadingSlash(req, res, site);
                } else if (pageSlug.startsWith("/static/")) {
                    handleStaticResource(req, res, site, pageSlug);
                } else if (pageSlug.startsWith("/rss")) {
                    handleRSS(req, res, site, pageSlug);
                } else {
                    renderer.renderCMSPage(req, res, site, pageSlug);
                }
            } catch (Exception e) {
                logger.error("Exception while rendering CMS page " + req.getRequestURI(), e);
                if (res.isCommitted()) {
                    return;
                }
                res.reset();
                res.resetBuffer();
                renderer.errorPage(req, res, site, 500);
            }
        } else {
            if (Authenticate.isLogged()) {
                renderer.errorPage(req, res, site, 403);
            } else {
                renderer.errorPage(req, res, site, 401);
            }
            return;
        }
    } else {
        if (Authenticate.isLogged()) {
            renderer.errorPage(req, res, site, 403);
        } else {
            renderer.errorPage(req, res, site, 401);
        }
        return;
    }
}
 
Example 19
Source File: CgformSqlController.java    From jeecg with Apache License 2.0 4 votes vote down vote up
/**
 * 导出 Form(采用XML方式)
 * 
 * @return
 * @throws SQLException
 */
@RequestMapping(params = "doMigrateOut")
public void doMigrateOut(HttpServletRequest request,HttpServletResponse response){
	String ids = request.getParameter("ids"); // 获得选择表单ID
	//List<String> listSQL = new ArrayList<String>();
	try {
		//listSQL = MigrateForm.createSQL(ids, jdbcTemplate);// 创建查询语句
		//MigrateForm.executeSQL(listSQL, jdbcTemplate);// 生成sql并拼装
		List<DBTable> dbTables = MigrateForm.buildExportDbTableList(ids, jdbcTemplate);  //创建导出的数据对象
		//MigrateForm.generateXmlDataOutFlieContent(ids, jdbcDao);
		//update by duanqilu 2013-12-05 增加多表单导出功能
		String ls_id="";
		if(ids.indexOf(",")>0){
			ls_id=ids.substring(0, ids.indexOf(","));
		}
		else{
			ls_id = ids;
		}
		CgFormHeadEntity cgFormHeadEntity = cgFormVersionDao.getCgFormById(ls_id);
		//update by duanqilu 2013-12-05 增加多表单导出功能
		//MigrateForm.createFile(request,cgFormHeadEntity.getTableName())
		String ls_filename = cgFormHeadEntity.getTableName();// 创建文件
		String destFileDir = ResourceUtil.getSystempPath()+File.separator+ls_filename;
		MigrateForm.generateXmlDataOutFlieContent(dbTables, destFileDir);
		ls_filename = MigrateForm.zip(null, "", destFileDir); // 压缩文件
		// 文件下载
		File file = new File(ls_filename);
		String filename = file.getName();
		InputStream fis = new BufferedInputStream(new FileInputStream(ls_filename));
		// 输出生成的zip文件
		// 清空response
		response.reset();
		// 设置response的Header
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		response.addHeader("Content-Length", "" + file.length());
		OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
		response.setContentType("application/octet-stream");
		response.setHeader("Content-disposition", "attachment;filename="
				+ new String(filename.getBytes("utf-8"), "ISO8859-1"));
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
			toClient.write(buffer, 0, bytesRead);
		}
		toClient.write(buffer);
		toClient.flush();
		toClient.close();
		fis.close();
		logger.info("["+IpUtil.getIpAddr(request)+"][online表单配置导出]");
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 20
Source File: SpreadsheetUtil.java    From sakai with Educational Community License v2.0 2 votes vote down vote up
/**
 * Try to head off a problem with downloading files from a secure HTTPS
 * connection to Internet Explorer.
 *
 * When IE sees it's talking to a secure server, it decides to treat all hints
 * or instructions about caching as strictly as possible. Immediately upon
 * finishing the download, it throws the data away.
 *
 * Unfortunately, the way IE sends a downloaded file on to a helper
 * application is to use the cached copy. Having just deleted the file,
 * it naturally isn't able to find it in the cache. Whereupon it delivers
 * a very misleading error message like:
 * "Internet Explorer cannot download roster from sakai.yoursite.edu.
 * Internet Explorer was not able to open this Internet site. The requested
 * site is either unavailable or cannot be found. Please try again later."
 *
 * There are several ways to turn caching off, and so to be safe we use
 * several ways to turn it back on again.
 *
 * This current workaround should let IE users save the files to disk.
 * Unfortunately, errors may still occur if a user attempts to open the
 * file directly in a helper application from a secure web server.
 *
 * TODO Keep checking on the status of this.
 */
private static void protectAgainstInstantDeletion(HttpServletResponse response) {
    response.reset();	// Eliminate the added-on stuff
    response.setHeader("Pragma", "public");	// Override old-style cache control
    response.setHeader("Cache-Control", "public, must-revalidate, post-check=0, pre-check=0, max-age=0");	// New-style
}