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:br.edu.ifpb.sislivros.actions.CadastrarLivro.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    Livro livro = null;/*from w  w w . j a  va2s .  co  m*/
    try {
        livro = montarLivro(request);
    } catch (FileUploadException ex) {
        Logger.getLogger(CadastrarLivro.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (livro != null) {
        CadastrarLivroBo cadastarBo = new CadastrarLivroBo();

        try {
            boolean cadastrou = cadastarBo.cadastrar(livro);
            if (cadastrou) {
                response.sendRedirect(request.getContextPath() + "/administrativo.jsp");
            }
        } catch (LivroExistenteException ex) {
            Logger.getLogger(CadastrarLivro.class.getName()).log(Level.SEVERE, null, ex);
            response.sendRedirect("errorPageISBN.html");
        }

    } else {
        response.sendRedirect(request.getContextPath() + "/home");
    }
}

From source file:com.boazlev.fnf.web.IndexerServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/xml;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    out.println("<?xml-stylesheet type=\"text/xsl\" href=\"out.xslt\"?>");
    out.println("<catalog>");

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload fileUpload = new ServletFileUpload(factory);
    try {//from   w ww.j  a  va 2 s  .c o  m
        FileItemIterator iterator = fileUpload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream mathMLContent = item.openStream();
            if (!item.isFormField()) {
                Map<String, Integer> index = indexer.index(mathMLContent, "./lines.txt");
                for (Map.Entry<String, Integer> mapEntry : index.entrySet()) {
                    out.println("<cd>");
                    out.print("<index>");
                    out.print(mapEntry.getKey());
                    out.println("</index>");
                    out.print("<count>");
                    out.print(mapEntry.getValue());
                    out.println("</count>");
                    out.println("</cd>");
                }
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    }
    out.print("</catalog>");
}

From source file:ShoppingCartViewerCookie.java

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

    String sessionid = null;//from w w  w.j a v  a  2  s . c o m
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("sessionid")) {
                sessionid = cookies[i].getValue();
                break;
            }
        }
    }

    // If the session ID wasn't sent, generate one.
    // Then be sure to send it to the client with the response.
    if (sessionid == null) {
        sessionid = generateSessionId();
        Cookie c = new Cookie("sessionid", sessionid);
        res.addCookie(c);
    }

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

    // 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 they want to add more items or check out.
    out.println("<FORM ACTION=\"/servlet/ShoppingCart\" 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.
    out.println("For help, click <A HREF=\"/servlet/Help" + "?topic=ShoppingCartViewerCookie\">here</A>");

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

From source file:edit.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  w  w .  j av  a  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");

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

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

    System.out.println("Saving Records...");

    employeeJDBCTemplate.update(Integer.parseInt(request.getParameter("employee_id")),
            Integer.parseInt(request.getParameter("salary")));

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

        out.println("Saved");
    }
}

From source file:com.netease.channel.controller.BaseController.java

protected void successRes(HttpServletResponse respose, String res) {
    respose.setContentType(JSON_CONTENT_TYPE);
    try {//from  w ww.j a v a2 s .  c o  m
        respose.getWriter().write(res);
        respose.getWriter().close();
    } catch (IOException e) {
        LOG.info("Controller response error");
    }
}

From source file:com.praktikum.praktikum4.ProdukServiceSpringJdbcTest.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   ww w  .  j  a v  a 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");
    PrintWriter out = response.getWriter();
    try {
        /* 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 ProdukServiceSpringJdbcTest</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet ProdukServiceSpringJdbcTest at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");
    } finally {
        out.close();
    }
}

From source file:com.example.HelloLicenseServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html; charset=UTF-8");
    UserService userService = UserServiceFactory.getUserService();
    PrintWriter output = response.getWriter();
    String url = request.getRequestURI();

    if (userService.isUserLoggedIn()) {
        // Provide a logout path.
        User user = userService.getCurrentUser();
        output.printf("<strong>%s</strong> | <a href=\"%s\">Sign out</a><br><br>", user.getEmail(),
                userService.createLogoutURL(url));

        try {/*from  w ww  .j  a  va2s  . c  o  m*/
            // Send a signed request for the user's license state.
            OAuthConsumer oauth = new DefaultOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
            oauth.setTokenWithSecret(TOKEN, TOKEN_SECRET);
            URLConnection http = new URL(
                    String.format(URL, APP_ID, URLEncoder.encode(user.getFederatedIdentity(), "UTF-8")))
                            .openConnection();
            oauth.sign(http);
            http.connect();

            // Convert the response from the license server to a string.
            BufferedReader input = new BufferedReader(new InputStreamReader(http.getInputStream()));
            String file = "";
            for (String line; (line = input.readLine()) != null; file += line)
                ;
            input.close();

            // Parse the string as JSON and display the license state.
            JSONObject json = new JSONObject(file);
            output.printf("Hello <strong>%s</strong> license!",
                    "YES".equals(json.get("result"))
                            ? "FULL".equals(json.get("accessLevel")) ? "full" : "free trial"
                            : "no");
        } catch (Exception exception) {
            // Dump any error.
            output.printf("Oops! <strong>%s</strong>", exception.getMessage());
        }
    } else { // The user isn't logged in.
        // Prompt for login.
        output.printf("<a href=\"%s\">Sign in</a>", userService.createLoginURL(url, null,
                "https://www.google.com/accounts/o8/id", new HashSet<String>()));
    }
}

From source file:com.sketchy.server.JsonServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");

    String pathInfo = request.getPathInfo();
    if (pathInfo.startsWith("/"))
        pathInfo = StringUtils.substringAfter(pathInfo, "/");
    String action = ACTION_PACKAGE + pathInfo;
    JSONServletResult jsonServletResult = null;
    try {/*from   w  ww  . ja v  a2 s .c  om*/

        ServletAction servletAction = ServletAction.getInstance(action);

        jsonServletResult = servletAction.execute(request);
    } catch (ClassNotFoundException e) {
        jsonServletResult = new JSONServletResult(Status.ERROR,
                "ServletAction '" + pathInfo + "' not found! " + e.getMessage());
    } catch (Exception e) {
        jsonServletResult = new JSONServletResult(Status.ERROR,
                "Unexpected Exception from ServletAction '" + pathInfo + "'! " + e.getMessage());
    }
    response.setStatus(HttpServletResponse.SC_OK);
    response.getWriter().println(jsonServletResult.toJSONString());

}

From source file:com.ctb.prism.report.api.RequirejsConfigServlet.java

/**
 *
 *//*from w w w .  ja  v  a  2s .  co  m*/
public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/javascript; charset=UTF-8");
    setNoExpire(response);

    PrintWriter out = response.getWriter();
    WebUtil webUtil = WebUtil.getInstance(getJasperReportsContext());

    List<RequirejsModuleMapping> requirejsMappings = getJasperReportsContext()
            .getExtensions(RequirejsModuleMapping.class);
    Map<String, String> modulePaths = new LinkedHashMap<String, String>();

    for (RequirejsModuleMapping requirejsMapping : requirejsMappings) {
        String modulePath = requirejsMapping.getPath();
        if (requirejsMapping.isClasspathResource()) {
            modulePath = request.getContextPath() + webUtil.getResourcesBasePath() + modulePath;
        }
        modulePaths.put(requirejsMapping.getName(), modulePath);
    }

    Map<String, Object> contextMap = new HashMap<String, Object>();

    contextMap.put("contextPath", request.getContextPath());
    contextMap.put("modulePaths", modulePaths.entrySet());

    out.write(VelocityUtil.processTemplate(REQUIREJS_CONFIG_TEMPLATE, contextMap));
}

From source file:com.npower.wurfl.WurflServletInit.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    out.println("Init servlet (Loaded on startup for WURFL initialization)");
}