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:DeliberateException.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    ServletOutputStream out = res.getOutputStream();
    res.setContentType("text/html");
    out.println("<html><head><title>Exception Thrower</title></head>");
    out.println("<body>You'll never see this!</body></html>");

}

From source file:MyServlet.java

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

    HttpSession session = req.getSession();

    Integer count = (Integer) session.getAttribute("snoop.count");
    if (count == null)
        count = new Integer(1);
    else/*  w ww. j  a v  a2  s  . com*/
        count = new Integer(count.intValue() + 1);
    session.setAttribute("snoop.count", count);

    out.println("<HTML><HEAD><TITLE>SessionSnoop</TITLE></HEAD>");
    out.println("<BODY><H1>Session Snoop</H1>");

    out.println("You've visited this page " + count + ((count.intValue() == 1) ? " time." : " times."));

    out.println("<P>");

    out.println("<H3>Here is your saved session data:</H3>");
    Enumeration e = session.getAttributeNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }

    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");

    out.println("Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");

    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren't supported.");

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

From source file:org.jasig.portlet.calendar.mvc.EmptyView.java

@Override
protected void prepareResponse(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType(getContentType());
    response.setCharacterEncoding(encoding.getJavaName());
}

From source file:org.ktunaxa.referral.server.mvc.UploadView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    response.setContentType("text/html");
    response.getWriter().println("<html>");
    response.getWriter().println("<body>");
    response.getWriter().println("<script type=\"text/javascript\">");
    UploadResponse ur = (UploadResponse) model.get(RESPONSE);
    SerializerState state = new SerializerState();
    if (ur != null) {
        JSONObject result = (JSONObject) getSerializer().marshall(state, ur.getResultMap());
        if (ur.isSuccess()) {
            response.getWriter()/*from  ww  w  . j a  va 2  s.  c o m*/
                    .println(MessageFormat.format(getSuccessScript(), result.getJSONObject("map").toString()));
        } else {
            response.getWriter()
                    .println(MessageFormat.format(getErrorScript(), result.getJSONObject("map").toString()));
        }
    } else {
        response.getWriter()
                .println(MessageFormat.format(getErrorScript(), getSerializer().toJSON("server error")));
    }
    response.getWriter().println("</script>");
}

From source file:com.parallax.server.blocklyprop.servlets.AuthenticationServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("application/json");

    String username = req.getParameter("username");
    String password = req.getParameter("password");

    User user = authenticationService.authenticate(username, password);

    if (user != null) {
        SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(req);
        if (savedRequest != null) {
            resp.sendRedirect(savedRequest.getRequestUrl());
        } else {//from  w w  w .  j  av  a 2 s.c o m

            JsonObject response = new JsonObject();
            response.addProperty("success", true);
            JsonObject userJson = new JsonObject();
            userJson.addProperty("id-user", user.getId());
            userJson.addProperty("screenname", user.getScreenname());
            userJson.addProperty("email", user.getEmail());
            response.add("user", userJson);
            resp.getWriter().write(response.toString());
        }
    } else {
        JsonObject response = new JsonObject();
        response.addProperty("success", false);
        response.addProperty("message", "Invalid authentication");
        resp.getWriter().write(response.toString());
    }
}

From source file:MyServlet.java

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

    printHeader(out);/* www .  j a va  2 s  . c o m*/
    printForm(out);
    printMessages(out);
    printFooter(out);
}

From source file:ShoppingCartViewerRewrite.java

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

    out.println("<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>");
    out.println("<BODY>");

    // Get the current session ID, or generate one if necessary
    String sessionid = req.getPathInfo();
    if (sessionid == null) {
        sessionid = generateSessionId();
    }/* ww  w . ja  va2 s.c  o  m*/

    // Cart items are associated with the session ID
    String[] items = getItemsFromCart(sessionid);

    // Print the current cart items.
    out.println("You currently have the following items in your cart:<BR>");
    if (items == null) {
        out.println("<B>None</B>");
    } else {
        out.println("<UL>");
        for (int i = 0; i < items.length; i++) {
            out.println("<LI>" + items[i]);
        }
        out.println("</UL>");
    }

    // Ask if the user wants to add more items or check out.
    // Include the session ID in the action URL.
    out.println("<FORM ACTION=\"/servlet/ShoppingCart/" + sessionid + "\" METHOD=POST>");
    out.println("Would you like to<BR>");
    out.println("<INPUT TYPE=SUBMIT VALUE=\" Add More Items \">");
    out.println("<INPUT TYPE=SUBMIT VALUE=\" Check Out \">");
    out.println("</FORM>");

    // Offer a help page. Include the session ID in the URL.
    out.println("For help, click <A HREF=\"/servlet/Help/" + sessionid
            + "?topic=ShoppingCartViewerRewrite\">here</A>");

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

From source file:info.losd.galen.api.GalenApiController.java

@ExceptionHandler(IllegalArgumentException.class)
void illegalArgumentException(HttpServletResponse response) throws IOException {
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.sendError(HttpStatus.BAD_REQUEST.value(), "The method specified is invalid");
}

From source file:com.antelink.sourcesquare.server.servlet.TimeServlet.java

/**
 * returns the estimated remaining time/*  w  w w  .j a  va  2 s .  co  m*/
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
    try {
        Gson gson = new Gson();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().append(gson.toJson(computeTimeLeft()));

    } catch (IOException e) {
        logger.debug("Error dispatching time", e);
    }
}

From source file:org.ng200.openolympus.controller.auth.OpenOlympusAuthenticationFailureHandler.java

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
    response.setContentType("application/json");
    response.setStatus(HttpStatus.OK.value());
    AuthenticationResponder.writeLoginStatusJson(response.getWriter(), "failed", null);
}