Example usage for javax.servlet.http HttpServletResponse getWriter

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

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse getWriter.

Prototype

public PrintWriter getWriter() throws IOException;

Source Link

Document

Returns a PrintWriter object that can send character text to the client.

Usage

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();//www.j  a v  a2  s.  c  o m
            return;
        }
        session.setAttribute(USER_KEY, username);
    }
    resp.sendRedirect(req.getRequestURI());
}

From source file:productClass.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * Select statement for the database connect to retrieve values
 * //w ww  .ja va2s.  c  o m
 * @param request servlet request
 * @param response servlet response
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    try (PrintWriter out = response.getWriter()) {
        if (!request.getParameterNames().hasMoreElements()) {
            out.println(getResults("SELECT * FROM product"));
        } else {
            int productID = Integer.parseInt(request.getParameter("productID"));
            out.println(getResults("SELECT * FROM product WHERE productID = ?", String.valueOf(productID)));
        }
    } catch (IOException ex) {
        Logger.getLogger(productClass.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.tvst.api.servlet.HomeServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w ww.j a v a  2  s  .  com
 *
 * @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("application/json;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        JSONObject object = new JSONObject();
        object.put(JSONKey.status.toString(), 1);
        object.put(JSONKey.server_time.toString(), System.currentTimeMillis());
        out.println(object.toString());
    }
}

From source file:FormLogin.java

public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, java.io.IOException {
    resp.setContentType("text/html");
    java.io.PrintWriter out = resp.getWriter();
    resp.setHeader("Expires", "Tues, 01 Jan 1980 00:00:00 GMT");
    String uri = req.getRequestURI();

    HttpSession session = req.getSession();
    String user = (String) session.getAttribute(USER_KEY);

    if (user == null) {
        login(out, uri);//from  w  ww .java 2 s  . c om
        return;
    }
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Welcome</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<center><h2>Welcome to our site!</h2>");
    out.println("</center><br><br>");
    out.println("</body>");
    out.println("</html>");
    out.flush();
}

From source file:productsave.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    try {/*  ww w .  j  ava2  s . c  o  m*/
        ServletContext x = this.getServletContext();
        String path = x.getRealPath("/images");

        System.out.println(path + " path");
        DiskFileUpload p = new DiskFileUpload();
        List q = p.parseRequest(request);
        Iterator z = q.iterator();
        while (z.hasNext()) {
            FileItem f = (FileItem) z.next();
            if (f.isFormField() == true) {
                //non-file data
                System.out.println("executed");
                String h = f.getFieldName();
                String data = f.getString();
                if (h.equalsIgnoreCase("productname")) {
                    productname = data;
                } else if (h.equalsIgnoreCase("category")) {
                    categoryid = data;
                    System.out.println(categoryid + " cccc");
                } else if (h.equalsIgnoreCase("price")) {
                    price = data;
                } else if (h.equalsIgnoreCase("description")) {
                    description = data;
                }

            } else {
                //file data
                String filename = f.getName();
                if (filename != null && filename.length() > 0) {
                    File g = new File(filename);

                    filename = g.getName();

                    //creating unique file name
                    long w = System.currentTimeMillis();
                    filename = w + filename;
                    System.out.println("path " + path + " file " + filename);
                    //upload file
                    File t = new File(path, filename);
                    f.write(t);
                    if (f.getFieldName().equals("image")) {
                        image = filename;
                    }
                }

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    productbean product = new productbean();
    product.setProductname(productname);
    product.setCategoryid(categoryid);
    product.setDescription(description);
    product.setImage(image);
    product.setPrice(price);
    int count = product.save();
    if (count != 0) {
        out.println("1");
    } else {
        out.println("0");
    }
}

From source file:com.epam.wilma.webapp.config.servlet.stub.upload.MultiPartFormUploadServlet.java

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

    boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
    if (!isMultipartContent) {
        out.println("You are not trying to upload");
    } else {//from w  w  w. j  a  v  a2  s.c o m
        try {
            List<FileItem> fields = upload.parseRequest(request);
            String msg = filesParser.parseMultiPartFiles(fields);
            LOGGER.info(urlAccessLogMessageAssembler.assembleMessage(request, msg));
            out.write(msg);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("File uploading failed! cause: " + e.getMessage());
            LOGGER.info(urlAccessLogMessageAssembler.assembleMessage(request, e.getMessage()), e);
        }
    }
}

From source file:com.mondospider.spiderlocationapi.SetSpiderStatus.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    if (!req.isSecure()) {
        resp.getWriter()
                .println("{\"result:error\", \"reason\":\"SSL secured connection required for updates.\"}");
        return;/*from  ww  w  .  j av a2 s.  c o m*/
    }

    if (req.getParameter("status") == null) {
        //Display Error&Help
        try {
            req.getRequestDispatcher("/index.html").forward(req, resp);
        } catch (ServletException e) {
            resp.getWriter().println("{\"result:error\", \"reason\":\"Forward failed\"}");
            e.printStackTrace();
            return;
        }
    }

    // Permission Check
    String key = req.getParameter("pwd");
    if (!isSecretKeyTrue(key)) {
        // accessDenied
        resp.getWriter().println("{\"result:error\", \"reason\":\"Wrong Key\"}");
        return;
    }

    try {

        String status = req.getParameter("status");

        // Update Position
        updateStatus(status);

        responseResp.put("result", "success");
        responseResp.put("updated_on", new Date());

        resp.setContentType("text/plain");

        resp.getWriter().println(responseResp.toString(2));
        return;

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

    resp.sendRedirect("/index.html");

}

From source file:jsst.server.FrontController.java

private void makeResponse(HttpServletResponse response, TestResult testResult)
        throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    try {/*  www .j av a2  s .  co  m*/
        JSONObject jsonObject = convertToJSON(testResult);
        jsonObject.write(writer);
    } catch (JSONException e) {
        throw new ServletException(e);
    } finally {
        writer.close();
    }
}

From source file:de.micromata.genome.tpsb.httpmockup.internaltest.TestServletOne.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String data = req.getParameter("data");
    if (StringUtils.contains(data, "OK") == true) {
        resp.setStatus(200);/*from   w w w  . java2 s . co m*/
        resp.getWriter().println("Ja, Kammer ist auch OK");
    } else {
        resp.setStatus(500);
        resp.getWriter().println("Ojeoje");
    }
    resp.getWriter().flush();
}

From source file:org.trimou.spring.web.view.TrimouView.java

@Override
protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    response.setContentType(getContentType());
    exposeRequestAttributesAsModel(model, request);
    final Writer writer = response.getWriter();
    try {/*from   w  w w .j  a v a  2 s. c  o  m*/
        engine.getMustache(viewName).render(writer, model);
    } catch (NullPointerException e) {
        throw new MustacheException(getUrl() + " is not exist.", e);
    } finally {
        writer.flush();
    }
}