Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- /**
- *
- * @author Sinus @ qasko
- */
- @WebServlet(urlPatterns = {"/main"})
- public class main extends HttpServlet {
- String driver = "com.mysql.jdbc.Driver";
- Connection con = null;
- Statement stmt = null;
- ResultSet rs = null;
- String userName = "root";
- String password = "";
- String URL = "jdbc:mysql://localhost/obchod";
- HttpSession session;
- Integer id_usera = 0;
- @Override
- public void init() {
- try {
- super.init();
- Class.forName(driver);
- con = DriverManager.getConnection(URL, userName, password);
- } catch (ServletException | ClassNotFoundException | SQLException ex) {
- }
- }
- public void vypisTovaru(PrintWriter out) {
- Integer zlava = (Integer) session.getAttribute("zlava");
- double aktCena = 0;
- try {
- stmt = con.createStatement();
- rs = stmt.executeQuery("select * from sklad");
- while (rs.next()) {
- aktCena = rs.getDouble("cena") * (100 - zlava) / 100;
- out.println("<form action='main' method='post'>");
- out.println("<input type='hidden' name='ID' value='" + rs.getString("ID") + "'>");
- out.println("<input type='hidden' name='cena' value='" + aktCena + "'>");
- out.println("<div class='col-md-4'>");
- out.println("<div class=\"card\">");
- out.print("<img style='display: inline-block; width: 100%' alt='" + rs.getString("nazov") + "' class=\"card-img-top\" src=\"assets/images/" + rs.getString("ID") + ".jpg\">");
- out.println("<div class=\"card-block\">");
- out.println("<h4 class=\"card-title\">" + rs.getString("nazov") + "</h4>");
- out.println("<h5><small class='text-muted'>" + aktCena + " EUR</small></h5>");
- if (rs.getInt("ks") <= 0) {
- out.println("<h6><small class='text-muted'>Nie je skladom.</small></h6>");
- } else {
- out.println("<h6><small class='text-muted'>Skladom " + rs.getString("ks") + " ks</small></h6>");
- }
- out.println("<input style='margin-top: 1em' class='btn btn-primary' type='submit' name='tlacidlo' value='Do košíka'>");
- out.println("</div></div></div></form>");
- }
- stmt.close();
- } catch (Exception e) {
- out.println("Problém s čítaním " + e.toString());
- }
- }
- //**********************************************************************
- public int OverUsera(String meno, String heslo) {
- int vysledok = 0;
- try {
- stmt = con.createStatement();
- rs = stmt.executeQuery("select max(id) as iid,count(id) as pocet from pouzivatelia "
- + "where login='" + meno + "' and heslo='" + heslo + "'");
- rs.next();
- if (rs.getInt("pocet") == 1) {
- vysledok = rs.getInt("iid");
- }
- stmt.close();
- } catch (Exception ex) {
- return 0;
- }
- return vysledok;
- }
- //**********************************************************************
- public void ZobrazNeopravnenyPristup(PrintWriter out) {
- try {
- out.println("Neoprávnený prístup");
- } catch (Exception ex) {
- out.println(ex.toString());
- }
- }
- //**********************************************************************
- public void ZapamatajUdajeOUserovi(int id_usera) {
- // nacitam potrebne udaje z databazy
- try {
- stmt = con.createStatement();
- rs = stmt.executeQuery("select meno, priezvisko, zlava from pouzivatelia "
- + "where id='" + id_usera + "'");
- rs.next();
- // vlozim data do session
- // session uz bola vytvorena v processRequest
- // vlozime ID
- session.setAttribute("ID", (Integer) id_usera);
- // vlozime meno a priezvisko ako jeden celok :)
- session.setAttribute("meno", rs.getString("meno") + " " + rs.getString("priezvisko"));
- // vlozime zlavu ako cislo
- session.setAttribute("zlava", (Integer) rs.getInt("zlava"));
- // nastavim dlzku platnosti session
- session.setMaxInactiveInterval(600); // 10 minut
- stmt.close();
- } catch (Exception ex) {
- }
- }
- //*******************************************************************************
- public void ZapisDoKosika(Integer id_usera, String id_tovaru, String cena) {
- try {
- stmt = con.createStatement();
- // zistim, ci uz tovar tam je,
- rs = stmt.executeQuery("select count(ID) as pocet from kosik where "
- + "(ID_pouzivatela='" + id_usera + "') and "
- + "(id_tovaru ='" + id_tovaru + "')");
- rs.next();
- int pocet = rs.getInt("pocet");
- if (pocet == 0) {
- // ak nie vlozim ho
- String sstr = "insert into kosik (ID_pouzivatela, id_tovaru, cena, ks) values ("
- + "'" + id_usera + "', "
- + "'" + id_tovaru + "', "
- + "'" + cena + "', "
- + "'1') ";
- stmt.executeUpdate(sstr);
- } else {
- // ak ano, len zvysim pocet ks
- stmt.executeUpdate("update kosik set ks=ks+1, cena ='" + cena + "' where "
- + "(ID_pouzivatela='" + id_usera + "') and "
- + "(id_tovaru ='" + id_tovaru + "')");
- }
- stmt.close();
- } catch (Exception e) {
- }
- }
- public void VytvorNovehoUsera() {
- }
- public void zobrazKosik(PrintWriter out, int zlava) {
- if (con == null) // sem sa dostane vzdy a ak je problem informuje raz
- {
- out.println("Niet spojenia<BR />");
- } else {
- try {
- int count = 0;
- double cenaTotal = 0;
- stmt = con.createStatement();
- rs = stmt.executeQuery("select * from kosik inner join sklad ON kosik.ID_tovaru = sklad.ID where (ID_pouzivatela='" + id_usera + "')");
- out.print("<table style='margin-top: 3em' class=\"table\">"
- + "<thead class=\"thead-default\">"
- + "<tr>"
- + "<th>#</th>"
- + "<th>Nazov</th>"
- + "<th>Pocet (ks)</th>"
- + "<th>Cena</th>"
- + "<th>Akcia</th>"
- + "</tr>"
- + "</thead>"
- + "<tbody>");
- while (rs.next()) {
- count++;
- double aktCena = rs.getDouble("sklad.cena") * (100 - zlava) / 100;
- cenaTotal = (cenaTotal + (aktCena * rs.getDouble("ks")));
- 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>"
- + "<form action='main' method='post'><td><input type='submit' class='btn btn-danger' name='tlacidlo' value='X'>"
- + "<input type='hidden' name='ID' value='" + rs.getString("ID") + "'>"
- + "</td></form></tr>");
- }
- out.println("</tbody></table>");
- out.println("<h5 class='text-muted'>TOTAL: " + Math.round(cenaTotal * 100.00) / 100.00 + " EUR</h5><hr>");
- if (count > 0) { //zobraz objednavacie tlacidlo iba ak je resultset
- out.println("<form action='main' method='post'>");
- out.println("<input name='tlacidlo' class='btn btn-primary' type='submit' value='Objednat'>");
- out.println("</form>");
- }
- stmt.close();
- } catch (Exception e) {
- out.println("Problém s čítaním " + e.toString());
- }
- }
- }
- /**
- * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
- * methods.
- *
- * @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");
- try (PrintWriter out = response.getWriter()) {
- /* TODO output your page here. You may use following sample code. */
- out.println("<!DOCTYPE html>\n"
- + "<html lang=\"sk\">\n"
- + " <head>\n"
- + "\n"
- + " <meta charset=\"utf-8\">\n"
- + " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n"
- + " <meta http-equiv=\"x-ua-compatible\" content=\"ie=edge\">\n"
- + "\n"
- + " <title>Eshop</title>\n"
- + " <link rel=\"stylesheet\" href=\"assets/bootstrap.min.css\">\n"
- + "\n"
- + " </head>\n"
- + " <body><div style='margin-top: 1em' class=\"container\">");
- // ak uz je user prihlaseny, existuje session
- session = request.getSession();
- id_usera = (Integer) session.getAttribute("ID");
- if (id_usera == null) {
- // ak este neexistuje, potrebujeme ju vytvorit po overeni prav
- // ak to prislo z ineho ako prihlasovacieho formulara,
- // mohla vyprsat alebo moze ist o neopravneny pristup
- if (request.getContentType() == null) {
- response.sendRedirect(request.getContextPath());
- return;
- }
- // ak neexistovala session, moze este ist o prvy pristup alebo kosik
- String tlacidlo = (request.getParameter("tlacidlo")).substring(0, 1);
- // ak to prislo z prihlasovacieho formulara, prislo to loginom
- // zabezpecim overenie prihlasenia
- // bud ide o login - "Vstup"
- if (tlacidlo.equals("V")) {
- id_usera = OverUsera(request.getParameter("meno"), request.getParameter("heslo"));
- if (id_usera == 0) {
- response.sendRedirect(request.getContextPath() + "/");
- return;
- }
- if (request.getParameter("meno").isEmpty() || request.getParameter("heslo").isEmpty()) {
- response.sendRedirect(request.getContextPath() + "/");
- return;
- }
- // nova session, potrebujem ju naplnit udajmi
- // zapamatam si ID aj meno a zlavu, aby sa mi jednoduchsie pracovalo
- ZapamatajUdajeOUserovi(id_usera);
- }
- /*
- * registracia usera
- *
- */
- if (tlacidlo.equals("R")) {
- String username = request.getParameter("username");
- String heslo = request.getParameter("heslo");
- String email = request.getParameter("email");
- String meno = request.getParameter("meno");
- String priezvisko = request.getParameter("priezvisko");
- String adresa = request.getParameter("adresa");
- if (username.isEmpty() || heslo.isEmpty() || email.isEmpty() || meno.isEmpty() || priezvisko.isEmpty() || adresa.isEmpty()) {
- response.sendRedirect(request.getContextPath() + "/register.html");
- }
- if (username.length() > 20 || heslo.length() > 20 || email.length() > 40 || adresa.length() > 50 || meno.length() > 20 || priezvisko.length() > 20) {
- response.sendRedirect(request.getContextPath() + "/register.html");
- }
- try {
- stmt = con.createStatement();
- stmt.executeUpdate("insert into pouzivatelia (login, heslo, mail, adresa, meno, priezvisko, zlava, poznamky) values ("
- + "'" + username + "', "
- + "'" + heslo + "', "
- + "'" + email + "', "
- + "'" + adresa + "', "
- + "'" + meno + "', "
- + "'" + priezvisko + "', "
- + "'0', "
- + "''"
- + ")");
- } catch (SQLException ex) {
- Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
- return;
- }
- response.sendRedirect(request.getContextPath() + "/");
- return;
- }
- }
- // inak je user uz prihlaseny a mam jeho data
- String meno = (String) session.getAttribute("meno");
- out.println("<div class=\"text-xs-right text-muted\">" + meno + "</div>");
- int zlava = (Integer) session.getAttribute("zlava");
- out.println("<div class=\"text-xs-right text-muted\">Zlava: " + zlava + "%</div><hr>");
- // home btn
- out.println("<div class=\"text-xs-right text-muted\"><a role='button' class='btn btn-info' href='" + request.getContextPath() + "/main'>Home</a>");
- // tlacidlo pre zoznam objednavok
- out.println("<a role='button' class='btn btn-warning' href='#'>Zoznam objednavok</a>");
- // tlacidlo pre kosik
- //out.println("<a role='button' class='btn btn-success' href='kosik'>Košík</a>");
- out.println("<form style='display: inline' method='post' action='main'><input type='submit' name='tlacidlo' value='Kosik' class='btn btn-success'></form>");
- // odhlasenie
- out.println("<a role='button' class='btn btn-primary' href='logout'>Odhlasenie</a></div>");
- // zoznam tovaru s moznostou objednat
- if ((request.getContentType() == null) || (request.getParameter("tlacidlo").substring(0, 1).equals("V")) || (request.getParameter("tlacidlo").substring(0, 1).equals("D"))) {
- out.println("<div style='margin-top: 3em' class='row'>");
- vypisTovaru(out);
- out.println("</div>");
- }
- // ak nieje volane naprazdno zostava pridanie tovaru
- if (request.getContentType() != null) {
- String tlacidlo = (request.getParameter("tlacidlo")).substring(0, 1);
- // alebo o pridanie do kosika - "Do kosika"
- if (tlacidlo.equals("D")) {
- ZapisDoKosika(id_usera, request.getParameter("ID"), request.getParameter("cena"));
- }
- if (tlacidlo.equals("K")) {
- zobrazKosik(out, zlava);
- }
- if (tlacidlo.equals("X")) {
- try {
- stmt = con.createStatement();
- stmt.executeUpdate("DELETE FROM kosik WHERE kosik.id = " + request.getParameter("ID"));
- zobrazKosik(out, zlava);
- stmt.close();
- } catch (SQLException ex) {
- Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- if (tlacidlo.equals("O")) {
- try {
- double celkovaCena = 0;
- stmt = con.createStatement();
- rs = stmt.executeQuery("select cena, ks from kosik where id_pouzivatela =" + id_usera);
- while (rs.next()) {
- celkovaCena = celkovaCena + (rs.getDouble("cena") * rs.getInt("ks"));
- }
- stmt.executeUpdate("insert into obj_zoznam (datum_objednavky, id_pouzivatela, suma, stav) values ("
- + "NOW(), "
- + "'" + id_usera + "', "
- + "'" + Math.round(celkovaCena * 100.00) / 100.00 + "', "
- + "'evidovana'"
- + ")", Statement.RETURN_GENERATED_KEYS);
- rs = stmt.getGeneratedKeys();
- rs.next();
- int orderID = rs.getInt(1);
- String sql = "insert into obj_polozky (id_objednavky, id_tovaru, cena, ks) VALUES (?, ?, ?, ?)";
- PreparedStatement ps = con.prepareStatement(sql);
- rs = stmt.executeQuery("SELECT * FROM kosik WHERE id_pouzivatela =" + id_usera);
- while (rs.next()) {
- String id_tovaru = rs.getString("ID_tovaru");
- double cena = rs.getDouble("cena");
- int ks = rs.getInt("ks");
- ps.setInt(1, orderID);
- ps.setString(2, id_tovaru);
- ps.setDouble(3, cena);
- ps.setInt(4, ks);
- ps.executeUpdate();
- }
- //vymazene kosik
- stmt.executeUpdate("delete from kosik where id_pouzivatela = " + id_usera);
- stmt.close();
- out.println("<div style='margin-top: 3em' class='alert alert-success'>Objednavka bola uspesne odoslana.</div>");
- out.println("Budete presmerovany na domovsku stranku za 3 sekundy...");
- response.setHeader("Refresh", "3;url=main");
- } catch (SQLException ex) {
- Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- }
- out.println("</div>");
- out.println(" <script src=\"assets/jquery.min.js\"></script>\n"
- + " <script src=\"assets/bootstrap.min.js\"></script>");
- out.println("</body>");
- out.println("</html>");
- }
- }
- // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
- /**
- * Handles the HTTP <code>GET</code> method.
- *
- * @param request servlet request
- * @param response servlet response
- * @throws ServletException if a servlet-specific error occurs
- * @throws IOException if an I/O error occurs
- */
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- processRequest(request, response);
- }
- /**
- * Handles the HTTP <code>POST</code> method.
- *
- * @param request servlet request
- * @param response servlet response
- * @throws ServletException if a servlet-specific error occurs
- * @throws IOException if an I/O error occurs
- */
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- processRequest(request, response);
- }
- /**
- * Returns a short description of the servlet.
- *
- * @return a String containing servlet description
- */
- @Override
- public String getServletInfo() {
- return "Short description";
- }// </editor-fold>
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement