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.sunway.cbm.util.ServletUtils.java

/**
 * ?json//  www  .j  a  v  a2 s .  co m
 * 
 * @param response
 * @param object
 */
public static void responseJson(HttpServletResponse response, Object object) {
    // JsonMapper jsonMapper = JsonMapper.buildNormalMapper();
    // String jsonStr = jsonMapper.toJson(object);
    String jsonStr = JSON.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss", features);
    try {
        response.setContentType("text/plain");
        response.getWriter().write(jsonStr);
        response.getWriter().flush();
        response.getWriter().close();
    } catch (IOException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }
    logger.debug(jsonStr);
}

From source file:co.edu.UNal.ArquitecturaDeSoftware.Bienestar.Vista.App.Usuario.Read.java

protected static void registrarUsuarioTaller(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    ArrayList r = CtrlUsuario.registrarATallerUsuario(Integer.parseInt(request.getParameter("1")),
            Integer.parseInt(request.getParameter("2"))); // parameter 1: idUsuario param2: idTaller

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    if (r.get(0) == "error") {
        JSONObject obj = new JSONObject();
        obj.put("isError", true);
        obj.put("errorDescrip", r.get(1));
        out.print(obj);//from ww  w .j  a  va 2 s .co m
    } else if (r.get(0) == "isExitoso") {
        JSONObject obj = new JSONObject();
        obj.put("Exitoso", true);
        out.print(obj);
    } else {
        Util.errordeRespuesta(r, out);
    }
}

From source file:co.edu.UNal.ArquitecturaDeSoftware.Bienestar.Vista.App.Usuario.Read.java

protected static void registrarDocenteTaller(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    ArrayList r = CtrlUsuario.registrarATallerDocente(Integer.parseInt(request.getParameter("1")),
            Integer.parseInt(request.getParameter("2"))); // parameter 1: idUsuarioDocente param2: idTaller

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    if (r.get(0) == "error") {
        JSONObject obj = new JSONObject();
        obj.put("isError", true);
        obj.put("errorDescrip", r.get(1));
        out.print(obj);/*from  ww w . j a v a2  s .  c om*/
    } else if (r.get(0) == "isExitoso") {
        JSONObject obj = new JSONObject();
        obj.put("Exitoso", true);
        out.print(obj);
    } else {
        Util.errordeRespuesta(r, out);
    }
}

From source file:co.com.realtech.mariner.util.jsf.file.FileDownloader.java

/**
 * Descargar excel a travs del FacesContext.
 *
 * @param context//  w  w  w  .j  a  va  2s. c  o m
 * @param bytes
 * @param nombreArchivo
 */
private static void descargarArchivo(FacesContext context, byte[] bytes, String nombreArchivo,
        String extension) {
    ExternalContext externalContext = context.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
    try {
        try (ServletOutputStream servletOutputStream = response.getOutputStream()) {
            response.addHeader("Content-Type", "application/" + extension);
            response.addHeader("Content-Disposition",
                    "attachment; filename=" + nombreArchivo + "." + extension);
            response.setContentLength(bytes.length);
            response.setContentType("application/" + extension);
            servletOutputStream.write(bytes);
            servletOutputStream.flush();
            context.responseComplete();
        }
    } catch (Exception e) {
        System.out.println("Error enviando reporte al cliente, error causado por " + e);
    }
}

From source file:co.edu.UNal.ArquitecturaDeSoftware.Bienestar.Vista.App.Admin.CUDEventos.java

protected static void iniciarWSC(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ArrayList<UsuarioEntity> usuarios = CtrlAdmin.iniciarWSC(Integer.parseInt(request.getParameter("1")), //id evento
            Integer.parseInt(request.getParameter("2")), //tamao tabla
            Integer.parseInt(request.getParameter("3"))//pagina
    ); // parameter 1: documentoDocente param2: idTaller

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();

    JSONArray list1 = new JSONArray();
    for (UsuarioEntity usuario : usuarios) {
        JSONObject obj = new JSONObject();
        obj.put("id", usuario.getIdUsuario());
        obj.put("titulo", usuario.getNombres() + " " + usuario.getApellidos());
        list1.add(obj);/*from ww  w.  ja  v a 2s .  c o m*/
    }
    out.print(list1);
}

From source file:co.edu.UNal.ArquitecturaDeSoftware.Bienestar.Vista.App.Usuario.Read.java

protected static void leerMultiplesTalleres(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    ArrayList<TallerEntity> talleres = new ArrayList<>();
    talleres = CtrlUsuario.leerMultiplesTalleres(Integer.parseInt(request.getParameter("1")),
            Integer.parseInt(request.getParameter("2"))); // posicin y tamao

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();
    System.out.println("Talleres: " + talleres.size());
    JSONArray list1 = new JSONArray();
    for (TallerEntity taller : talleres) {
        JSONObject obj = new JSONObject();
        obj.put("id", taller.getIdTaller());
        obj.put("titulo", taller.getNombre());
        list1.add(obj);/*from  w  ww  . ja v a2s  . c om*/
    }
    out.print(list1);
}

From source file:co.edu.UNal.ArquitecturaDeSoftware.Bienestar.Vista.App.Admin.CUDEventos.java

protected static void consultarUsuariosEnConvocatoriaId(HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    ArrayList<UsuarioEntity> usuarios = new ArrayList<>();
    usuarios = CtrlAdmin.obtenerUsuariosEnConvocatoria(Integer.parseInt(request.getParameter("3")), //id evento
            Integer.parseInt(request.getParameter("2")), //tamao tabla
            Integer.parseInt(request.getParameter("1"))//pagina
    );//w  ww .  j  a va 2  s  .co m

    response.setContentType("application/json;charset=UTF-8");
    PrintWriter out = response.getWriter();

    JSONArray list1 = new JSONArray();
    for (UsuarioEntity usuario : usuarios) {
        JSONObject obj = new JSONObject();
        obj.put("id", usuario.getIdUsuario());
        obj.put("titulo", usuario.getNombres() + " " + usuario.getApellidos());
        list1.add(obj);
    }
    out.print(list1);
}

From source file:org.esgf.legacydatacart.WgetGeneratorController.java

private static void writeBash(String wgetText, String filename, HttpServletResponse response) {
    try {//from   w  w  w  . j a v a 2 s .c  o m
        //attach the sh file extension to the response
        response.setContentType("text/x-sh");
        response.addHeader("Content-Disposition", "attachment; filename=" + filename);
        response.setContentLength((int) wgetText.length());

        PrintWriter out = response.getWriter();
        out.print(wgetText);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.fjn.helper.common.io.file.common.FileUpAndDownloadUtil.java

public static void downloadToBrowser(String filename, String realpath, HttpServletRequest request,
        HttpServletResponse response) {
    // ?MIME TYPE?
    //try {/*from   ww  w.  j  av  a 2s  .  c o  m*/
    //      mimetypesMap=new MimetypesFileTypeMap(request.getSession().getServletContext().getRealPath("WEB-INF/my.mime.types"));
    mimetypesMap = new MimetypesFileTypeMap();
    //} catch (IOException e1) {
    //   e1.printStackTrace();
    //}

    //   response.setCharacterEncoding("UTF-8");
    response.setContentType(mimetypesMap.getContentType(filename));
    response.addHeader("Content-Disposition", "attachment;filename=" + toUTF8(filename));
    FileInputStream in = null;
    OutputStream out = null;
    try {
        /*   ????
           BufferedReader in = new BufferedReader(new InputStreamReader(
                 new FileInputStream(new File(realpath))));
           BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
                 response.getOutputStream()));
           int length = -1;
           char[] chs = new char[1024];
           while ((length = in.read(chs)) != -1) {
              out.write(chs, 0, length);
           }
        */
        in = new FileInputStream(new File(realpath));
        out = response.getOutputStream();
        int length = -1;
        byte[] bs = new byte[1024];
        while ((length = in.read(bs)) != -1) {
            out.write(bs, 0, length);
        }

        out.flush();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null)
                out.close();
            if (in != null)
                in.close();
        } catch (Exception ex) {

        }
    }

}

From source file:com.cisco.ca.cstg.pdi.utils.Util.java

/**
 * This method is used to download files from specified path
 * @param response//w  ww .j av a 2 s. c  om
 * @param archiveFile
 */
public static void downloadArchiveFile(HttpServletResponse response, File archiveFile) {
    if (archiveFile.isFile()) {
        response.reset();
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + archiveFile.getName() + "\"");
        FileInputStream is = null;
        ServletOutputStream op = null;
        try {
            op = response.getOutputStream();
            double dLength = archiveFile.length();
            int iLength = 0;
            int num_read = 0;

            if (dLength >= Integer.MIN_VALUE && dLength <= Integer.MAX_VALUE) {
                iLength = (int) dLength;
            }
            byte[] arBytes = new byte[iLength];
            is = new FileInputStream(archiveFile);

            while (num_read < iLength) {
                int count = is.read(arBytes, num_read, iLength - num_read);
                if (count < 0) {
                    throw new IOException("end of stream reached");
                }
                num_read += count;
            }
            op.write(arBytes);
            op.flush();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
            if (null != op) {
                try {
                    op.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
    }
}