Example #1
1
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.print("<html><head><title>Page2</title></head><body>");
    Users tmpUser = null;
    HttpSession session;

    tmpUser = usersService.findByLogin(request.getParameter("login"));
    if (tmpUser != null) {
      if ((tmpUser.getPassword()).equals(request.getParameter("password"))) {
        session = request.getSession(true);
        session.setAttribute("users", tmpUser);
        response.sendRedirect("http://localhost:8080/orders");
      } else {
        out.print("Access denied :(");
      }

    } else {
      String login = request.getParameter("login");
      String pass = request.getParameter("password");
      tmpUser = new Users(login, pass);
      usersService.saveUsers(tmpUser);
      session = request.getSession(true);
      session.setAttribute("users", tmpUser);
      response.sendRedirect("http://localhost:8080/orders");
    }
    out.print("</body></html>");
  }
Example #2
1
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    HttpSession session = request.getSession();
    PrintWriter out = response.getWriter();
    StringBuilder sb = new StringBuilder();

    HashMap<String, String> userInfo = (HashMap<String, String>) session.getAttribute("userInfo");
    String ticket = request.getParameter("ticket");

    if (userInfo == null) {
      response.sendRedirect(response.encodeRedirectUrl(request.getContextPath() + "/SignIn"));
    } else {
      if (userInfo.get("role").equals("technician")) {
        sb.append(LayoutProvider.getInstance().getLoggedInHeader(userInfo.get("name")));
        sb.append("<div id=\"body\">");
        sb.append(
            "<h3>Schedule Confirmation</h3><p>You have scheduled <strong>ticket # "
                + ticket
                + "</strong></p>");
        if (ticket != null) {
          List<String> tickets;
          try {
            if (userInfo.get("tickets").equals("")) {
              tickets = null;
            } else {
              tickets = Arrays.asList(userInfo.get("tickets").split("\\,"));
            }
          } catch (Exception ex) {
            System.out.println("PayBill: error splitting tickets");
            tickets = null;
          }
          String remaining = "";
          if (tickets != null && tickets.size() > 0) {
            for (String t : tickets) {
              if (!t.equals(ticket)) {
                remaining += t + ",";
              }
            }
            if (remaining.length() > 0) remaining = remaining.substring(0, remaining.length() - 1);
          } else {
            remaining = "";
          }
          userInfo.put("tickets", remaining);
        }
        sb.append("</div>");
      } else {
        sb.append("<h2>Error</h2>");
        sb.append("<p>You do not have access to this page.</p>");
        sb.append("</div>");
      }
    }
    out.println(sb.toString());
    out.close();
  }
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {
    res.setContentType("text/html");
    try {
      PrintWriter pw = res.getWriter();
      pw.println("<html><head><TITLE>Web-Enabled Automated Manufacturing System</TITLE></head>");
      pw.println(
          "<body><br><br><br><form name=modifyuser method=post action='http://peers:8080/servlet/showUser')");
      v = U.allUsers();
      pw.println("<table align='center' border=0> <tr><td>");
      pw.println(
          "Select User Name To Modify</td><td><SELECT id=select1 name=uid style='HEIGHT: 22px; LEFT: 74px; TOP: 222px; WIDTH: 155px'>");
      pw.println("<OPTION selected value=''></OPTION>");
      for (i = 0; i < v.size(); i++)
        pw.println(
            "<OPTION value="
                + (String) v.elementAt(i)
                + ">"
                + (String) v.elementAt(i)
                + "</OPTION>");
      pw.println(
          "</SELECT></td></tr><tr><td></td><td><input type='submit' name='submit' value='Submit'></td></tr></table></form></body></html>");
      pw.flush();
      pw.close();

    } catch (Exception e) {
    }
  }
Example #4
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Session Tracking Example";
    HttpSession session = request.getSession(true);
    String heading;

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

    if (accessCount == null) {
      accessCount = new Integer(0);
      heading = "Welcome, Newcomer";
    } else {
      heading = "Welcome Back";
      accessCount = new Integer(accessCount.intValue() + 1);
    }

    session.setAttribute("accessCount", accessCount);
    out.println(
        "<BODY BGCOLOR=\"#FDF5E6\">\n"
            + "<H1 ALIGN=\"CENTER\">"
            + heading
            + "</H1>\n"
            + "<H2>Information on Your Session:</H2>\n"
            + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n"
            + "<TR BGCOLOR=\"#FFAD00\">\n"
            + "  <TH>Info Type<TH>Value\n"
            + "<TR>\n"
            + "  <TD>ID\n"
            + "  <TD>"
            + session.getId()
            + "\n"
            + "<TR>\n"
            + "  <TD>Creation Time\n"
            + "  <TD>"
            + new Date(session.getCreationTime())
            + "\n"
            + "<TR>\n"
            + "  <TD>Time of Last Access\n"
            + "  <TD>"
            + new Date(session.getLastAccessedTime())
            + "\n"
            + "<TR>\n"
            + "  <TD>Number of Previous Accesses\n"
            + "  <TD>"
            + accessCount
            + "\n"
            + "</TR>"
            + "</TABLE>\n");

    // the following two statements show how to retrieve parameters in
    // the request.  The URL format is something like:
    // http://localhost:8080/project2/servlet/ShowSession?myname=Chen%20Li
    String myname = request.getParameter("myname");
    if (myname != null) out.println("Hey " + myname + "<br><br>");

    out.println("</BODY></HTML>");
  }
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

    String support = "support"; // valid username

    HttpSession session = null;
    session = req.getSession(false); // Get user's session object (no new one)
    if (session == null) {

      invalidUser(out); // Intruder - reject
      return;
    }

    String userName = (String) session.getAttribute("user"); // get username

    if (!userName.equals(support)) {

      invalidUser(out); // Intruder - reject
      return;
    }

    String action = "";
    if (req.getParameter("todo") != null) action = req.getParameter("todo");

    if (action.equals("update")) {

      doUpdate(out);
      return;
    }

    out.println("<p>Nothing to do.</p>todo=" + action);
  }
Example #6
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    HttpSession session = request.getSession();

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String type = request.getParameter("type");
    System.out.println(username + password + type);

    session.setAttribute("user", username);

    try {
      writer.println("<html>");
      writer.println("<body bgcolor=green>");
      writer.println("<center>");
      ps.setString(1, username);
      ps.setString(2, password);
      ps.setString(3, type);
      ResultSet rs = ps.executeQuery();

      if (rs.next()) {
        writer.println("<h1>LOGIN SUCCESSFUL</h1><br><br>");
        writer.println("<a href=account.html>click here to see your account</a>");
      } else {
        writer.println("<h1>LOGIN FAILED</h1><br><br>");
        writer.println("<a href=login.html>click here to login again</a>");
      }
      writer.println("</center>");
      writer.println("</body>");
      writer.println("</html>");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #7
0
  void sendHTML(
      HttpServletRequest request,
      HttpServletResponse response,
      String script,
      Exception scriptError,
      Object scriptResult,
      StringBuffer scriptOutput,
      boolean capture)
      throws IOException {
    // Format the output using a simple templating utility
    SimpleTemplate st = new SimpleTemplate(BshServlet.class.getResource("page.template"));
    st.replace("version", getBshVersion());

    // String requestURI = HttpUtils.getRequestURL( request ).toString()
    // I was told this should work
    String requestURI = request.getRequestURI();

    st.replace("servletURL", requestURI);
    if (script != null) st.replace("script", script);
    else st.replace("script", exampleScript);
    if (capture) st.replace("captureOutErr", "CHECKED");
    else st.replace("captureOutErr", "");
    if (script != null)
      st.replace(
          "scriptResult", formatScriptResultHTML(script, scriptResult, scriptError, scriptOutput));

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    st.write(out);
    out.flush();
  }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   String title = "Showing Request Headers";
   StringBuilder sb = new StringBuilder();
   sb.append("<html>\n<head>\n");
   sb.append("<title>" + title + "</title>\n");
   sb.append("</head>\n");
   sb.append("<body bgcolor='#FDF5E6'>\n");
   sb.append("<h1 align='center'>" + title + "</h1>\n");
   sb.append("<b> Request Method: </b>" + request.getMethod() + "<br>\n");
   sb.append("<b> Request URI: </b>" + request.getRequestURI() + "<br>\n");
   sb.append("<b> Request Protocol: </b>" + request.getProtocol() + "<br>\n");
   sb.append("<table border=1 align='center'>\n");
   sb.append("<tr bgcolor='#FFAD00'>\n");
   sb.append("<th> Header Name </th><th> Header Value </th></tr>\n");
   Enumeration headerNames = request.getHeaderNames();
   while (headerNames.hasMoreElements()) {
     String headerName = (String) headerNames.nextElement();
     sb.append("<tr><td>" + headerName + "</td>");
     sb.append("<td>" + request.getHeader(headerName) + "</td></tr>\n");
   }
   sb.append("</table>\n");
   sb.append("</body></html>");
   out.println(sb.toString());
   out.close();
 }
Example #9
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // POST method only used for tracked login operation
    HttpSession session = request.getSession();
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();

    // Get the username and password from request
    String username = request.getParameter("id");
    String password = request.getParameter("pwd");

    Long id = 0L;
    try {
      id = Long.parseLong(username);
    } catch (Exception ex) {
    }

    if (username != null && password != null) {
      // Login into tracked system
      CTracked ctracked = db.loginTrackedFromMobile(id, password).getResult();

      if (ctracked != null) {
        // Login successful
        out.print("OK," + ctracked.getUsername());
        session.setAttribute("device_id", ctracked.getUsername());
        log.info(ctracked + " : logined!");
      }
    }
  }
Example #10
0
 /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("application/vnd.ms-excel");
   PrintWriter out = response.getWriter();
   out.println("\tQ1\tQ2\tQ3\tQ4\tTotal");
   out.println("Apples\t78\t87\t92\t29\t=SUM(B2:E2)");
   out.println("Oranges\t77\t86\t93\t30\t=SUM(B3:E3)");
 }
Example #11
0
 private void sendResponse(HttpServletResponse pResp, String pContentType, String pJsonTxt)
     throws IOException {
   setContentType(pResp, pContentType);
   pResp.setStatus(200);
   setNoCacheHeaders(pResp);
   PrintWriter writer = pResp.getWriter();
   writer.write(pJsonTxt);
 }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    System.out.println("queryString: " + request.getQueryString());
    out.println("FILTER-QUERYSTRING:" + (request.getQueryString() != null ? "PASS" : "FAIL"));
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    // Prepare this response
    response.setContentType("text/plain");
    PrintWriter writer = response.getWriter();
    writer.println("ResponseWrap01c PASSED");
  }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html");
   PrintWriter pw = response.getWriter();
   HttpSession session = request.getSession();
   String str = (String) session.getAttribute("foo");
   pw.println("The name is " + str);
 }
 /** Utility method to serialize an exception and its stack trace to simple HTML. */
 private final void serializeException(PrintWriter osw, Throwable t) {
   osw.write("<b>Exception</b>: " + t.toString() + "\n<br/><br/>");
   osw.write("<b>Stack trace:</b>");
   osw.write(
       "<pre style=\"margin: 1px solid red; padding: 3px; font-family: sans-serif; font-size: small;\">");
   t.printStackTrace(osw);
   osw.write("</pre>");
 }
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter writer = response.getWriter();
    writer.write("<h1>Hello, <em>World!</em></h1>");
    writer.close();
  }
Example #17
0
 public void service(ServletRequest req, ServletResponse res)
     throws ServletException, IOException {
   System.out.println("\n\n-----Service called----\n");
   res.setContentType("text/html");
   PrintWriter out = res.getWriter();
   out.print("<html><body>");
   out.print("<b>hello simple servlet</b>");
   out.print("</body></html>");
 }
Example #18
0
  /**
   * 打印支持JSONP格式的结果
   *
   * @param response
   * @param restRequest
   * @param restResponse
   * @throws java.io.IOException
   */
  public static void printJsonForJsonp(
      HttpServletResponse response, RestRequest restRequest, RestResponse restResponse)
      throws IOException {

    PrintWriter out = response.getWriter();
    String jsonString = JSON.toJSONString(restResponse);
    response.setContentType("text/javascript; charset=UTF-8");
    out.print(restRequest.getCallback() + "(" + jsonString + ")");
  }
Example #19
0
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html"); // must come first
   PrintWriter out = response.getWriter();
   out.println(
       "<html><head><title>Hello Client!</title></head><body>"
           + "<h1>Hello Client!</h1>"
           + "</body></html>");
 }
Example #20
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // Set response content type
    response.setContentType("text/html");

    // Actual logic goes here.
    PrintWriter out = response.getWriter();
    out.println("<h1>" + message + "</h1>");
  }
Example #21
0
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    // read the last post id here .......................
    String url = req.getRequestURI();
    String urlprt[] = url.split("/");
    int urlcount = urlprt.length - 1;

    JSONParser parserPost = new JSONParser();
    JSONObject post = null;
    String id = urlprt[urlcount];

    // read the post  here .............................

    try {

      if (id != null) {
        Object objPost =
            parserPost.parse(new FileReader("..\\webapps\\Blog\\post\\" + id + ".json"));

        post = (JSONObject) objPost;
        String postauthor = post.get("author").toString();
        String posttitle = post.get("title").toString();
        String postcontent = post.get("content").toString();

        JSONArray arr = (JSONArray) post.get("comments");
        List<String> list = new ArrayList<String>();
        Iterator<String> iterator = arr.iterator();

        while (iterator.hasNext()) {
          list.add(iterator.next());
        }

        int listsz = list.size();
        String[] comments = new String[listsz];
        for (int i = 0; i < listsz; i++) {
          comments[i] = list.get(i);
        }

        req.setAttribute("title", posttitle);
        req.setAttribute("content", postcontent);
        req.setAttribute("author", postauthor);
        req.setAttribute("comments", comments);
        req.setAttribute("id", id);

        req.getRequestDispatcher("/view.jsp").forward(req, res);
      }

    } catch (Exception e) {
      res.setContentType("text/html");
      PrintWriter out = res.getWriter();
      out.println("get POST ......................");
      out.println(e);
      out.println("......................");
    }
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<h1>This is TestServlet.</h1>");
    out.println("<h1>The http request is GET.</h1>");
    out.println("<h2>Now is " + new Date() + "</h2>");

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

    // User user = new User();

    accesses++;
    out.print("Number of times this servlet has been accessed:" + accesses + " asdf " + accesses);
  }
  /**
   * Attempts to send an internal server error HTTP error, if possible. Otherwise simply pushes the
   * exception message to the output stream.
   *
   * @param message Message to be printed to the logger and to the output stream.
   * @param t Exception that caused the error.
   */
  protected void filterError(String message, Throwable t) {
    log.error("XSLT filter error: " + message, t);
    if (false == origResponse.isCommitted()) {
      // Reset the buffer and previous status code.
      origResponse.reset();
      origResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      origResponse.setContentType("text/html; charset=UTF-8");
    }

    // Response committed. Just push the error to the output stream.
    try {
      final OutputStream os = origResponse.getOutputStream();
      final PrintWriter osw = new PrintWriter(new OutputStreamWriter(os, "iso8859-1"));
      osw.write("<html><body><!-- " + XSLTFilterConstants.ERROR_TOKEN + " -->");
      osw.write("<h1 style=\"color: red; margin-top: 1em;\">");
      osw.write("Internal server exception");
      osw.write("</h1>");
      osw.write("<b>URI</b>: " + origRequest.getRequestURI() + "\n<br/><br/>");
      serializeException(osw, t);
      if (t instanceof ServletException && ((ServletException) t).getRootCause() != null) {
        osw.write("<br/><br/><h2>ServletException root cause:</h2>");
        serializeException(osw, ((ServletException) t).getRootCause());
      }
      osw.write("</body></html>");
      osw.flush();
    } catch (IOException e) {
      // Not much to do in such case (connection broken most likely).
      log.debug("Filter error could not be returned to client.");
    }
  }
Example #25
0
  public void doGet(HttpServletRequest rq, HttpServletResponse rs) {
    PrintWriter pw = null;
    try {
      pw = rs.getWriter();
      rs.setContentType("application/json");
      OperatorBLInterface operatorInterface = new Operator();
      LoyaltyApplication loyaltyApplication = new LoyaltyApplication();
      boolean found = loyaltyApplication.operatorExists(Integer.parseInt(rq.getParameter("code")));

      pw.println("{");
      pw.println("\"success\":true,");
      pw.println("\"found\":" + found);

      pw.println("}");
    } catch (ApplicationException ae) {
      System.out.println(ae);

      pw.println("{");
      pw.println("\"success\":false,");
      pw.println("\"errorMessage\":" + "\"" + ae + "\"");
      pw.println("}");
    } catch (Exception e) {
      System.out.println(e);
    }
  }
Example #26
0
  public void doGet(HttpServletRequest rq, HttpServletResponse rs) {
    PrintWriter pw = null;
    try {
      pw = rs.getWriter();
      rs.setContentType("application/json");
      LoyaltyApplication loyaltyApplication = new LoyaltyApplication();
      loyaltyApplication.removeOperator(Integer.parseInt(rq.getParameter("code")));
      pw.println("{");
      pw.println("\"success\":true,");
      pw.println("\"message\":\"removed\"");
      pw.println("}");

    } catch (ApplicationException ae) {

      System.out.println(ae);

      pw.println("{");
      pw.println("\"success\":false,");
      pw.println("\"errorMessage\":" + "\"" + ae + "\"");
      pw.println("}");

    } catch (IOException ioe) {
      System.out.println(ioe);
    }
  }
Example #27
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Reading All Request Parameters";
    out.println(
        ServletUtilities.headWithTitle(title)
            + "<BODY BGCOLOR=\"#FDF5E6\">\n"
            + "<H1 ALIGN=CENTER>"
            + title
            + "</H1>\n"
            + "<TABLE BORDER=1 ALIGN=CENTER>\n"
            + "<TR BGCOLOR=\"#FFAD00\">\n"
            + "<TH>Parameter Name<TH>Parameter Value(s)");
    Enumeration paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
      String paramName = (String) paramNames.nextElement();
      out.println("<TR><TD>" + paramName + "\n<TD>");
      String[] paramValues = request.getParameterValues(paramName);
      if (paramValues.length == 1) {
        String paramValue = paramValues[0];
        if (paramValue.length() == 0) out.print("<I>No Value</I>");
        else out.print(paramValue);
      } else {
        out.println("<UL>");
        for (int i = 0; i < paramValues.length; i++) {
          out.println("<LI>" + paramValues[i]);
        }
        out.println("</UL>");
      }
    }
    out.println("</TABLE>\n</BODY></HTML>");
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    System.out.println("[Servlet3.doPost]");

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("FILTER-REQUEST:" + request.getSession().getAttribute("FILTER-REQUEST"));
    out.println("FILTER-FORWARD:" + request.getSession().getAttribute("FILTER-FORWARD"));
    out.println("FILTER-INCLUDE:" + request.getSession().getAttribute("FILTER"));
  }
Example #29
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String users = getUsersFromDB();

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    HtmlUtilities.printHeader(out, "Registered Users");
    out.println(users);
    HtmlUtilities.printActions(out);
    HtmlUtilities.printFooter(out);
  }
Example #30
0
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   resp.setContentType("text/plain");
   PrintWriter pw = resp.getWriter();
   String color = getColor(req);
   if (color == null) {
     pw.print("No session found");
   } else {
     pw.print("You posted " + color);
   }
   pw.close();
 }