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

The following examples show how to use javax.servlet.http.HttpServletResponse#setHeader() . These examples are extracted from open source projects. 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 Project: cloudstack   File: HttpUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void addSecurityHeaders(final HttpServletResponse resp) {
    if (resp.containsHeader("X-Content-Type-Options")) {
        resp.setHeader("X-Content-Type-Options", "nosniff");
    }
    else {
        resp.addHeader("X-Content-Type-Options", "nosniff");
    }
    if (resp.containsHeader("X-XSS-Protection")) {
        resp.setHeader("X-XSS-Protection", "1;mode=block");
    }
    else {
        resp.addHeader("X-XSS-Protection", "1;mode=block");
    }

    if (resp.containsHeader("content-security-policy")) {
        resp.setIntHeader("content-security-policy", 1);
    }else {
        resp.addIntHeader("content-security-policy", 1);
    }
    resp.addHeader("content-security-policy","default-src=none");
    resp.addHeader("content-security-policy","script-src=self");
    resp.addHeader("content-security-policy","connect-src=self");
    resp.addHeader("content-security-policy","img-src=self");
    resp.addHeader("content-security-policy","style-src=self");
}
 
Example 2
private Object writeSvg(String suggestedFilenameStem,
                        byte[] dataBytes,
                        Response response) throws IOException {
    HttpServletResponse httpResponse = response.raw();

    httpResponse.setHeader("Content-Type", "image/svg+xml");
    httpResponse.setHeader("Content-Disposition", "attachment; filename=" + suggestedFilenameStem + ".svg");
    httpResponse.setHeader("Content-Transfer-Encoding", "7bit");

    httpResponse.setContentLength(dataBytes.length);
    httpResponse.getOutputStream().write(dataBytes);
    httpResponse.getOutputStream().flush();
    httpResponse.getOutputStream().close();

    return httpResponse;
}
 
Example 3
public ActionForward prepareExecutePrintCandidacies(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment; filename=" + getReportFilename());

    final ServletOutputStream writer = response.getOutputStream();
    final Over23CandidacyProcess process = getProcess(request);
    final Spreadsheet spreadsheet = buildReport(process.getOver23IndividualCandidaciesThatCanBeSendToJury());

    spreadsheet.exportToXLSSheet(writer);
    writer.flush();
    response.flushBuffer();

    return null;
}
 
Example 4
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
    String fileName = httpServletRequest.getParameter("fileName");
    if(fileName!=null){
        if(!fileName.endsWith(".xls")){
            fileName += ".xls" ;
        }
    }else{
        fileName = "default.xls";
    }
    log.info("{}",fileName);
    httpServletResponse.setContentType("application/vnd.ms-excel");
    httpServletResponse.setHeader("Content-Disposition", "attachment;filename="+fileName);
    httpServletResponse.setContentType("utf-8");
    return true;
}
 
Example 5
Source Project: frpMgr   File: ServletUtils.java    License: MIT License 6 votes vote down vote up
/**
 * 根据浏览器 If-None-Match Header, 计算Etag是否已无效.
 * 如果Etag有效, checkIfNoneMatch返回false, 设置304 not modify status.
 * @param etag 内容的ETag.
 */
public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response, String etag) {
	String headerValue = request.getHeader(HttpHeaders.IF_NONE_MATCH);
	if (headerValue != null) {
		boolean conditionSatisfied = false;
		if (!"*".equals(headerValue)) {
			StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");

			while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
				String currentToken = commaTokenizer.nextToken();
				if (currentToken.trim().equals(etag)) {
					conditionSatisfied = true;
				}
			}
		} else {
			conditionSatisfied = true;
		}

		if (conditionSatisfied) {
			response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
			response.setHeader(HttpHeaders.ETAG, etag);
			return false;
		}
	}
	return true;
}
 
Example 6
Source Project: xipki   File: HealthCheckServlet.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
    throws ServletException, IOException {
  resp.setHeader("Access-Control-Allow-Origin", "*");

  try {
    String path = (String) req.getAttribute(HttpConstants.ATTR_XIPKI_PATH);

    ResponderAndPath responderAndPath = server.getResponderForPath(path);
    if (responderAndPath == null) {
      resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
      resp.setContentLength(0);
      return;
    }

    HealthCheckResult healthResult = server.healthCheck(responderAndPath.getResponder());
    int status = healthResult.isHealthy()
        ? HttpServletResponse.SC_OK : HttpServletResponse.SC_INTERNAL_SERVER_ERROR;

    byte[] respBytes = JSON.toJSONBytes(healthResult);
    resp.setStatus(status);
    resp.setContentType(HealthCheckServlet.CT_RESPONSE);
    resp.setContentLength(respBytes.length);
    resp.getOutputStream().write(respBytes);
  } catch (Throwable th) {
    if (th instanceof EOFException) {
      LogUtil.warn(LOG, th, "connection reset by peer");
    } else {
      LOG.error("Throwable thrown, this should not happen", th);
    }
    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    resp.setContentLength(0);
  } finally {
    resp.flushBuffer();
  }
}
 
Example 7
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
        throws IOException, ServletException {


    String ajaxRequestHeader = request.getHeader("X-Requested-With");
    response.setHeader("X-Frame-Options", "DENY");

    if ("XMLHttpRequest".equals(ajaxRequestHeader)) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } else {
        LOG.debug("redirecting to login page loginPath" + loginPath);
        response.sendRedirect(loginPath);
    }
}
 
Example 8
/**
 * Sends an error to the client.
 *
 * @param e The exception that caused the problem.
 * @param rs The <code>ReqState</code> for the client.
 */

public void anyExceptionHandler(Throwable e, ReqState rs) {
  try {
    log.error("DODServlet ERROR (anyExceptionHandler): " + e);
    printThrowable(e);
    // Strip any double quotes out of the parser error message.
    // These get stuck in auto-magically by the javacc generated parser
    // code and they break our error parser (bummer!)
    String msg = e.getMessage();
    if (msg != null)
      msg = msg.replace('\"', '\'');

    if (rs != null) {
      HttpServletResponse response = rs.getResponse();
      log.error(rs + "");
      if (track) {
        RequestDebug reqD = (RequestDebug) rs.getUserObject();
        log.error("  request number: " + reqD.reqno + " thread: " + reqD.threadDesc);
      }
      BufferedOutputStream eOut = new BufferedOutputStream(response.getOutputStream());
      response.setHeader("Content-Description", "dods-error");

      // This should probably be set to "plain" but this works, the
      // C++ slients don't barf as they would if I sent "plain" AND
      // the C++ don't expect compressed data if I do this...
      response.setHeader("Content-Encoding", "");

      DAP2Exception de2 = new DAP2Exception(opendap.dap.DAP2Exception.UNDEFINED_ERROR, msg);
      de2.print(eOut);
    }

  } catch (IOException ioe) {
    log.error("Cannot respond to client! IO Error: " + ioe.getMessage());
  }

}
 
Example 9
@Override
	public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
		httpServletResponse.setHeader("Content-type", "application/json;charset=UTF-8");
//		httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		// 如果这里状态改为HttpServletResponse.SC_UNAUTHORIZED 会导致feign之间调用异常 see https://xujin.org/sc/sc-feign-4xx/
		httpServletResponse.setStatus(HttpServletResponse.SC_OK);
		LogBack.error("用户没有登录时返回给前端的数据");
		JsonData jsonData =  new JsonData(StatusEnum.LOGIN_EXPIRED);
		httpServletResponse.getWriter().write(JsonUtil.toJsonString(jsonData));
	}
 
Example 10
@SuppressWarnings("rawtypes")
@Override
public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
	Integer sc = (Integer) model.get(SC_KEY);
	if (sc == null) {
		sc = DEFAULT_SC;
	}
	response.setStatus(sc.intValue());

	response.setContentType(getContentType());

	if (model.containsKey(CUSTOM_HEADERS_KEY)) {
		Map<String, String> customHeaders = (Map<String, String>) model.get(CUSTOM_HEADERS_KEY);
		if (customHeaders != null) {
			for (String headerName : customHeaders.keySet()) {
				response.setHeader(headerName, customHeaders.get(headerName));
			}
		}
	}

	try (OutputStream out = response.getOutputStream()) {
		String content = (String) model.get(CONTENT_KEY);
		if (content != null) {
			byte[] contentBytes = content.getBytes("UTF-8");
			response.setContentLength(contentBytes.length);
			out.write(contentBytes);
		} else {
			response.setContentLength(0);
		}
	}
}
 
Example 11
Source Project: apiman   File: HttpCacheUtil.java    License: Apache License 2.0 5 votes vote down vote up
static void disableHttpCaching(HttpServletResponse httpResponse) {
    Date now = new Date();
    httpResponse.setDateHeader("Date", now.getTime()); //$NON-NLS-1$
    httpResponse.setDateHeader("Expires", expiredSinceYesterday(now)); //$NON-NLS-1$
    httpResponse.setHeader("Pragma", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
    httpResponse.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-1$ //$NON-NLS-2$
}
 
Example 12
Source Project: es   File: PushController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取页面的提示信息
 * @return
 */
@RequestMapping(value = "/admin/polling")
@ResponseBody
public Object polling(HttpServletResponse resp, @CurrentUser User user) {
    resp.setHeader("Connection", "Keep-Alive");
    resp.addHeader("Cache-Control", "private");
    resp.addHeader("Pragma", "no-cache");

    Long userId = user.getId();
    if(userId == null) {
        return null;
    }
    //如果用户第一次来 立即返回
    if(!pushService.isOnline(userId)) {
        Long unreadMessageCount = messageApi.countUnread(userId);
        List<Map<String, Object>> notifications = notificationApi.topFiveNotification(user.getId());

        Map<String, Object> data = Maps.newHashMap();
        data.put("unreadMessageCount", unreadMessageCount);
        data.put("notifications", notifications);
        pushService.online(userId);
        return data;
    } else {
        //长轮询
        return pushService.newDeferredResult(userId);
    }
}
 
Example 13
@Override
protected final void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // ファイル名に日本語を含めても文字化けしないようにUTF-8にエンコードする
    val encodedFilename = EncodeUtils.encodeUtf8(filename);
    val contentDisposition = String.format("attachment; filename*=UTF-8''%s", encodedFilename);

    response.setHeader(CONTENT_TYPE, getContentType());
    response.setHeader(CONTENT_DISPOSITION, contentDisposition);

    // CSVヘッダをオブジェクトから作成する
    CsvSchema schema = csvMapper.schemaFor(clazz).withHeader();

    if (isNotEmpty(columns)) {
        // カラムが指定された場合は、スキーマを再構築する
        val builder = schema.rebuild().clearColumns();
        for (String column : columns) {
            builder.addColumn(column);
        }
        schema = builder.build();
    }

    // 書き出し
    val outputStream = createTemporaryOutputStream();
    try (Writer writer = new OutputStreamWriter(outputStream, "Windows-31J")) {
        csvMapper.writer(schema).writeValue(writer, data);
    }
}
 
Example 14
public ActionForward exportXLS(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    ExternalSupervisorViewsBean bean = getRenderedObject("sessionBean");
    final Spreadsheet spreadsheet = generateSpreadsheet(bean);

    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-disposition", "attachment; filename=" + getFilename(bean) + ".xls");
    spreadsheet.exportToXLSSheet(response.getOutputStream());
    response.getOutputStream().flush();
    response.flushBuffer();
    return null;
}
 
Example 15
Source Project: EasyCaptcha   File: CaptchaUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 设置相应头
 *
 * @param response HttpServletResponse
 */
public static void setHeader(HttpServletResponse response) {
    response.setContentType("image/gif");
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
}
 
Example 16
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	assertTrue("Invalid request content-length", request.getContentLength() > 0);
	assertNotNull("No content-type", request.getContentType());
	String body = FileCopyUtils.copyToString(request.getReader());
	assertEquals("Invalid request body", s, body);
	response.setStatus(HttpServletResponse.SC_CREATED);
	response.setHeader("Location", baseUrl + location);
	response.setContentLength(buf.length);
	response.setContentType(contentType.toString());
	FileCopyUtils.copy(buf, response.getOutputStream());
}
 
Example 17
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
	
		java.util.Map<String,String[]> map = request.getParameterMap();
		String param = "";
		if (!map.isEmpty()) {
			String[] values = map.get("BenchmarkTest00476");
			if (values != null) param = values[0];
		}
		
		
		
		String bar;
		
		// Simple ? condition that assigns constant to bar on true condition
		int num = 106;
		
		bar = (7*18) + num > 200 ? "This_should_always_happen" : param;
		
		
		
response.setHeader("X-XSS-Protection", "0");
		response.getWriter().println(bar);
	}
 
Example 18
/**
 * Creates a PDF document based on the PO information and the items that were selected by the user on the Purchase Order
 * Retransmit Document page to be retransmitted, then display the PDF to the browser.
 *
 * @param mapping An ActionMapping
 * @param form An ActionForm
 * @param request The HttpServletRequest
 * @param response The HttpServletResponse
 * @throws Exception
 * @return An ActionForward
 */
public ActionForward printingRetransmitPoOnly(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

    String selectedItemIndexes = request.getParameter("selectedItemIndexes");
    String documentNumber = request.getParameter("poDocumentNumberForRetransmit");
    PurchaseOrderDocument po = SpringContext.getBean(PurchaseOrderService.class).getPurchaseOrderByDocumentNumber(documentNumber);
    String retransmitHeader = request.getParameter("retransmitHeader");

    // setting the isItemSelectedForRetransmitIndicator items of the PO obtained from the database based on its value from
    // the po from the form

    setItemSelectedForRetransmitIndicatorFromPOInForm(selectedItemIndexes, po.getItems());
    po.setRetransmitHeader(retransmitHeader);
    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    try {
        StringBuffer sbFilename = new StringBuffer();
        sbFilename.append("PURAP_PO_");
        sbFilename.append(po.getPurapDocumentIdentifier());
        sbFilename.append("_");
        sbFilename.append(System.currentTimeMillis());
        sbFilename.append(".pdf");

        // below method will throw ValidationException if errors are found
        SpringContext.getBean(PurchaseOrderService.class).retransmitPurchaseOrderPDF(po, baosPDF);

        response.setHeader("Cache-Control", "max-age=30");
        response.setContentType("application/pdf");
        StringBuffer sbContentDispValue = new StringBuffer();
        sbContentDispValue.append("inline");
        sbContentDispValue.append("; filename=");
        sbContentDispValue.append(sbFilename);

        response.setHeader("Content-disposition", sbContentDispValue.toString());

        response.setContentLength(baosPDF.size());

        ServletOutputStream sos;

        sos = response.getOutputStream();

        baosPDF.writeTo(sos);

        sos.flush();

    }
    catch (ValidationException e) {
        LOG.warn("Caught ValidationException while trying to retransmit PO with doc id " + po.getDocumentNumber());
        return mapping.findForward(KFSConstants.MAPPING_ERROR);
    }
    finally {
        if (baosPDF != null) {
            baosPDF.reset();
        }
    }

    return null;
}
 
Example 19
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    response.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Origin, Authorization, appId, serviceId");
    response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    super.afterCompletion(request, response, handler, ex);
}
 
Example 20
@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
	
		String param = "";
		java.util.Enumeration<String> headers = request.getHeaders("Referer");
		
		if (headers != null && headers.hasMoreElements()) {
			param = headers.nextElement(); // just grab first element
		}
		
		// URL Decode the header value since req.getHeaders() doesn't. Unlike req.getParameters().
		param = java.net.URLDecoder.decode(param, "UTF-8");
		
		
		String bar = org.owasp.esapi.ESAPI.encoder().encodeForHTML(param);
		
		
response.setHeader("X-XSS-Protection", "0");
		response.getWriter().println(bar.toCharArray());
	}