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

The following examples show how to use javax.servlet.http.HttpServletResponse#getContentType() . 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
private void writeHeaders(HttpServletResponse servletResponse) {
	this.headers.forEach((headerName, headerValues) -> {
		for (String headerValue : headerValues) {
			servletResponse.addHeader(headerName, headerValue);
		}
	});
	// HttpServletResponse exposes some headers as properties: we should include those if not already present
	if (servletResponse.getContentType() == null && this.headers.getContentType() != null) {
		servletResponse.setContentType(this.headers.getContentType().toString());
	}
	if (servletResponse.getCharacterEncoding() == null &&
			this.headers.getContentType() != null &&
			this.headers.getContentType().getCharset() != null) {
		servletResponse
				.setCharacterEncoding(this.headers.getContentType().getCharset().name());
	}
}
 
Example 2
@Override
protected void applyHeaders() {
	HttpServletResponse response = getNativeResponse();
	MediaType contentType = getHeaders().getContentType();
	if (response.getContentType() == null && contentType != null) {
		response.setContentType(contentType.toString());
	}
	Charset charset = (contentType != null ? contentType.getCharset() : null);
	if (response.getCharacterEncoding() == null && charset != null) {
		response.setCharacterEncoding(charset.name());
	}
	long contentLength = getHeaders().getContentLength();
	if (contentLength != -1) {
		response.setContentLengthLong(contentLength);
	}
}
 
Example 3
@Override
protected void applyHeaders() {
	MediaType contentType = getHeaders().getContentType();
	HttpServletResponse response = getNativeResponse();
	if (response.getContentType() == null && contentType != null) {
		response.setContentType(contentType.toString());
	}
	Charset charset = (contentType != null ? contentType.getCharset() : null);
	if (response.getCharacterEncoding() == null && charset != null) {
		response.setCharacterEncoding(charset.name());
	}
	long contentLength = getHeaders().getContentLength();
	if (contentLength != -1) {
		response.setContentLengthLong(contentLength);
	}
}
 
Example 4
Source Project: Doradus   File: RESTServlet.java    License: Apache License 2.0 6 votes vote down vote up
private void sendResponse(HttpServletResponse servletResponse, RESTResponse restResponse) throws IOException {
    servletResponse.setStatus(restResponse.getCode().getCode());
    
    Map<String, String> responseHeaders = restResponse.getHeaders();
    if (responseHeaders != null) {
        for (Map.Entry<String, String> mapEntry : responseHeaders.entrySet()) {
            if (mapEntry.getKey().equalsIgnoreCase(HttpDefs.CONTENT_TYPE)) {
                servletResponse.setContentType(mapEntry.getValue());
            } else {
                servletResponse.setHeader(mapEntry.getKey(), mapEntry.getValue());
            }
        }
    }
    
    byte[] bodyBytes = restResponse.getBodyBytes();
    int bodyLen = bodyBytes == null ? 0 : bodyBytes.length;
    servletResponse.setContentLength(bodyLen);
    
    if (bodyLen > 0 && servletResponse.getContentType() == null) {
        servletResponse.setContentType("text/plain");
    }
    
    if (bodyLen > 0) {
        servletResponse.getOutputStream().write(restResponse.getBodyBytes());
    }
}
 
Example 5
@Override
protected void applyHeaders() {
	MediaType contentType = getHeaders().getContentType();
	HttpServletResponse response = getNativeResponse();
	if (response.getContentType() == null && contentType != null) {
		response.setContentType(contentType.toString());
	}
	Charset charset = (contentType != null ? contentType.getCharset() : null);
	if (response.getCharacterEncoding() == null && charset != null) {
		response.setCharacterEncoding(charset.name());
	}
	long contentLength = getHeaders().getContentLength();
	if (contentLength != -1) {
		response.setContentLengthLong(contentLength);
	}
}
 
Example 6
private void sendFallback(Integer size, HttpServletResponse response) throws IOException {
    if (response.getContentType() == null) {
        response.setContentType(StringUtil.getMimeType("jpeg"));
    }
    InputStream in = null;
    try {
        in = getClass().getResourceAsStream("default_cover.jpg");
        BufferedImage image = ImageIO.read(in);
        if (size != null) {
            image = scale(image, size, size);
        }
        ImageIO.write(image, "jpeg", response.getOutputStream());
    } finally {
        FileUtil.closeQuietly(in);
    }
}
 
Example 7
private void sendFallback(Integer size, HttpServletResponse response) throws IOException {
    if (response.getContentType() == null) {
        response.setContentType(StringUtil.getMimeType("jpeg"));
    }
    InputStream in = null;
    try {
        in = getClass().getResourceAsStream("default_cover.jpg");
        BufferedImage image = ImageIO.read(in);
        if (size != null) {
            image = scale(image, size, size);
        }
        ImageIO.write(image, "jpeg", response.getOutputStream());
    } finally {
        IOUtils.closeQuietly(in);
    }
}
 
Example 8
private void sendFallback(Integer size, HttpServletResponse response) throws IOException {
    if (response.getContentType() == null) {
        response.setContentType(StringUtil.getMimeType("jpeg"));
    }
    try (InputStream in = getClass().getResourceAsStream("default_cover.jpg")) {
        BufferedImage image = ImageIO.read(in);
        if (size != null) {
            image = scale(image, size, size);
        }
        ImageIO.write(image, "jpeg", response.getOutputStream());
    }
}
 
Example 9
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    if (response instanceof HttpServletResponse) {
        final PrintWriter out = response.getWriter();
        final HttpServletResponse wrapper = (HttpServletResponse) response;
        chain.doFilter(request, wrapper);
        final String origData = wrapper.getContentType();
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "Hello");
        }
        if ("text/html".equals(wrapper.getContentType())) {
            final CharArrayWriter caw = new CharArrayWriter();
            final int bodyIndex = origData.indexOf("</body>");
            if (-1 != bodyIndex) {
                caw.write(origData.substring(0, bodyIndex - 1));
                caw.write("\n<p>My custom footer</p>");
                caw.write("\n</body></html>");
                response.setContentLength(caw.toString().length());
                out.write(caw.toString());
            } else {
                out.write(origData);
            }
        } else {
            out.write(origData);
        }
        out.close();
    } else {
        chain.doFilter(request, response);
    }
}
 
Example 10
/**
 * Create a servlet response using the various values and codes stored in the given one,
 * makes copies mostly
 * @param response any valid response, cannot be null
 */
public EntityHttpServletResponse(HttpServletResponse response) {
    this.content = new ByteArrayOutputStream(512);
    this.outputStream = new EntityServletOutputStream(content);
    if (response == null) {
        throw new IllegalArgumentException("response to copy cannot be null");
    }
    this.setBufferSize( response.getBufferSize() );
    if (response.getContentType() != null) {
        this.setContentType( response.getContentType() );
    }
    this.setLocale( response.getLocale() );
}
 
Example 11
Source Project: vespa   File: ServletResponseController.java    License: Apache License 2.0 5 votes vote down vote up
private static void setHeaders_holdingLock(Response jdiscResponse, HttpServletResponse servletResponse) {
    for (final Map.Entry<String, String> entry : jdiscResponse.headers().entries()) {
        servletResponse.addHeader(entry.getKey(), entry.getValue());
    }

    if (servletResponse.getContentType() == null) {
        servletResponse.setContentType("text/plain;charset=utf-8");
    }
}
 
Example 12
/**
 * Create a servlet response using the various values and codes stored in the given one,
 * makes copies mostly
 * @param response any valid response, cannot be null
 */
public EntityHttpServletResponse(HttpServletResponse response) {
    this.content = new ByteArrayOutputStream(512);
    this.outputStream = new EntityServletOutputStream(content);
    if (response == null) {
        throw new IllegalArgumentException("response to copy cannot be null");
    }
    this.setBufferSize( response.getBufferSize() );
    if (response.getContentType() != null) {
        this.setContentType( response.getContentType() );
    }
    this.setLocale( response.getLocale() );
}
 
Example 13
public void render(HttpServletRequest req, HttpServletResponse resp, Object obj) throws Throwable {
    String child = evalPath(req, obj);
    if (child == null) {
        child = Mvcs.getActionContext().getPath();
    }
    if (obj != null && req.getAttribute("obj") == null)
        req.setAttribute("obj", obj);
    if (resp.getContentType() == null)
    	resp.setContentType("text/html");
    render.render(child, req, new LazyResponseWrapper(resp));
}
 
Example 14
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;

    Matcher m = subPathPattern.matcher(getSubPathCheckURL(req));
    if (!m.matches()) {
        chain.doFilter(request, response);
        return;
    }

    HttpServletResponse resp = (HttpServletResponse) response;
    ETagResponseWrapper wrapResp = new ETagResponseWrapper(resp);

    chain.doFilter(request, wrapResp);

    byte[] bytes = wrapResp.getCaptureAsBytes();
    LOGGER.info("Response bytes length = " + bytes.length);

    if (contentTypePattern != null) {
        String contentType = resp.getContentType();
        if (contentType == null || !contentTypePattern.matcher(contentType).matches()) {
            LOGGER.info("Non-supported content: " + contentType);
            writeResp(bytes, resp);
            return;
        }
    }
    String resourcePath = getResourcePathFromRequest(req);
    String token = ETagHashUtils.getMd5Digest(bytes, resourcePath);
    if (isEmpty(token)) {
        writeResp(bytes, resp);
        return;
    }
    resp.setHeader(ETAG_HEADER, token);
    String previousToken = req.getHeader(IF_NONE_MATCH_HEADER);
    if (previousToken != null && previousToken.equals(token)) { // compare previous token with current one
        LOGGER.info(ETAG_HEADER + " match: returning '304 Not Modified'");
        resp.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        resp.setHeader(LAST_MODIFIED_HEADER, resp.getHeader(IF_MODIFIED_SINCE_HEADER));
    } else { // first time through - set last modified time to now
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MILLISECOND, 0);
        Date lastModified = cal.getTime();
        resp.setDateHeader(LAST_MODIFIED_HEADER, lastModified.getTime());
        writeResp(bytes, resp);
    }
}
 
Example 15
Source Project: v-mock   File: MockFilterHandler.java    License: MIT License 4 votes vote down vote up
/**
 * 成功场合
 *
 * @param mockResponse
 * @param response
 */
private void successAndLog(MockUrl mockUrl, MockResponse mockResponse,
                           HttpServletRequest request, HttpServletResponse response) {
    // 日志处理,只有成功命中的场合才记录详细,防止产生过多垃圾数据。
    JSONObject responseDetailJson = new JSONObject();
    MockLog mockLog = new MockLog();
    // 命中url,系统中配置的,可能是带path占位符的
    mockLog.setHitUrl(mockUrl.getUrl());
    // 实际url
    mockLog.setRequestUrl(getProcessedUrl(request));
    // ip
    mockLog.setRequestIp(ServletUtil.getClientIP(request));
    // request method
    mockLog.setRequestMethod(request.getMethod());
    // request detail
    mockLog.setRequestDetail(requestToJson(request));
    // header逻辑处理
    String customHeader = mockResponse.getCustomHeader();
    if (StrUtil.isNotBlank(customHeader)) {
        // 将custom header存储的json 反序列化,并遍历存入header.
        JSONArray jsonArray = new JSONArray(customHeader);
        jsonArray.forEach(jsonItem -> {
            String key = ((JSONObject) jsonItem).getStr("key");
            String val = ((JSONObject) jsonItem).getStr("val");
            response.addHeader(key, val);
        });
        // header
        responseDetailJson.put("respHeader", jsonArray);
    }
    // 默认返回contentType为json
    String contentType = response.getContentType();
    if (StrUtil.isBlank(contentType)) {
        response.setContentType(ContentType.JSON.toString(UTF_8));
    }
    // 响应http码
    responseDetailJson.put("respStatus", mockResponse.getStatusCode());
    response.setStatus(mockResponse.getStatusCode());
    // 相应内容
    responseDetailJson.put("respContent", mockResponse.getContent());
    mockLog.setResponseDetail(responseDetailJson.toString());
    // 异步插入
    logService.asyncInsert(mockLog);
    outMsg(mockResponse.getContent(), response);
}
 
Example 16
Source Project: fast-family-master   File: WebUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean isBinaryContent(final HttpServletResponse response) {
    return response.getContentType() != null && (response.getContentType()
            .startsWith("image") || response.getContentType().startsWith("video") || response
            .getContentType().startsWith("audio"));
}
 
Example 17
Source Project: fast-family-master   File: WebUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static boolean isMultipart(final HttpServletResponse response) {
    return response.getContentType() != null && (response.getContentType()
            .startsWith("multipart/form-data") || response.getContentType()
            .startsWith("application/octet-stream"));
}
 
Example 18
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
	HttpServletRequest httpRequest = (HttpServletRequest) request;
	HttpServletResponse httpResponse = (HttpServletResponse) response;

	chain.doFilter(request, response);

	// Defect 491041: post check to ensure every response includes a Content-Type header.
	if (httpResponse.getStatus() != HttpServletResponse.SC_NO_CONTENT) {
		String contentType = httpResponse.getContentType();
		if (contentType == null) {
			String requestURI = httpRequest.getRequestURI();

			if (requestURI != null) {
				String[] pathInfoParts = requestURI.split("\\/");
				if (pathInfoParts.length == 0) {
					return;
				}

				String filename = pathInfoParts[pathInfoParts.length - 1];
				if (filename.equals("defaults.pref") || filename.endsWith(".json") || filename.endsWith(".launch")) {
					httpResponse.setContentType(ProtocolConstants.CONTENT_TYPE_JSON);
				} else if (filename.endsWith(".md") || filename.endsWith(".yml")) {
					httpResponse.setContentType(ProtocolConstants.CONTENT_TYPE_PLAIN_TEXT);
				} else if (filename.endsWith(".css")) {
					httpResponse.setContentType(ProtocolConstants.CONTENT_TYPE_CSS);
				} else if (filename.endsWith(".js")) {
					httpResponse.setContentType(ProtocolConstants.CONTENT_TYPE_JAVASCRIPT);
				} else if (filename.endsWith(".woff")) {
					httpResponse.setContentType(ProtocolConstants.CONTENT_TYPE_FONT);
				} else {
					// see if we have a mime type to use as the content type
					String mimeType = httpRequest.getServletContext().getMimeType(filename);
					if (mimeType != null) {
						String newContentType = mimeType + "; charset=UTF-8";
						httpResponse.setContentType(newContentType);
					} else {
						// fall back to using plain text content type
						httpResponse.setContentType(ProtocolConstants.CONTENT_TYPE_PLAIN_TEXT);
					}
				}
			}
		}
	}
}
 
Example 19
protected boolean responseContentTypeIsJson(HttpServletResponse response) {
	String responseContentType = response.getContentType();
	return this.contentTypeIsJson(responseContentType);
}
 
Example 20
/**
 * Apply this view's content type as specified in the "contentType"
 * bean property to the given response.
 * <p>Only applies the view's contentType if no content type has been
 * set on the response before. This allows handlers to override the
 * default content type beforehand.
 * @param response current HTTP response
 * @see #setContentType
 */
protected void applyContentType(HttpServletResponse response)	{
	if (response.getContentType() == null) {
		response.setContentType(getContentType());
	}
}