簡體   English   中英

學習在 Java Servlet 連接到 db 中編程

[英]Learn to program in Java Servlet connection to db

我正在學習用java編程以及servlet和jsp頁面的使用。

我在理解如何與數據庫建立連接時遇到了一些麻煩。 特別是我有一個名為 Database.java 的 Java 頁面,我在其中創建了與數據庫的連接,並在其中執行了所有功能。 我創建了一個名為 Prenotation.java 的頁面,我必須在其中執行一些操作。 我的問題是我不想在此頁面上保留數據庫連接(正如您從代碼中看到的那樣),但我想通過 Database.java 頁面建立連接。 我已經嘗試了幾次,但我不明白我該怎么做。 你能給我一些建議嗎? 謝謝你。

數據庫.java

package db;
import java.math.BigDecimal;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;

import entity.*;

public class Database {

    private Connection connection = null;
    private PreparedStatement statement = null;
    private ResultSet rs = null;

    private String dbname = "Hotel";
    String nomeutente = "root";
    String password = "123456789";
     private static Database db = null;

    public static synchronized Database getDatabase() {
        if (db == null) {
            db = new Database();
        }
        return db;
    }
    private Database() {
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + dbname 
                    + "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC",
                    nomeutente, password);
        } catch (Exception exc) {
            exc.printStackTrace();
        }
    }
    public Connection getConnection() {
        return connection;
    }
    public boolean checkUser(String email, String password) throws SQLException {
        boolean result = false;
        String query = "select password from users where email=?";

            statement = connection.prepareStatement(query);
            statement.setString(1, email);
            rs = statement.executeQuery();
            if (rs.next() && password.equals(rs.getString("password"))) {
                result = true;
            }

            rs.close();
            statement.close();

        return result;
    }
    public boolean existingMail(String email) throws SQLException {
        String query = "select * from users where email=?";
        boolean result = true;
        statement = connection.prepareStatement(query);
        statement.setString(1, email);
        rs = statement.executeQuery();

        if (rs.next()) {
            result = true;
        } else {
            result = false;
        }
        rs.close();
        statement.close();
        return result;
    }

    public boolean insertUtente(Utente u,String password) throws SQLException {
         String query = "INSERT INTO users (email,nome,cognome,luogodinascita,datadinascita,indirizzo,password) VALUES (?,?,?,?,?,?,?)";
         if(existingMail(u.getEmail())) {
             return false;
         } 
            statement = connection.prepareStatement(query);
            statement.setString(1, u.getEmail());
            statement.setString(2, u.getNome());
            statement.setString(3, u.getCognome());
            statement.setString(4, u.getLuogodinascita());
            statement.setString(5, u.getDatadinascita());
            statement.setString(6, u.getIndirizzo());
            statement.setString(7, password);
            statement.execute();
            statement.close();
            return true;

    }

    public Utente getUtente(String email) throws SQLException {
        String query= "select * from users where email=?";
        statement = connection.prepareStatement(query);
        statement.setString(1, email);
        rs=statement.executeQuery();
        if(!rs.next()) {
            return null;
        }
        Utente u=new Utente(email,rs.getString("nome"),rs.getString("cognome"),rs.getString("datadinascita"),rs.getString("luogodinascita"),rs.getString("indirizzo"));
        rs.close();
        statement.close();
        return u;
    }

    public boolean modificaPassword(String email, String password) throws SQLException {
        String query="UPDATE users SET password='"+password+"' WHERE email='"+email+"'";   
        Statement statement=connection.createStatement();
        statement.executeUpdate(query);
        statement.close();
        return true;
    }
    public boolean modificaProfilo(Utente u) throws SQLException {
        String query="UPDATE users SET nome = ?, cognome = ?, datadinascita = ?, luogodinascita = ?, indirizzo = ? WHERE email = ?";
        statement = connection.prepareStatement(query);
        statement.setString(1, u.getNome());
        statement.setString(2, u.getCognome());
        statement.setString(3, u.getDatadinascita());
        statement.setString(4, u.getLuogodinascita());
        statement.setString(5, u.getIndirizzo());
        statement.setString(6, u.getEmail());
        statement.executeUpdate();
        statement.close();
        return true;
    }}

這是我所說的頁面

package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;
import db.Database;
import entity.Prenotazione;
/**
 *
 * @author OOPs
 */
public class Prenotation extends HttpServlet {

    private static final String ResultSet = null;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session=request.getSession();
         String idPrenotazione = request.getParameter("idPrenotazione");
         String email = request.getParameter("email");
         int typeRoom = Integer.parseInt(request.getParameter("typeRoom"));;
         String arrivalDate = request.getParameter("arrivalDate");
         String departureDate = request.getParameter("departureDate");
         response.setContentType("text/html;charset=UTF-8");
         PrintWriter out = response.getWriter();

       try {

            Class.forName("com.mysql.cj.jdbc.Driver");
      //  out.println("driver loaded");
            Connection  con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Hotel?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root" ,"123456789");
            out.println("Connect");


            Statement  st =  con.createStatement();
           // Statement stmt = con.createStatement();
            out.println("connection successfull");
            int total = 0;
            PreparedStatement ps = con.prepareStatement( "SELECT COUNT(*) as total FROM reservation WHERE typeRoom = ? AND (? >= arrivaldate AND ? <= departuredate) OR (? >= arrivaldate AND ? <= departuredate)");

            int c = 0;
            ps.setInt(++c, typeRoom);
            ps.setString(++c, arrivalDate);
            ps.setString(++c, departureDate);
            ps.setString(++c, arrivalDate);
            ps.setString(++c, departureDate);

            ResultSet rs = ps.executeQuery();

           // ResultSet rs2  = stmt.executeQuery(check);
            out.println("<h1> Stringa check eseguito </h1>");

            if( total  > 0) { 
            //  response.sendRedirect("home.jsp");
                response.sendRedirect("PrenotazioneNegata.jsp");
            }
            else {
             st.executeUpdate("insert into reservation (email,typeRoom,arrivalDate,departureDate)values ('"+email+"','"+typeRoom+"','"+arrivalDate+"','"+departureDate+"')");
             response.sendRedirect("PrenotazioneAvvenuta.jsp");
            }
          out.println("<h1> Registrazione Eseguita </h1>");

        }catch(Exception e){
        out.println("Errore." +e);
        }
        finally {
            out.close();
        }
    }

    // <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>

}

Web 容器通常會將請求路由到同一個 servlet 實例,因此它需要是線程安全的。 目前, Database類提供了一個單一的連接,它將被並發請求使用,因此它不是線程安全的。

考慮創建類似ConnectionFactory類的東西。 例如:

public class ConnectionFactory {
    public Connection getConnection() {
        // move all the creation code from Database class to here
        // create and return a new instance
    }
}

然后修改Database類使用工廠

public class Database {
   private final ConnectionFactory connectionFactory;

   public Database(ConnectionFactory connectionFactory) {
      this.connectionFactory = connectionFactory;
   }

   // change to private and use the factory
   private Connection getConnection() {
      return connectionFactory.getConnection();
   }

   // example method to be used by servlet
   public int getTotalReservations(int typeRoom, String arrivalDate, departureDate) {
      // query related code currently in serlvet goes here...
   }
}

並使用 servlet 生命周期init()方法創建對象,以便 servlet 可以使用它。 例如:

public class Prenotation extends HttpServlet {
    private Database database;

    @Override
    public void init()  throws ServletException {
        super.init();
        this.database = new Database(new ConnectionFactory());  // no statics needed!
    }

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session=request.getSession();
     String idPrenotazione = request.getParameter("idPrenotazione");
     String email = request.getParameter("email");
     int typeRoom = Integer.parseInt(request.getParameter("typeRoom"));;
     String arrivalDate = request.getParameter("arrivalDate");
     String departureDate = request.getParameter("departureDate");
     response.setContentType("text/html;charset=UTF-8");
     PrintWriter out = response.getWriter();

    // use the method from `Database` which knows how to query the DB.
    int totalReservations = database.getTotalReservations(typeRoom, arrivalDate, departureDate);

    // more processing... and forward to the JSP
}

請注意, Database現在指的是一個 USERS 表和一個 RESERVATTIONS 表。 最好將它們拆分為單獨的類,例如UsersQueryReservationsQuery 它們都可以共享同一個ConnectionFactory實例。

也可以看看:

  • 單一責任原則
  • 控制反轉(將ConnectionFactory注入Database
  • servlet 生命周期
  • 為什么靜態變量(或單例)是/可能是邪惡的
  • 數據源(而不是低級ConnectionFactory

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM