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.ibm.ws.lars.rest.ErrorHandler.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setStatus(500);//from w w w  .j  ava  2 s .c o m
    response.setContentType(MediaType.APPLICATION_JSON);
    PrintWriter printWriter = response.getWriter();
    JsonGenerator frontPageJsonGenerator = new JsonFactory().createGenerator(printWriter);
    frontPageJsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter());

    frontPageJsonGenerator.writeStartObject();
    frontPageJsonGenerator.writeStringField("message",
            "Internal server error, please contact the server administrator");
    frontPageJsonGenerator.writeNumberField("statusCode", response.getStatus());
    frontPageJsonGenerator.writeEndObject();

    frontPageJsonGenerator.flush();
    frontPageJsonGenerator.close();
}

From source file:UsingContexts.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    HttpSession session = request.getSession(true);

    Integer counter2 = (Integer) getServletContext().getAttribute("counter2");

    if (counter2 == null) {
        counter2 = new Integer(1);
    } else {/*from   w  w  w . j  a  v a2s  .co m*/
        counter2 = new Integer(counter2.intValue() + 1);
    }

    getServletContext().setAttribute("counter2", counter2);

    Integer counter = (Integer) session.getAttribute("counter");

    if (counter == null) {
        counter = new Integer(1);
    } else {
        counter = new Integer(counter.intValue() + 1);
    }

    session.setAttribute("counter", counter);

    out.println("<HTML>");
    out.println("<HEAD>");
    out.println("<TITLE>");
    out.println("Using Contexts");
    out.println("</TITLE>");
    out.println("</HEAD>");
    out.println("<BODY>");
    out.println("<H1>Using Contexts</H1>");

    out.println("Welcome! You have been here " + counter + " times.<BR>");

    out.println("Total page accesses: " + counter2 + "<BR>");

    if (session.isNew()) {
        out.println("This is a new session.<BR>");
    } else {
        out.println("This is not a new session.<BR>");
    }

    out.println("The session ID: " + session.getId() + "<BR>");
    out.println("Last time accessed: " + new Date(session.getLastAccessedTime()) + "<BR>");
    out.println("Creation time: " + new Date(session.getCreationTime()) + "<BR>");
    out.println("Timeout length: " + session.getMaxInactiveInterval() + " seconds<BR>");

    out.println("</BODY>");
    out.println("</HTML>");
}

From source file:hotel.web.util.RegistrationVerifier.java

/**
 * Processes requests for both HTTP/*from w ww.  j  a v  a 2  s .  c o  m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @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");
    String errMsg = "";
    String destination = "/registrationVerified.jsp";

    try {
        String id = request.getParameter("id");
        byte[] decoded = Base64.decode(id.getBytes());
        String username = new String(decoded);
        Users user = userService.find(username);
        if (user == null) {
            throw new RuntimeException("Sorry, that user is not in our system");
        }
        user.setEnabled(true);
        userService.edit(user);

    } catch (Exception dae) {
        errMsg = "VERIFICATION ERROR: " + dae.getLocalizedMessage();
        request.setAttribute("errMsg", errMsg);
        destination = "/registrationError.jsp";
    }

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(destination);
    dispatcher.forward(request, response);

}

From source file:org.shredzone.cilla.plugin.sitemap.SitemapView.java

/**
 * Renders a sitemap of all pages.// w  ww .  j  a v a  2  s . c o  m
 */
@View(pattern = "/sitemap.xml.gz", name = "sitemap")
public void sitemapView(HttpServletRequest req, HttpServletResponse resp) throws ViewException {
    try {
        resp.setContentType("text/xml");
        resp.setHeader("Content-Encoding", "gzip");

        try (GZIPOutputStream go = new GZIPOutputStream(resp.getOutputStream())) {
            SitemapWriter writer = new SitemapWriter(go);

            writer.writeHeader();
            writeHome(writer);
            writePages(writer);
            writer.writeFooter();
            writer.flush();

            go.finish();
        }
    } catch (IOException ex) {
        throw new ViewException(ex);
    }
}

From source file:bookUtilities.RemoveBookServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w w  w  .ja v a2  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");
    JSONObject message = removeBook(request.getParameter("bookId"));
    PrintWriter printout = response.getWriter();
    printout.print(message);
    printout.flush();
}

From source file:com.web.vehiclerouting.graphhopper.http.InvalidRequestServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    try {/*from  w w  w.  j  a v a 2 s .  com*/
        res.setStatus(HttpServletResponse.SC_NOT_FOUND);
        res.setContentType("text/plain");
        res.setContentType("UTF-8");
        JSONObject json = new JSONObject();
        json.put("error_code", "404");
        writeJson(req, res, json);
    } catch (JSONException ex) {
        Logger.getLogger(InvalidRequestServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:FormLogin.java

public void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, java.io.IOException {
    resp.setContentType("text/html");
    java.io.PrintWriter out = resp.getWriter();
    HttpSession session = req.getSession(true);
    String user = (String) session.getAttribute(USER_KEY);

    if (user == null) {
        String username = req.getParameter(FIELD_USER);
        String password = req.getParameter(FIELD_PASSWORD);

        if (!validUser(username, password)) {
            out.println("<html>");
            out.println("<title>Invalid User</title>");
            out.println("<body><center><h2>" + "Invalid User!</h2><br>");
            out.println("Press the 'Back' button to try again");
            out.println("</center></body></html>");
            out.flush();//ww w  . j av a 2 s  .co m
            return;
        }
        session.setAttribute(USER_KEY, username);
    }
    resp.sendRedirect(req.getRequestURI());
}

From source file:fish.payara.examples.jdays2016.springboot.DataLoaderServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.// w  w  w.  j a va  2  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");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet DataLoader</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet DataLoader at " + request.getContextPath() + "</h1>");

        out.println("Loaded " + loader.parseFile(new File(request.getParameter("file"))) + "records");

        out.println("</body>");
        out.println("</html>");
    }
}

From source file:ro.allevo.fintpws.security.CustomAccessDeniedHandler.java

@Produces(MediaType.APPLICATION_JSON)
@Override/* ww  w.  j ava2 s .c o m*/
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception)
        throws IOException, ServletException {

    response.setContentType("application/json");
    response.setStatus(403);
    try {
        JSONObject obj = JsonResponseWrapper.getEntity(Status.FORBIDDEN.getStatusCode(), ERROR_FORBIDDEN, null,
                null);
        PrintWriter out = response.getWriter();
        out.print(obj);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.expressflow.servlets.ExecProcessServlet.java

private void performRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html");

    UserService userService = UserServiceFactory.getUserService();
    User user = userService.getCurrentUser();
    if (user != null) {
        StringBuilder sb = new StringBuilder(request.getRequestURI());
        String processID = sb.substring(6, sb.length());
        if (processID != null) {
            try {
                // TaskQueues do not support UserService functions...
                // Add the process to the flow-processing queue
                TaskOptions taskOptions = TaskOptions.Builder.withUrl("/_ah/queue/flowprocessor");

                Enumeration parameterNames = request.getParameterNames();
                while (parameterNames.hasMoreElements()) {
                    String parameterName = (String) parameterNames.nextElement();
                    String[] paramValues = request.getParameterValues(parameterName);
                    if (paramValues.length == 1) {
                        taskOptions.param(parameterName, paramValues[0]);
                    } else {
                        System.err.print(parameterName + " has more values?!");
                    }/* w  w w.j  a va 2s. c  o  m*/
                }

                //                  Map<String, String[]> parameterMap = request.getParameterMap();
                //                  for (Map.Entry<String, String[]> parameter : parameterMap.entrySet()) {
                //                     for(String value : parameter.getValue()){
                //                        taskOptions.param(parameter.getKey(), value);
                //                     }
                //                  }

                Queue queue = QueueFactory.getQueue("flowprocessor");
                queue.add(taskOptions.param("key", processID));

            } catch (Exception e) {
                log.info(e.getMessage());
            }
        }
    } else {
        response.sendRedirect(response.encodeRedirectURL(userService.createLoginURL(request.getRequestURI())));
    }
}