Advertisement
Guest User

Untitled

a guest
Jun 21st, 2016
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 20.77 KB | None | 0 0
  1.  
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.sql.SQLException;
  9. import java.sql.Statement;
  10. import java.util.logging.Level;
  11. import java.util.logging.Logger;
  12. import javax.servlet.ServletException;
  13. import javax.servlet.annotation.WebServlet;
  14. import javax.servlet.http.HttpServlet;
  15. import javax.servlet.http.HttpServletRequest;
  16. import javax.servlet.http.HttpServletResponse;
  17. import javax.servlet.http.HttpSession;
  18.  
  19. /**
  20.  *
  21.  * @author Sinus @ qasko
  22.  */
  23. @WebServlet(urlPatterns = {"/main"})
  24. public class main extends HttpServlet {
  25.  
  26.     String driver = "com.mysql.jdbc.Driver";
  27.     Connection con = null;
  28.     Statement stmt = null;
  29.     ResultSet rs = null;
  30.     String userName = "root";
  31.     String password = "";
  32.     String URL = "jdbc:mysql://localhost/obchod";
  33.     HttpSession session;
  34.     Integer id_usera = 0;
  35.  
  36.     @Override
  37.     public void init() {
  38.         try {
  39.             super.init();
  40.             Class.forName(driver);
  41.             con = DriverManager.getConnection(URL, userName, password);
  42.         } catch (ServletException | ClassNotFoundException | SQLException ex) {
  43.         }
  44.     }
  45.  
  46.     public void vypisTovaru(PrintWriter out) {
  47.         Integer zlava = (Integer) session.getAttribute("zlava");
  48.         double aktCena = 0;
  49.  
  50.         try {
  51.             stmt = con.createStatement();
  52.             rs = stmt.executeQuery("select * from sklad");
  53.             while (rs.next()) {
  54.                 aktCena = rs.getDouble("cena") * (100 - zlava) / 100;
  55.  
  56.                 out.println("<form action='main' method='post'>");
  57.                 out.println("<input type='hidden' name='ID' value='" + rs.getString("ID") + "'>");
  58.                 out.println("<input type='hidden' name='cena' value='" + aktCena + "'>");
  59.                 out.println("<div class='col-md-4'>");
  60.                 out.println("<div class=\"card\">");
  61.                 out.print("<img style='display: inline-block; width: 100%' alt='" + rs.getString("nazov") + "' class=\"card-img-top\" src=\"assets/images/" + rs.getString("ID") + ".jpg\">");
  62.                 out.println("<div class=\"card-block\">");
  63.                 out.println("<h4 class=\"card-title\">" + rs.getString("nazov") + "</h4>");
  64.                 out.println("<h5><small class='text-muted'>" + aktCena + " EUR</small></h5>");
  65.                 if (rs.getInt("ks") <= 0) {
  66.                     out.println("<h6><small class='text-muted'>Nie je skladom.</small></h6>");
  67.                 } else {
  68.                     out.println("<h6><small class='text-muted'>Skladom " + rs.getString("ks") + " ks</small></h6>");
  69.                 }
  70.  
  71.                 out.println("<input style='margin-top: 1em' class='btn btn-primary' type='submit' name='tlacidlo' value='Do košíka'>");
  72.                 out.println("</div></div></div></form>");
  73.             }
  74.             stmt.close();
  75.         } catch (Exception e) {
  76.             out.println("Problém s čítaním " + e.toString());
  77.         }
  78.     }
  79.     //**********************************************************************
  80.  
  81.     public int OverUsera(String meno, String heslo) {
  82.         int vysledok = 0;
  83.         try {
  84.             stmt = con.createStatement();
  85.             rs = stmt.executeQuery("select max(id) as iid,count(id) as pocet from pouzivatelia "
  86.                     + "where login='" + meno + "' and heslo='" + heslo + "'");
  87.  
  88.             rs.next();
  89.             if (rs.getInt("pocet") == 1) {
  90.                 vysledok = rs.getInt("iid");
  91.             }
  92.             stmt.close();
  93.         } catch (Exception ex) {
  94.             return 0;
  95.         }
  96.         return vysledok;
  97.     }
  98. //**********************************************************************
  99.  
  100.     public void ZobrazNeopravnenyPristup(PrintWriter out) {
  101.  
  102.         try {
  103.             out.println("Neoprávnený prístup");
  104.         } catch (Exception ex) {
  105.             out.println(ex.toString());
  106.         }
  107.     }
  108.  
  109.     //**********************************************************************
  110.     public void ZapamatajUdajeOUserovi(int id_usera) {
  111.         // nacitam potrebne udaje z databazy
  112.         try {
  113.             stmt = con.createStatement();
  114.             rs = stmt.executeQuery("select meno, priezvisko, zlava from pouzivatelia "
  115.                     + "where id='" + id_usera + "'");
  116.             rs.next();
  117.             // vlozim data do session
  118.             // session uz bola vytvorena v processRequest
  119.  
  120.             // vlozime ID
  121.             session.setAttribute("ID", (Integer) id_usera);
  122.             // vlozime meno a priezvisko ako jeden celok :)
  123.             session.setAttribute("meno", rs.getString("meno") + " " + rs.getString("priezvisko"));
  124.             // vlozime zlavu ako cislo
  125.             session.setAttribute("zlava", (Integer) rs.getInt("zlava"));
  126.             // nastavim dlzku platnosti session
  127.             session.setMaxInactiveInterval(600); // 10 minut
  128.  
  129.             stmt.close();
  130.         } catch (Exception ex) {
  131.         }
  132.     }
  133.  
  134.     //*******************************************************************************
  135.     public void ZapisDoKosika(Integer id_usera, String id_tovaru, String cena) {
  136.         try {
  137.             stmt = con.createStatement();
  138.             // zistim, ci uz tovar tam je,
  139.             rs = stmt.executeQuery("select count(ID) as pocet from kosik where "
  140.                     + "(ID_pouzivatela='" + id_usera + "') and "
  141.                     + "(id_tovaru ='" + id_tovaru + "')");
  142.             rs.next();
  143.             int pocet = rs.getInt("pocet");
  144.  
  145.             if (pocet == 0) {
  146.                 // ak nie vlozim ho
  147.                 String sstr = "insert into kosik (ID_pouzivatela, id_tovaru, cena, ks) values ("
  148.                         + "'" + id_usera + "', "
  149.                         + "'" + id_tovaru + "', "
  150.                         + "'" + cena + "', "
  151.                         + "'1') ";
  152.                 stmt.executeUpdate(sstr);
  153.             } else {
  154.                 // ak ano, len zvysim pocet ks
  155.                 stmt.executeUpdate("update kosik set ks=ks+1, cena ='" + cena + "' where "
  156.                         + "(ID_pouzivatela='" + id_usera + "') and "
  157.                         + "(id_tovaru ='" + id_tovaru + "')");
  158.             }
  159.             stmt.close();
  160.         } catch (Exception e) {
  161.         }
  162.     }
  163.  
  164.     public void VytvorNovehoUsera() {
  165.  
  166.     }
  167.  
  168.     public void zobrazKosik(PrintWriter out, int zlava) {
  169.         if (con == null) // sem sa dostane vzdy a ak je problem informuje raz
  170.         {
  171.             out.println("Niet spojenia<BR />");
  172.         } else {
  173.  
  174.             try {
  175.                 int count = 0;
  176.                 double cenaTotal = 0;
  177.                 stmt = con.createStatement();
  178.  
  179.                 rs = stmt.executeQuery("select * from kosik inner join sklad ON kosik.ID_tovaru = sklad.ID where (ID_pouzivatela='" + id_usera + "')");
  180.  
  181.                 out.print("<table style='margin-top: 3em' class=\"table\">"
  182.                         + "<thead class=\"thead-default\">"
  183.                         + "<tr>"
  184.                         + "<th>#</th>"
  185.                         + "<th>Nazov</th>"
  186.                         + "<th>Pocet (ks)</th>"
  187.                         + "<th>Cena</th>"
  188.                         + "<th>Akcia</th>"
  189.                         + "</tr>"
  190.                         + "</thead>"
  191.                         + "<tbody>");
  192.  
  193.                 while (rs.next()) {
  194.  
  195.                     count++;
  196.  
  197.                     double aktCena = rs.getDouble("sklad.cena") * (100 - zlava) / 100;
  198.  
  199.                     cenaTotal = (cenaTotal + (aktCena * rs.getDouble("ks")));
  200.  
  201.                     out.println("<tr><th scope=\"row\">" + rs.getString("ID") + "</th><td>" + rs.getString("sklad.nazov") + "</td><td>" + rs.getString("ks") + "</td><td>" + Math.round(aktCena * rs.getDouble("ks") * 100.0) / 100.0 + " EUR</td>"
  202.                             + "<form action='main' method='post'><td><input type='submit' class='btn btn-danger' name='tlacidlo' value='X'>"
  203.                             + "<input type='hidden' name='ID' value='" + rs.getString("ID") + "'>"
  204.                             + "</td></form></tr>");
  205.  
  206.                 }
  207.  
  208.                 out.println("</tbody></table>");
  209.                 out.println("<h5 class='text-muted'>TOTAL: " + Math.round(cenaTotal * 100.00) / 100.00 + " EUR</h5><hr>");
  210.  
  211.                 if (count > 0) { //zobraz objednavacie tlacidlo iba ak je resultset
  212.                     out.println("<form action='main' method='post'>");
  213.                     out.println("<input name='tlacidlo' class='btn btn-primary' type='submit' value='Objednat'>");
  214.                     out.println("</form>");
  215.                 }
  216.  
  217.                 stmt.close();
  218.             } catch (Exception e) {
  219.                 out.println("Problém s čítaním " + e.toString());
  220.             }
  221.         }
  222.     }
  223.  
  224.     /**
  225.      * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
  226.      * methods.
  227.      *
  228.      * @param request servlet request
  229.      * @param response servlet response
  230.      * @throws ServletException if a servlet-specific error occurs
  231.      * @throws IOException if an I/O error occurs
  232.      */
  233.     protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  234.             throws ServletException, IOException {
  235.         response.setContentType("text/html;charset=UTF-8");
  236.         try (PrintWriter out = response.getWriter()) {
  237.             /* TODO output your page here. You may use following sample code. */
  238.             out.println("<!DOCTYPE html>\n"
  239.                     + "<html lang=\"sk\">\n"
  240.                     + "    <head>\n"
  241.                     + "\n"
  242.                     + "        <meta charset=\"utf-8\">\n"
  243.                     + "        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n"
  244.                     + "        <meta http-equiv=\"x-ua-compatible\" content=\"ie=edge\">\n"
  245.                     + "\n"
  246.                     + "        <title>Eshop</title>\n"
  247.                     + "        <link rel=\"stylesheet\" href=\"assets/bootstrap.min.css\">\n"
  248.                     + "\n"
  249.                     + "    </head>\n"
  250.                     + "    <body><div style='margin-top: 1em' class=\"container\">");
  251.  
  252.             // ak uz je user prihlaseny, existuje session
  253.             session = request.getSession();
  254.  
  255.             id_usera = (Integer) session.getAttribute("ID");
  256.  
  257.             if (id_usera == null) {
  258.                 // ak este neexistuje, potrebujeme ju vytvorit po overeni prav
  259.                 // ak to prislo z ineho ako prihlasovacieho formulara,
  260.                 // mohla vyprsat alebo moze ist o neopravneny pristup
  261.                 if (request.getContentType() == null) {
  262.                     response.sendRedirect(request.getContextPath());
  263.                     return;
  264.                 }
  265.  
  266.                 // ak neexistovala session, moze este ist o prvy pristup alebo kosik
  267.                 String tlacidlo = (request.getParameter("tlacidlo")).substring(0, 1);
  268.                 // ak to prislo z prihlasovacieho formulara, prislo to loginom  
  269.                 // zabezpecim overenie prihlasenia
  270.  
  271.                 // bud ide o login - "Vstup"
  272.                 if (tlacidlo.equals("V")) {
  273.                     id_usera = OverUsera(request.getParameter("meno"), request.getParameter("heslo"));
  274.                     if (id_usera == 0) {
  275.                         response.sendRedirect(request.getContextPath() + "/");
  276.                         return;
  277.                     }
  278.                     if (request.getParameter("meno").isEmpty() || request.getParameter("heslo").isEmpty()) {
  279.                         response.sendRedirect(request.getContextPath() + "/");
  280.                         return;
  281.                     }
  282.                     // nova session, potrebujem ju naplnit udajmi
  283.                     // zapamatam si ID aj meno a zlavu, aby sa mi jednoduchsie pracovalo
  284.                     ZapamatajUdajeOUserovi(id_usera);
  285.                 }
  286.  
  287.                 /*
  288.                  * registracia usera
  289.                  *
  290.                  */
  291.                 if (tlacidlo.equals("R")) {
  292.                     String username = request.getParameter("username");
  293.                     String heslo = request.getParameter("heslo");
  294.                     String email = request.getParameter("email");
  295.                     String meno = request.getParameter("meno");
  296.                     String priezvisko = request.getParameter("priezvisko");
  297.                     String adresa = request.getParameter("adresa");
  298.  
  299.                     if (username.isEmpty() || heslo.isEmpty() || email.isEmpty() || meno.isEmpty() || priezvisko.isEmpty() || adresa.isEmpty()) {
  300.                         response.sendRedirect(request.getContextPath() + "/register.html");
  301.                     }
  302.  
  303.                     if (username.length() > 20 || heslo.length() > 20 || email.length() > 40 || adresa.length() > 50 || meno.length() > 20 || priezvisko.length() > 20) {
  304.                         response.sendRedirect(request.getContextPath() + "/register.html");
  305.                     }
  306.  
  307.                     try {
  308.                         stmt = con.createStatement();
  309.                         stmt.executeUpdate("insert into pouzivatelia (login, heslo, mail, adresa, meno, priezvisko, zlava, poznamky) values ("
  310.                                 + "'" + username + "', "
  311.                                 + "'" + heslo + "', "
  312.                                 + "'" + email + "', "
  313.                                 + "'" + adresa + "', "
  314.                                 + "'" + meno + "', "
  315.                                 + "'" + priezvisko + "', "
  316.                                 + "'0', "
  317.                                 + "''"
  318.                                 + ")");
  319.                     } catch (SQLException ex) {
  320.                         Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
  321.                         return;
  322.                     }
  323.  
  324.                     response.sendRedirect(request.getContextPath() + "/");
  325.  
  326.                     return;
  327.                 }
  328.  
  329.             }
  330.  
  331.             // inak je user uz prihlaseny a mam jeho data
  332.             String meno = (String) session.getAttribute("meno");
  333.             out.println("<div class=\"text-xs-right text-muted\">" + meno + "</div>");
  334.  
  335.             int zlava = (Integer) session.getAttribute("zlava");
  336.             out.println("<div class=\"text-xs-right text-muted\">Zlava: " + zlava + "%</div><hr>");
  337.  
  338.             // home btn
  339.             out.println("<div class=\"text-xs-right text-muted\"><a role='button' class='btn btn-info' href='" + request.getContextPath() + "/main'>Home</a>");
  340.  
  341.             // tlacidlo pre zoznam objednavok
  342.             out.println("<a role='button' class='btn btn-warning' href='#'>Zoznam objednavok</a>");
  343.  
  344.             // tlacidlo pre kosik
  345.             //out.println("<a role='button' class='btn btn-success' href='kosik'>Košík</a>");
  346.             out.println("<form style='display: inline' method='post' action='main'><input type='submit' name='tlacidlo' value='Kosik' class='btn btn-success'></form>");
  347.  
  348.             // odhlasenie
  349.             out.println("<a role='button' class='btn btn-primary' href='logout'>Odhlasenie</a></div>");
  350.  
  351.             // zoznam tovaru s moznostou objednat
  352.             if ((request.getContentType() == null) || (request.getParameter("tlacidlo").substring(0, 1).equals("V")) || (request.getParameter("tlacidlo").substring(0, 1).equals("D"))) {
  353.                 out.println("<div style='margin-top: 3em' class='row'>");
  354.                 vypisTovaru(out);
  355.                 out.println("</div>");
  356.             }
  357.  
  358.             // ak nieje volane naprazdno zostava pridanie tovaru
  359.             if (request.getContentType() != null) {
  360.                 String tlacidlo = (request.getParameter("tlacidlo")).substring(0, 1);
  361.  
  362.                 // alebo o pridanie do kosika - "Do kosika"
  363.                 if (tlacidlo.equals("D")) {
  364.                     ZapisDoKosika(id_usera, request.getParameter("ID"), request.getParameter("cena"));
  365.                 }
  366.  
  367.                 if (tlacidlo.equals("K")) {
  368.                     zobrazKosik(out, zlava);
  369.                 }
  370.  
  371.                 if (tlacidlo.equals("X")) {
  372.                     try {
  373.                         stmt = con.createStatement();
  374.  
  375.                         stmt.executeUpdate("DELETE FROM kosik WHERE kosik.id = " + request.getParameter("ID"));
  376.  
  377.                         zobrazKosik(out, zlava);
  378.  
  379.                         stmt.close();
  380.                     } catch (SQLException ex) {
  381.                         Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
  382.                     }
  383.                 }
  384.  
  385.                 if (tlacidlo.equals("O")) {
  386.                     try {
  387.                         double celkovaCena = 0;
  388.  
  389.                         stmt = con.createStatement();
  390.  
  391.                         rs = stmt.executeQuery("select cena, ks from kosik where id_pouzivatela =" + id_usera);
  392.                         while (rs.next()) {
  393.                             celkovaCena = celkovaCena + (rs.getDouble("cena") * rs.getInt("ks"));
  394.                         }
  395.  
  396.                         stmt.executeUpdate("insert into obj_zoznam (datum_objednavky, id_pouzivatela, suma, stav) values ("
  397.                                 + "NOW(), "
  398.                                 + "'" + id_usera + "', "
  399.                                 + "'" + Math.round(celkovaCena * 100.00) / 100.00 + "', "
  400.                                 + "'evidovana'"
  401.                                 + ")", Statement.RETURN_GENERATED_KEYS);
  402.  
  403.                         rs = stmt.getGeneratedKeys();
  404.                         rs.next();
  405.                         int orderID = rs.getInt(1);
  406.  
  407.                         String sql = "insert into obj_polozky (id_objednavky, id_tovaru, cena, ks) VALUES (?, ?, ?, ?)";
  408.  
  409.                         PreparedStatement ps = con.prepareStatement(sql);
  410.  
  411.                         rs = stmt.executeQuery("SELECT * FROM kosik WHERE id_pouzivatela =" + id_usera);
  412.  
  413.                         while (rs.next()) {
  414.  
  415.                             String id_tovaru = rs.getString("ID_tovaru");
  416.                             double cena = rs.getDouble("cena");
  417.                             int ks = rs.getInt("ks");
  418.  
  419.                             ps.setInt(1, orderID);
  420.                             ps.setString(2, id_tovaru);
  421.                             ps.setDouble(3, cena);
  422.                             ps.setInt(4, ks);
  423.  
  424.                             ps.executeUpdate();
  425.  
  426.                         }
  427.  
  428.                         //vymazene kosik
  429.                         stmt.executeUpdate("delete from kosik where id_pouzivatela = " + id_usera);
  430.  
  431.                         stmt.close();
  432.  
  433.                         out.println("<div style='margin-top: 3em' class='alert alert-success'>Objednavka bola uspesne odoslana.</div>");
  434.                         out.println("Budete presmerovany na domovsku stranku za 3 sekundy...");
  435.  
  436.                         response.setHeader("Refresh", "3;url=main");
  437.  
  438.                     } catch (SQLException ex) {
  439.                         Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
  440.                     }
  441.                 }
  442.             }
  443.  
  444.             out.println("</div>");
  445.             out.println("        <script src=\"assets/jquery.min.js\"></script>\n"
  446.                     + "        <script src=\"assets/bootstrap.min.js\"></script>");
  447.             out.println("</body>");
  448.             out.println("</html>");
  449.  
  450.         }
  451.     }
  452.  
  453.     // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  454.     /**
  455.      * Handles the HTTP <code>GET</code> method.
  456.      *
  457.      * @param request servlet request
  458.      * @param response servlet response
  459.      * @throws ServletException if a servlet-specific error occurs
  460.      * @throws IOException if an I/O error occurs
  461.      */
  462.     @Override
  463.     protected void doGet(HttpServletRequest request, HttpServletResponse response)
  464.             throws ServletException, IOException {
  465.         processRequest(request, response);
  466.     }
  467.  
  468.     /**
  469.      * Handles the HTTP <code>POST</code> method.
  470.      *
  471.      * @param request servlet request
  472.      * @param response servlet response
  473.      * @throws ServletException if a servlet-specific error occurs
  474.      * @throws IOException if an I/O error occurs
  475.      */
  476.     @Override
  477.     protected void doPost(HttpServletRequest request, HttpServletResponse response)
  478.             throws ServletException, IOException {
  479.         processRequest(request, response);
  480.     }
  481.  
  482.     /**
  483.      * Returns a short description of the servlet.
  484.      *
  485.      * @return a String containing servlet description
  486.      */
  487.     @Override
  488.     public String getServletInfo() {
  489.         return "Short description";
  490.     }// </editor-fold>
  491.  
  492. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement