Example usage for javax.servlet.http HttpServletResponse setContentType

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

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse 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.goodhuddle.huddle.web.api.ExportApiController.java

@RequestMapping(value = "/{fileName:.+}", method = RequestMethod.GET)
public void downloadExport(@PathVariable String fileName, HttpServletResponse response) throws IOException {
    log.debug("Downloading export file: {}", fileName);
    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment; filename=\"members.csv\"");
    File exportFile = exportService.getExportFile(fileName);
    try (FileInputStream in = new FileInputStream(exportFile)) {
        IOUtils.copy(in, response.getOutputStream());
        response.flushBuffer();/*from   w  w  w.  j  a  v  a  2  s  .c o m*/
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.rm.server.serialization.ExportNodeSourceToCatalogServlet.java

private void upload(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html");
    try (CatalogObjectAction catalogObjectAction = buildCatalogObjetAction(request)) {
        CatalogRequestBuilder catalogRequestBuilder = new CatalogRequestBuilder(catalogObjectAction);
        String requestUri = catalogRequestBuilder.build();
        LOGGER.info("Post node source to catalog with URI: " + requestUri);
        postRequestAndHandleResponse(response, catalogObjectAction, catalogRequestBuilder, requestUri);
    } catch (Exception e) {
        logErrorAndWriteResponseToClient(e, response);
    }//from  w  ww .j  a v  a  2 s  .  c om
}

From source file:com.adobe.epubcheck.web.EpubCheckServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/plain");
    PrintWriter out = resp.getWriter();
    if (!ServletFileUpload.isMultipartContent(req)) {
        out.println("Invalid request type");
        return;/*  w  w w  . ja  v a 2s  . c o  m*/
    }
    try {
        DiskFileItemFactory itemFac = new DiskFileItemFactory();
        // itemFac.setSizeThreshold(20000000); // bytes
        File repositoryPath = new File("upload");
        repositoryPath.mkdir();
        itemFac.setRepository(repositoryPath);
        ServletFileUpload servletFileUpload = new ServletFileUpload(itemFac);
        List fileItemList = servletFileUpload.parseRequest(req);
        Iterator list = fileItemList.iterator();
        FileItem book = null;
        while (list.hasNext()) {
            FileItem item = (FileItem) list.next();
            String paramName = item.getFieldName();
            if (paramName.equals("file"))
                book = item;
        }
        if (book == null) {
            out.println("Invalid request: no epub uploaded");
            return;
        }
        File bookFile = File.createTempFile("work", "epub");
        book.write(bookFile);
        EpubCheck epubCheck = new EpubCheck(bookFile, out);
        if (epubCheck.validate())
            out.println("No errors or warnings detected");
        book.delete();
    } catch (Exception e) {
        out.println("Internal Server Error");
        e.printStackTrace(out);
    }
}

From source file:com.dgq.utils.Struts2Utils.java

private static HttpServletResponse initResponseHeaderServlet(final String contentType,
        HttpServletResponse response, final String... headers) {
    // ?headers?//from  w  ww  .jav a2  s. c om
    String encoding = DEFAULT_ENCODING;
    boolean noCache = DEFAULT_NOCACHE;
    for (String header : headers) {
        String headerName = StringUtils.substringBefore(header, ":");
        String headerValue = StringUtils.substringAfter(header, ":");

        if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
            encoding = headerValue;
        } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
            noCache = Boolean.parseBoolean(headerValue);
        } else {
            throw new IllegalArgumentException(headerName + "??header");
        }
    }

    // headers?
    String fullContentType = contentType + ";charset=" + encoding;
    response.setContentType(fullContentType);
    if (noCache) {
        ServletUtils.setNoCacheHeader(response);
    }

    return response;
}

From source file:UTF8.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {/*  w w w  .  j a va 2  s  . c o  m*/
        BufferedReader reader = req.getReader();

        res.setContentType("text/html; charset=UTF-8");
        PrintWriter out = new PrintWriter(new OutputStreamWriter(res.getOutputStream(), "UTF8"), true);

        // Read and write 4K chars at a time
        // (Far more efficient than reading and writing a line at a time)
        char[] buf = new char[4 * 1024]; // 4Kchar buffer
        int len;
        while ((len = reader.read(buf, 0, buf.length)) != -1) {
            out.write(buf, 0, len);
        }
        out.flush();
    } catch (Exception e) {
        getServletContext().log(e, "Problem filtering page to UTF-8");
    }
}

From source file:count.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w ww . 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("text/html;charset=UTF-8");

    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

    EmployeeJDBCTemplate employeeJDBCTemplate = (EmployeeJDBCTemplate) context.getBean("employeeJDBCTemplate");

    Employee employee = employeeJDBCTemplate.getCount();

    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        out.println(employee.getDepartment());
    }
}

From source file:com.cami.web.controller.uploadController.java

@RequestMapping(value = "/get/{value}", method = RequestMethod.GET)
public void get(HttpServletResponse response, @PathVariable String value) {
    try {/*from   www  .j  a v a2  s  .co  m*/

        response.setContentType(ufile.type);
        response.setContentLength(ufile.length);
        FileCopyUtils.copy(ufile.bytes, response.getOutputStream());

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.jamespot.glifpix.wrappers.SampleHtmlTestService.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");
    response.setStatus(HttpServletResponse.SC_OK);
    PrintWriter out = response.getWriter();

    SampleTagsServiceHandler tsh = new SampleTagsServiceHandler();

    out.println("<h1>HtmlTestService</h1>");
    out.println("<table>");
    String[] tags = tsh.getTags(request.getParameter("text"), request.getParameter("lng"),
            Integer.parseInt(request.getParameter("nbTags")));

    if (tags != null && tags.length > 0) {
        for (int i = 0; i < tags.length; i++) {
            out.println("<tr><td>" + tags[i] + "</td></tr>");
        }//  w w w  .j  a v  a2  s. co m

    }
    out.println("</table>");

    out.println("<p><a href='/html/form'>Back</a></p>");
}

From source file:org.broadleafcommerce.admin.util.controllers.ListDirectoryController.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    XmlDirectoryListing dirs = new XmlDirectoryListing();
    response.setContentType("text/xml");
    dirs.setDateFormat("MMM DD, yyyy");

    String basepath = request.getPathTranslated().substring(0, request.getPathTranslated().indexOf("ls"));
    dirs.generateXmlDirectoryListing(new File(basepath + rootDirectory), response.getOutputStream());

    return null;//w  w w.jav  a 2 s. co  m
}

From source file:net.lightbody.bmp.proxy.jetty.servlet.SendRedirect.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache,no-store");

    String url = request.getParameter("URL");
    if (url != null && url.length() > 0) {
        response.sendRedirect(url);/*from  w  w w  .  j a v  a  2s  . c  om*/
    } else {
        PrintWriter pout = response.getWriter();
        Page page = null;

        try {
            page = new Page();
            page.title("SendRedirect Servlet");

            page.add(new Heading(1, "SendRedirect Servlet"));

            page.add(new Heading(1, "Form to generate Dump content"));
            TableForm tf = new TableForm(response
                    .encodeURL(URI.addPaths(request.getContextPath(), request.getServletPath()) + "/action"));
            tf.method("GET");
            tf.addTextField("URL", "URL", 40, request.getContextPath() + "/dump");
            tf.addButton("Redirect", "Redirect");
            page.add(tf);
            page.write(pout);
            pout.close();
        } catch (Exception e) {
            log.warn(LogSupport.EXCEPTION, e);
        }
    }
}