Example usage for javax.servlet ServletResponse setContentType

List of usage examples for javax.servlet ServletResponse setContentType

Introduction

In this page you can find the example usage for javax.servlet ServletResponse setContentType.

Prototype


public void setContentType(String type);

Source Link

Document

Sets the content type of the response being sent to the client, if the response has not been committed yet.

Usage

From source file:com.mirantis.cachemod.filter.CacheFilter.java

public void writeCacheToResponse(CacheEntry cacheEntry, ServletResponse response, boolean fragment)
        throws IOException {

    if (cacheEntry.getContentType() != null) {
        response.setContentType(cacheEntry.getContentType());
    }//from w ww.j  a va 2s. com

    if (!fragment) {

        if (response instanceof HttpServletResponse) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;

            if (cacheEntry.getLastModified() != -1) {
                httpResponse.setDateHeader("Last-Modified", cacheEntry.getLastModified());
            }

            if (cacheEntry.getExpires() != Long.MAX_VALUE) {
                httpResponse.setDateHeader("Expires", cacheEntry.getExpires());
            }

            if (cacheEntry.getMaxAge() != -1) {
                if (cacheEntry.getMaxAge() < 0) { // set max-age based on life time
                    long currentMaxAge = -cacheEntry.getMaxAge() / 1000 - System.currentTimeMillis() / 1000;
                    if (currentMaxAge < 0) {
                        currentMaxAge = 0;
                    }
                    httpResponse.addHeader("Cache-Control", "max-age=" + currentMaxAge);
                } else {
                    httpResponse.addHeader("Cache-Control", "max-age=" + cacheEntry.getMaxAge());
                }
            }

        }
    }

    if (cacheEntry.getLocale() != null) {
        response.setLocale(cacheEntry.getLocale());
    }

    OutputStream out = new BufferedOutputStream(response.getOutputStream());
    response.setContentLength(cacheEntry.getContent().length);
    out.write(cacheEntry.getContent());
    out.flush();
}

From source file:jp.co.opentone.bsol.linkbinder.view.filter.UploadFileFilter.java

private void writeResponse(ServletRequest req, ServletResponse res, UploadFileFilterResult result)
        throws IOException {
    res.setContentType("text/plain;charset=" + req.getCharacterEncoding());
    OutputStream out = res.getOutputStream();
    out.write(JSON.encode(result).getBytes(req.getCharacterEncoding()));
}

From source file:com.netsteadfast.greenstep.sys.GreenStepBaseFormAuthenticationFilter.java

protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
    if (isAjaxRequest((HttpServletRequest) request)) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().write(Constants.NO_LOGIN_JSON_DATA);
        return;/*from   www. j a v  a  2s  .  co  m*/
    }
    if (this.isDojoxContentPane((HttpServletRequest) request)) { //  dojox.layout.ContentPane ??? login.action ??          
        WebUtils.issueRedirect(request, response, Constants.DOJOX_CONTENT_PANE_XHR_RE_LOGIN_PAGE);
        return;
    }
    WebUtils.issueRedirect(request, response, getLoginUrl());
}

From source file:io.hops.hopsworks.api.tensorflow.TensorboardProxyServlet.java

private void sendErrorResponse(ServletResponse servletResponse, String message) throws IOException {
    servletResponse.setContentType("text/html");
    PrintWriter out = servletResponse.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title></title>");
    out.println("</head>");
    out.println("<body>");
    out.println(message);//ww  w.  j  a v  a2 s.  co  m
    out.println("</body>");
    out.println("</html>");
}

From source file:o2.web.HelloWorldServlet.java

@Override
public void service(ServletRequest req, ServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    ApplicationContext context = new ClassPathXmlApplicationContext("knights.xml");
    Knight knight = (Knight) context.getBean("knight");
    knight.embarkOnQuest();//from  ww  w.ja  v a 2  s . co  m

    response.setContentType("text/html;charset=utf-8");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = response.getWriter();
    String title = "Webapp Demo";
    out.println(
            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
    out.println("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
    out.println("<head>");
    out.println("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />");
    out.println("<title>" + title + "</title>");
    out.println("<body>");
    out.println("<h1>Hello World!O2</h1>");
    out.println("</body>");
    out.println("</html>");

}

From source file:com.netsteadfast.greenstep.sys.GreenStepMobileFormAuthenticationFilter.java

protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
    if (isAjaxRequest((HttpServletRequest) request)) {
        response.setCharacterEncoding(Constants.BASE_ENCODING);
        response.setContentType("application/json");
        response.getWriter().write(Constants.NO_LOGIN_JSON_DATA);
        return;//from w w w  .  j  a  v a2  s  .  c  o m
    }
    if (this.isIframeMode((HttpServletRequest) request)) { // iframe ??? login.action ?          
        WebUtils.issueRedirect(request, response, "/pages/system/error_static.jsp");
        return;
    }
    if (this.isDojoxContentPane((HttpServletRequest) request)) { //  dojox.layout.ContentPane ??? login.action ??          
        WebUtils.issueRedirect(request, response, Constants.DOJOX_CONTENT_PANE_XHR_RE_LOGIN_PAGE);
        return;
    }
    WebUtils.issueRedirect(request, response, getLoginUrl());
}

From source file:org.apache.myfaces.custom.suggestajax.inputsuggestajax.InputSuggestAjaxRenderer.java

public void encodeAjax(FacesContext context, UIComponent uiComponent) throws IOException {
    // we are not sending html, xml or json, so notify the system about that else any filter
    // trying to parse the result as html (e.g. richfaces) will fail
    ServletResponse response = (ServletResponse) context.getExternalContext().getResponse();
    response.setContentType("text/plain");

    InputSuggestAjax inputSuggestAjax = (InputSuggestAjax) uiComponent;

    Collection suggesteds = getSuggestedItems(context, uiComponent);

    MethodExpression labelMethod = inputSuggestAjax.getItemLabelMethod();

    StringBuffer buf = new StringBuffer();

    buf.append("[");

    if (labelMethod != null) {
        Converter converter = getRequiredConverter(context, inputSuggestAjax);

        for (Iterator iterator = suggesteds.iterator(); iterator.hasNext();) {
            Object suggestedItemObject = iterator.next();

            String label = (String) labelMethod.invoke(context.getELContext(),
                    new Object[] { suggestedItemObject });
            String value = converter.getAsString(context, inputSuggestAjax, suggestedItemObject);

            buf.append("[\"").append(label).append("\",\"").append(value).append("\"],");
        }/*from   w  ww  . ja  v a 2  s  . c om*/
    } else {
        //writing the suggested list
        for (Iterator suggestedItem = suggesteds.iterator(); suggestedItem.hasNext();) {
            Object item = suggestedItem.next();

            String prefix = escapeQuotes(encodeSuggestString(item.toString()).substring(0, 1)).toUpperCase();

            buf.append("[\"").append(encodeSuggestString(escapeQuotes(item.toString()))).append("\",\"")
                    .append(prefix).append("\"],");
        }
    }

    buf.append("]");

    context.getResponseWriter().write(buf.toString());
}

From source file:net.ymate.module.webproxy.support.DispatchProxyFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    request.setCharacterEncoding(__charsetEncoding);
    response.setCharacterEncoding(__charsetEncoding);
    ////from w w w . j  a  v  a 2 s.c  o  m
    response.setContentType(
            Type.ContentType.HTML.getContentType().concat("; charset=").concat(__charsetEncoding));
    //
    HttpServletRequest _request = new RequestMethodWrapper((HttpServletRequest) request, __requestMethodParam);
    HttpServletResponse _response = (HttpServletResponse) response;
    IRequestContext _requestContext = new DefaultRequestContext(_request, __requestPrefix);
    if (null == __ignorePatern || !__ignorePatern.matcher(_requestContext.getOriginalUrl()).find()) {
        if (StringUtils.isNotBlank(__prefix)
                && !StringUtils.startsWith(_requestContext.getRequestMapping(), __prefix)
                || __doMatchBlacklist(_requestContext.getRequestMapping())) {
            _response = new GenericResponseWrapper(_response);
            GenericDispatcher.create(WebMVC.get()).execute(_requestContext, __filterConfig.getServletContext(),
                    _request, _response);
        } else {
            try {
                YMP.get().getEvents()
                        .fireEvent(new WebProxyEvent(WebProxy.get(), WebProxyEvent.EVENT.REQUEST_RECEIVED)
                                .addParamExtend(IEvent.EVENT_SOURCE, _requestContext));
                //
                String _requestMapping = _requestContext.getRequestMapping();
                if (StringUtils.isNotBlank(__prefix)) {
                    _requestMapping = StringUtils.substringAfter(_requestMapping, __prefix);
                }
                StringBuilder _url = new StringBuilder(WebProxy.get().getModuleCfg().getServiceBaseUrl())
                        .append(_requestMapping);
                if (Type.HttpMethod.GET.equals(_requestContext.getHttpMethod())) {
                    if (StringUtils.isNotBlank(_request.getQueryString())) {
                        _url.append("?").append(_request.getQueryString());
                    }
                }
                WebProxy.get().transmission(_request, _response, _url.toString(),
                        _requestContext.getHttpMethod());
            } catch (Throwable e) {
                _LOG.warn("An exception occurred: ", RuntimeUtils.unwrapThrow(e));
            } finally {
                YMP.get().getEvents()
                        .fireEvent(new WebProxyEvent(WebProxy.get(), WebProxyEvent.EVENT.REQUEST_COMPLETED)
                                .addParamExtend(IEvent.EVENT_SOURCE, _requestContext));
            }
        }
    } else {
        chain.doFilter(_request, _response);
    }
}

From source file:net.ymate.platform.mvc.web.DispatcherFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // ?// w  w w.  j av  a 2s  .c o m
    request.setCharacterEncoding(WebMVC.getConfig().getCharsetEncoding());
    response.setCharacterEncoding(WebMVC.getConfig().getCharsetEncoding());
    response.setContentType("text/html;charset=" + WebMVC.getConfig().getCharsetEncoding());
    //
    IWebRequestContext _context = __dispHelper.bindRequestContext((HttpServletRequest) request);
    if (null == ignorePatern || !ignorePatern.matcher(_context.getUrl()).find()) {
        __dispHelper.doRequestProcess(_context, __filterConfig.getServletContext(),
                (HttpServletRequest) request, (HttpServletResponse) response);
    } else {
        chain.doFilter(request, response);
    }
}

From source file:se.inera.certificate.proxy.mappings.remote.RemoteDispatcher.java

private void sendResponseEntity(ServletResponse response, HttpEntity entity) throws IOException {
    // Entity can be null in case of 304 answer.
    if (entity != null) {
        Header contentType = entity.getContentType();

        if (contentType != null) {
            response.setContentType(contentType.getValue());
        }/*from  w w  w  .jav  a  2 s.  co m*/
        copyLarge(entity.getContent(), response.getOutputStream());
    }
    response.getOutputStream().flush();
}