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:ShoppingCartViewerHidden.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>");

    // Cart items are passed in as the item parameter.
    String[] items = req.getParameterValues("item");

    // 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 {//from  ww  w.j  a  v  a 2s .c o m
        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 current items as hidden fields so they'll be passed on.
    out.println("<FORM ACTION=\"/servlet/ShoppingCart\" METHOD=POST>");
    if (items != null) {
        for (int i = 0; i < items.length; i++) {
            out.println("<INPUT TYPE=HIDDEN NAME=\"item\" VALUE=\"" + items[i] + "\">");
        }
    }
    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>");

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

From source file:controller.ImageCTMH.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();
    String mamh = session.getAttribute("mamh").toString();
    session.removeAttribute("mamh");
    if (!ServletFileUpload.isMultipartContent(request)) {
        out.println("Nothing to upload");
        return;/*from  w w  w . java2  s .  c  o m*/
    }
    FileItemFactory itemfactory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(itemfactory);
    String a = "";
    try {
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            String myfolder = ("asset/Images") + "/";
            File uploadDir = new File(
                    "E:/Cng ngh phn m?m/? ?n/1996Shop/ShopOnline/web/asset/Images");
            File file = File.createTempFile("img", ".png", uploadDir);
            item.write(file);
            a = myfolder + file.getName();
            ct.setHinhAnh(a);
            ct.setMaMh(Long.parseLong(mamh));
            cTHinhAnhDAO.insert(ct);
            response.sendRedirect("CTSanPham.jsp?MaMH=" + mamh + "");
        }

    } catch (FileUploadException e) {
        out.println("upload fail");
    } catch (Exception ex) {

    }
}

From source file:de.iew.web.view.js.JavascriptConfigView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> stringObjectMap, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    response.setContentType("text/javascript; charset=utf-8");

    PrintWriter writer = response.getWriter();
    writer.write("define(function(){return{");

    writer.write(renderBaseUrlHelper(request));

    writer.write("}});");
}

From source file:com.facebook.tsdb.tsdash.server.MetricHeaderEndpoint.java

/**
 * GET params:/*from  w  w  w .j a va  2s .  c  o m*/
 * "metric" - metric name
 * "from" - start of the time range
 * "to" - end of the time range
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    try {
        // decode parameters
        long ts = System.currentTimeMillis();
        String jsonParams = request.getParameter("params");
        if (jsonParams == null) {
            throw new Exception("Parameters not specified");
        }
        JSONObject jsonParamsObj = (JSONObject) JSONValue.parse(jsonParams);
        long tsFrom = (Long) jsonParamsObj.get("tsFrom");
        long tsTo = (Long) jsonParamsObj.get("tsTo");
        String metricName = (String) jsonParamsObj.get("metric");
        HashMap<String, String> tags = MetricQuery.decodeTags((JSONObject) jsonParamsObj.get("tags"));
        if (metricName == null) {
            throw new Exception("Missing parameter");
        }
        TsdbDataProvider dataProvider = TsdbDataProviderFactory.get();
        Metric metric = dataProvider.fetchMetricHeader(metricName, tsFrom, tsTo, tags);
        out.println(metric.toJSONString());
        long loadTime = System.currentTimeMillis() - ts;
        logger.info("[Header] time frame: " + (tsTo - tsFrom) + "s, " + "metric: " + metricName + ", tags: "
                + tags + ", " + "load time: " + loadTime + "ms");
    } catch (Exception e) {
        out.println(getErrorResponse(e));
    }
    out.close();
}

From source file:com.parleys.server.frontend.web.ipad.filters.LoginFilter.java

@Override
public void doFilter(final ServletRequest req, final ServletResponse response, final FilterChain chain)
        throws IOException {
    final HttpServletResponse res = (HttpServletResponse) response;
    final PrintWriter writer = res.getWriter();
    res.setStatus(HttpServletResponse.SC_OK);
    res.setHeader("Cache-Control", "must-revalidate");
    res.setHeader("Expires", "Fri, 30 Oct 1998 14:19:41 GMT");
    try {//w  ww .  j  a va2 s. c  om
        final String username = req.getParameter("username");
        final String password = req.getParameter("password");
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            final ParleysService bean = applicationContext.getBean(ParleysService.class);
            final Long userId = bean.getUserId(username, password);

            final String usernameAndPassword = username + ";" + password;
            final String encrypted = AESEncrypter.INSTANCE.encrypt(usernameAndPassword);
            final Cookie rememberMeCookie = new Cookie(PARLEYS_REMEMBER_ME_IPAD, encrypted);
            rememberMeCookie.setMaxAge(3600 * 24 * 7 * 26); // A half year
            res.addCookie(rememberMeCookie);

            writeUserId(writer, userId);
        } else {
            writeError(writer);
        }
    } catch (Exception e) {
        writeError(writer);
    }
}

From source file:org.craftercms.cstudio.publishing.servlet.StatusMonitoringServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);
    response.getWriter().println("{ status: \"" + statusMessage + "\" }");
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:com.cueup.hegemon.testing.server.ResponseListener.java

ResponseListener(HttpServletResponse response, CustomTestOutput customOutput) throws IOException {
    this.output = response.getWriter();
    this.customOutput = customOutput;
    this.failed = Maps.newHashMap();
    this.ignored = Sets.newHashSet();
}

From source file:com.test.servlet.LoginController.java

@Override
public void setResponse(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    String email = getParam(RequestParam.email.toString());
    String password = getParam(RequestParam.password.toString());
    if (Utility.isStringEmpty(email)) {
        writer.print(//  w  w w.j  a  va 2 s.  co  m
                Utility.generalErrorMessage(ResponseCode.email_not_provided.toString(), "Email is required!"));
        return;
    }
    if (Utility.isStringEmpty(password)) {
        writer.print(Utility.generalErrorMessage(ResponseCode.password_not_provided.toString(),
                "Password is required!"));
        return;
    }

    DBUtility dbUtil = new DBUtility(servlet);
    User user = dbUtil.getUser(email, password);
    if (user != null) {
        HttpSession session = request.getSession();
        session.setAttribute("user_id", user.getId());
        String sessionKey = SessionGenerator.getInstance().nextSessionId();
        Cookie cookie = new Cookie("auth_key", sessionKey);
        cookie.setMaxAge(Constants.COOKIE_AGE);
        response.addCookie(cookie);

        dbUtil.insertSession(sessionKey, user.getId());

        JSONObject jResponse = new JSONObject();
        jResponse.put(JSONKey.status.toString(), 0);
        //jResponse.put(JSONKey.auth_key.toString(), sessionKey);
        jResponse.put(JSONKey.user_info.toString(), user.toJSONObject());

        writer.print(jResponse.toString());
    } else {
        writer.print(Utility.generalErrorMessage(ResponseCode.email_doesnt_exist.toString(),
                "Email address not found"));
    }
}

From source file:jetbrains.buildServer.staticUIExtensions.web.StaticContentController.java

@Nullable
private ModelAndView sendError(@NotNull final HttpServletRequest request,
        @NotNull final HttpServletResponse response, @NotNull final String errorMessage) throws IOException {
    response.getWriter().write("ERROR: Content for StaticUIExtensions plugin was not found. " + errorMessage);
    return null;//from w  w w .ja  v  a  2  s  .com
}

From source file:org.zalando.logbook.servlet.example.ExampleController.java

@RequestMapping(value = "/reader", produces = MediaType.TEXT_PLAIN_VALUE)
public void reader(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    try (PrintWriter writer = response.getWriter()) {
        CharStreams.copy(request.getReader(), writer);
    }//w ww.java 2  s .  c om
}