Example usage for javax.servlet.http HttpServletResponse setHeader

List of usage examples for javax.servlet.http HttpServletResponse setHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setHeader.

Prototype

public void setHeader(String name, String value);

Source Link

Document

Sets a response header with the given name and value.

Usage

From source file:com.yunda.htmlsnap.web.api.HtmlSnapController.java

@RequestMapping(method = RequestMethod.GET)
public void snap(@RequestParam("htmlUrl") String htmlUrl, @RequestParam("imgType") String imgType,
        HttpServletRequest request, HttpServletResponse response) {
    logger.info("?:" + htmlUrl);
    //JavaHost.printAllVirtualDns();
    response.setContentType("image/" + imgType);
    response.setHeader("Content-Type", "image/" + imgType);
    boolean flag = false;
    ServletOutputStream sos = null;/*  ww  w.ja v  a 2s.c  om*/
    if (StringUtils.isNotBlank(htmlUrl)) {
        BrowserService browserService = null;
        try {
            browserService = BrowserFactory.getBrowerService();
            sos = response.getOutputStream();
            flag = browserService.generatePng(URLDecoder.decode(htmlUrl, "UTF-8"), sos, imgType);
        } catch (IOException e) {
            logger.error("??:" + e);
        } finally {
            BrowserFactory.recycleService(browserService);
        }
    }
    logger.info("?" + flag);
    if (!flag) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    if (null != sos) {
        try {
            sos.flush();
            sos.close();
        } catch (IOException e1) {
            logger.error("?", e1);
        }
    }
}

From source file:com.adito.extensions.actions.GetExtensionDescriptorAction.java

private void sendApplicationDescriptor(ExtensionDescriptor app, HttpServletRequest request,
        HttpServletResponse response, SessionInfo session, Properties properties)
        throws JDOMException, IOException, UndefinedParameterException, CoreException {
    response.setHeader("Content-type", "text/xml");
    byte[] xml = ExtensionParser.processAgentParameters(app, request, session, properties).getBytes();
    //      response.setContentLength(xml.length);
    response.getOutputStream().write(xml);
    response.getOutputStream().close();/*from w  ww . jav a 2  s  .  c o  m*/
}

From source file:de.highbyte_le.weberknecht.request.view.WebActionProcessor.java

protected void processRedirect(HttpServletResponse response, View view) {
    if (log.isDebugEnabled())
        log.debug("processRedirect() - initiate redirection to: " + view.getRedirection());

    response.setHeader("Location", view.getRedirection().toExternalForm());
    response.setStatus(303); //303 - "see other" (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)
}

From source file:FormLogin.java

public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, java.io.IOException {
    resp.setContentType("text/html");
    java.io.PrintWriter out = resp.getWriter();
    resp.setHeader("Expires", "Tues, 01 Jan 1980 00:00:00 GMT");
    String uri = req.getRequestURI();

    HttpSession session = req.getSession();
    String user = (String) session.getAttribute(USER_KEY);

    if (user == null) {
        login(out, uri);/*from www  . j a  va 2s  .  com*/
        return;
    }
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Welcome</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<center><h2>Welcome to our site!</h2>");
    out.println("</center><br><br>");
    out.println("</body>");
    out.println("</html>");
    out.flush();
}

From source file:org.saiku.adhoc.rest.StandaloneCdaResource.java

private void setResponseHeaders(final String mimeType, final String attachmentName) {
    // Make sure we have the correct mime type
    final HttpServletResponse response = anotherServlerResponse;
    if (response == null) {
        return;//from  w  ww . j  a v a 2 s . c  om
    }

    response.setHeader("Content-Type", mimeType);

    if (attachmentName != null) {
        response.setHeader("content-disposition", "attachment; filename=" + attachmentName);
    }

    // We can't cache this request
    response.setHeader("Cache-Control", "max-age=0, no-store");
}

From source file:com.megacasting_ppe.web.ServletPageError.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  w w. j a  va2 s  .  c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    response.setHeader("Cache-Control", "no-cache");
    HttpSession session = request.getSession();

    JSONObject global = new JSONObject();

    if (session.getAttribute("Connecter") != null) {
        String connecterCandidatOk = (String) session.getAttribute("Connecter");
        if (connecterCandidatOk == "false") {

            global.put("candidatAutherreur",
                    "le nom d'utilisateur ou le mot de passe du candidat est incorrect");
            session.removeAttribute("Connecter");
        }
    }
    if (session.getAttribute("ConnecterDiffuseur") != null) {
        String connecterDiffuseurOk = (String) session.getAttribute("ConnecterDiffuseur");
        if (connecterDiffuseurOk == "false") {

            global.put("diffuseurAutherreur",
                    "le nom d'utilisateur ou le mot de passe du diffuseur est incorrect");
            session.removeAttribute("ConnecterDiffuseur");
        }
    }

    if (session.getAttribute("ErreurInscriptionCandidat") != null) {
        String ErreurInscription = (String) session.getAttribute("ErreurInscriptionCandidat");
        if (ErreurInscription == "true") {

            global.put("Inscriptionerreur",
                    "Un ou plusieurs champs saisies dans le formulaire d'inscription sont invalide");
            session.removeAttribute("ErreurInscriptionCandidat");
        }
    }

    try (PrintWriter out = response.getWriter()) {
        out.println(global.toString());
    }

}

From source file:com.albert.swagger.ContactController.java

@ApiOperation(value = "", notes = "", response = Contact.class, position = 2)
@RequestMapping(value = "/1.0/contact/add.do", method = RequestMethod.POST)
public void add(@RequestBody Contact contact, HttpServletResponse response) {
    //contactService.create(contact);
    String location = ServletUriComponentsBuilder.fromCurrentRequest().pathSegment("{id}").buildAndExpand("")
            .toUriString();//from   w  w  w  .  ja v a  2s .c o  m

    response.setHeader("Location", location);
}

From source file:com.struts2ext.json.JSONUtil.java

public static void writeJSONToResponse(SerializationParams serializationParams) throws IOException {
    StringBuilder stringBuilder = new StringBuilder();
    if (StringUtils.isNotBlank(serializationParams.getSerializedJSON()))
        stringBuilder.append(serializationParams.getSerializedJSON());

    if (StringUtils.isNotBlank(serializationParams.getWrapPrefix()))
        stringBuilder.insert(0, serializationParams.getWrapPrefix());
    else if (serializationParams.isWrapWithComments()) {
        stringBuilder.insert(0, "/* ");
        stringBuilder.append(" */");
    } else if (serializationParams.isPrefix())
        stringBuilder.insert(0, "{}&& ");

    if (StringUtils.isNotBlank(serializationParams.getWrapSuffix()))
        stringBuilder.append(serializationParams.getWrapSuffix());

    String json = stringBuilder.toString();

    if (LOG.isDebugEnabled()) {
        LOG.debug("[JSON]" + json);
    }/*from  ww w  .j  av  a2s .c  o  m*/

    HttpServletResponse response = serializationParams.getResponse();

    // status or error code
    if (serializationParams.getStatusCode() > 0)
        response.setStatus(serializationParams.getStatusCode());
    else if (serializationParams.getErrorCode() > 0)
        response.sendError(serializationParams.getErrorCode());

    // content type
    if (serializationParams.isSmd())
        response.setContentType("application/json-rpc;charset=" + serializationParams.getEncoding());
    else
        response.setContentType(
                serializationParams.getContentType() + ";charset=" + serializationParams.getEncoding());

    if (serializationParams.isNoCache()) {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Expires", "0");
        response.setHeader("Pragma", "No-cache");
    }

    if (serializationParams.isGzip()) {
        response.addHeader("Content-Encoding", "gzip");
        GZIPOutputStream out = null;
        InputStream in = null;
        try {
            out = new GZIPOutputStream(response.getOutputStream());
            in = new ByteArrayInputStream(json.getBytes(serializationParams.getEncoding()));
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            if (in != null)
                in.close();
            if (out != null) {
                out.finish();
                out.close();
            }
        }

    } else {
        response.setContentLength(json.getBytes(serializationParams.getEncoding()).length);
        PrintWriter out = response.getWriter();
        out.print(json);
    }
}

From source file:org.openmrs.module.vcttrac.web.view.chart.AbstractChartView.java

/**
 * @see org.springframework.web.servlet.view.AbstractView
 *//*from  w w  w.  j  a v a 2 s .  co m*/
@Override
@SuppressWarnings("unchecked")
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    // Respond as a PNG image
    response.setContentType("image/png");

    // Disable caching
    response.setHeader("Pragma", "No-cache");
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-cache");

    int width = (request.getParameter("width") != null && request.getParameter("width").compareTo("") != 0)
            ? (Integer.valueOf(request.getParameter("width")))
            : 450;
    int height = (request.getParameter("height") != null && request.getParameter("height").compareTo("") != 0)
            ? (Integer.valueOf(request.getParameter("height")))
            : 350;

    JFreeChart chart = createChart(model, request);
    chart.setBackgroundPaint(Color.WHITE);
    chart.getPlot().setOutlineStroke(new BasicStroke(0));
    chart.getPlot().setOutlinePaint(getBackgroundColor());
    chart.getPlot().setBackgroundPaint(getBackgroundColor());

    chart.getPlot().setNoDataMessage(VCTTracUtil.getMessage("vcttrac.error.noDataAvailable", null));

    ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, width, height);
}

From source file:com.nagarro.core.v2.controller.BaseController.java

protected void setTotalCountHeader(final HttpServletResponse response, final PaginationWsDTO paginationDto) {
    if (paginationDto != null && paginationDto.getTotalResults() != null) {
        response.setHeader(HEADER_TOTAL_COUNT, String.valueOf(paginationDto.getTotalResults()));
    }/*ww w  . ja v  a 2  s. c o  m*/
}