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:ru.langboost.controllers.file.FileController.java

@RequestMapping(value = "/file/{id}", method = RequestMethod.GET)
public void get(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id) {
    File file = fileService.get(id);
    try {//from w  w w.j  av a 2  s  .  c  o m
        if (file != null) {
            response.setContentType(file.getContentType());
            response.setHeader("Content-disposition", "attachment; filename=\"" + file.getFileName() + "\"");
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Content-Length", String.valueOf(file.getSource().length));
            FileCopyUtils.copy(file.getSource(), response.getOutputStream());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:technology.tikal.ventas.service.almacen.SalidaService.java

@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)//from  w ww. j a v  a2s .  c o  m
public void crear(@PathVariable final Long pedidoId, @Valid @RequestBody final RegistroAlmacenTransient request,
        final BindingResult result, final HttpServletRequest httpRequest,
        final HttpServletResponse httpResponse) {
    if (result.hasErrors()) {
        throw new NotValidException(result);
    }
    Salida nuevo = salidaController.crear(pedidoId, request);
    httpResponse.setHeader("Location", httpRequest.getRequestURI() + "/" + nuevo.getId());
}

From source file:coral.reef.web.ReefToCoralController.java

@RequestMapping(value = "/{exp}/**")
public void dispatchToExpHandler(@PathVariable("exp") String exp, HttpSession httpSession,
        HttpServletResponse httpResponse, HttpServletRequest httpRequest) throws IOException {

    httpResponse.setHeader("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
    httpResponse.setHeader("Pragms", "no-cache");
    httpResponse.setHeader("Expires", "0");

    Integer id = (Integer) httpSession.getAttribute(REEF_ID);
    String sessionExp = (String) httpSession.getAttribute(REEF_EXP);

    String path = ((String) httpRequest.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE))
            .substring(exp.length() + 2);

    ReefHandler handler = service.handler(exp);

    if (path.startsWith(handler.startMarker())) {

        if (sessionExp != null || id != null) {
            // TODO remove old client (?)
        }/*from  w  ww.  j ava2  s  .  c  o m*/

        String query = httpRequest.getQueryString();
        query = (query == null) ? "" : query;
        id = handler.addClient(null);
        String result = handler.process(id, path, query);
        result = service.replaceHost(exp, result);
        httpSession.setAttribute(REEF_ID, id);
        httpSession.setAttribute(REEF_EXP, exp);
        httpResponse.setContentType("text/html");
        httpResponse.getWriter().println(result);

    } else if (path.startsWith(handler.refreshMarker())) {

        if (sessionExp != null || id != null) {
            // TODO remove old client (?)
        }

        String query = httpRequest.getQueryString();
        query = (query == null) ? "" : query;
        id = Integer.parseInt(query.replaceAll("[^\\d]", ""));
        id = handler.addClient(id);
        String result = handler.process(id, "", "?refreshid=" + id);
        result = service.replaceHost(exp, result);
        httpSession.setAttribute(REEF_ID, id);
        httpSession.setAttribute(REEF_EXP, exp);
        httpResponse.setContentType("text/html");
        httpResponse.getWriter().println(result);

    } else if (path.startsWith(handler.processMarker()) && sessionExp != null && sessionExp.equals(exp)) {

        /*
         * PROCESS
         */

        String query = httpRequest.getQueryString();
        query = (query == null) ? "" : query;
        String result = handler.process(id, path, query);
        result = service.replaceHost(exp, result);
        httpResponse.setContentType("text/html");
        httpResponse.getWriter().println(result);

    } else if (path.startsWith(handler.serverMarker())) {

        /*
         * SERVER
         */

        String result = handler.server(path.substring(handler.serverMarker().length() + 1),
                httpRequest.getParameterMap());
        result = service.replaceHost(exp, result);
        httpResponse.setContentType("text/html");
        httpResponse.getWriter().println(result);

    } else if (handler.getResMap().containsKey(path)) {

        /*
         * RESOURCE
         */

        File f = handler.getResMap().get(path);
        FileSystemResource fr = new FileSystemResource(f);
        String type = servletContext.getMimeType(path);
        httpResponse.setContentType(type);

        IOUtils.copy(fr.getInputStream(), httpResponse.getOutputStream());
    } else {
        // no match = no response => should propagate to next controller
        System.out.println(path + " - " + handler.getResMap());
    }

}

From source file:org.syncope.core.rest.controller.ConfigurationController.java

@PreAuthorize("hasRole('CONFIGURATION_READ')")
@RequestMapping(method = RequestMethod.GET, value = "/dbexport")
@Transactional(readOnly = true)/*  w ww .  j  a  v a2 s  .co m*/
public void dbExport(final HttpServletResponse response) {
    response.setContentType(MediaType.TEXT_XML_VALUE);
    response.setHeader("Content-Disposition", "attachment; filename=content.xml");

    try {
        importExport.export(response.getOutputStream());

        LOG.debug("Default content successfully exported");
    } catch (Throwable t) {
        LOG.error("While exporting content", t);
    }
}

From source file:technology.tikal.ventas.service.almacen.EntradaService.java

@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)/* w  ww.  ja  v  a  2  s .  c  o  m*/
public void crear(@PathVariable final Long pedidoId, @Valid @RequestBody final RegistroAlmacenTransient request,
        final BindingResult result, final HttpServletRequest httpRequest,
        final HttpServletResponse httpResponse) {
    if (result.hasErrors()) {
        throw new NotValidException(result);
    }
    Entrada nuevo = entradaController.crear(pedidoId, request);
    httpResponse.setHeader("Location", httpRequest.getRequestURI() + "/" + nuevo.getId());
}

From source file:cn.shengyuan.yun.admin.system.controller.CommonController.java

@RequestMapping(value = "/captchaImage", method = RequestMethod.GET)
public String captchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {

    response.setDateHeader("Expires", 0);
    // Set standard HTTP/1.1 no-cache headers.
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    // Set standard HTTP/1.0 no-cache header.
    response.setHeader("Pragma", "no-cache");
    // return a jpeg
    response.setContentType("image/jpeg");
    // create the text for the image
    String capText = captchaProducer.createText();
    // store the text in the session
    request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
    // create the image with the text
    BufferedImage bi = captchaProducer.createImage(capText);
    ServletOutputStream out = response.getOutputStream();
    // write the data out
    ImageIO.write(bi, "jpg", out);
    try {/*from  w w w  .j a v a 2s  . c  om*/
        out.flush();
    } finally {
        out.close();
    }
    return null;

}

From source file:MyPack.AjaxFriendList.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from   w  w w  . j  av a2  s.  c  o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    response.setContentType("text/html;charset=UTF-8");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");
    HttpSession s = request.getSession(true);
    try (PrintWriter out = response.getWriter()) {
        //getting AJAX parameter
        String query = request.getParameter("term");
        //Creating JSONArray Object
        JSONArray arrayObj = new JSONArray();
        //Changing Case of AJAX parameter
        query = query.toLowerCase();

        try {
            Connection con = ConnectionClass.getConnected();
            PreparedStatement p = con
                    .prepareStatement("select name from friend where name LIKE '" + query + "%'");
            ResultSet rs = p.executeQuery();
            while (rs.next() == true) {
                arrayObj.put(rs.getString(1));
            }
            out.println(arrayObj.toString());
            out.close();
        } catch (SQLException ea) {
        }
    }
}

From source file:cltestgrid.GetBlob2.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    String userAgent = req.getHeader("User-Agent");
    if (userAgent != null && userAgent.contains("Baiduspider")) {
        resp.setStatus(SC_MOVED_PERMANENTLY);
        resp.setHeader("Location", "http://www.baidu.com/search/spider.html");
        resp.setHeader("X-READ-ME",
                "Please honor robots.txt and don't waste our resources. http://cl-test-grid.appspot.com/robots.txt");
        return;// www  .j  ava 2s  .  c om
    }

    final String key = req.getParameter("key");
    GcsFilename filename = new GcsFilename("cl-test-grid-logs", key);
    GcsInputChannel readChannel = null;
    InputStream inputStream = null;
    try {
        final boolean lock = false;
        //readChannel = FileServiceFactory.getFileService().openReadChannel(file, lock);
        readChannel = GcsServiceFactory.createGcsService().openReadChannel(filename, 0);
        inputStream = Channels.newInputStream(readChannel);
        resp.setContentType("text/plain");
        // The log files are gzipped, but the Cloud Storage Client Library ungzips them automatically.
        // After we return this data, GAE gzips our output in case client accepts 'gzip' contect encoding.
        IOUtils.copy(new BufferedInputStream(inputStream, 100 * 1024), resp.getOutputStream());
        resp.getOutputStream().flush();
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(readChannel);
    }
}

From source file:com.jaspersoft.jasperserver.war.CSVServlet.java

public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
    try {/*  w w  w .ja  v  a2 s .  c om*/
        resp.setContentType(MIME_TYPE);
        resp.setHeader("Pragma", "");
        resp.setHeader("Cache-Control", "no-store");
        //resp.setContentType(HTML_TYPE); // for testing
        PrintWriter out = resp.getWriter();
        printQuery(getDrillThroughSQL(req), getConnection(req), out);
    } catch (Exception e) {
        e.printStackTrace();
        log.error(e);
    }
}