【问题标题】:Get ID from url for sql request in DAO JEE project在 DAO JEE 项目中从 url 获取 sql 请求的 ID
【发布时间】:2018-01-11 17:35:28
【问题描述】:

我今天来这里是因为我有问题。 我正在尝试在 JEE 中为我的应用程序使用 DAO 概念。

问题是使用 DAO 概念对我来说要困难得多。

我尝试显示“站点”列表。 显示列表没问题,工作正常。

但是现在,我想显示同一个列表,其中包含 url 中的一个参数。

例如,我的网址是:http://localhost:8080/secteurs?ID=3

我的 servlet 看起来像这样:

package org.oc.servlets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.oc.beans.InfoSecteur;
import org.oc.beans.InfoSite;
import org.oc.dao.*;

public class Secteur extends HttpServlet {

private InfoSecteurDao infoSecteurDao;

public void init() throws ServletException {
    DaoFactory daoFactory = DaoFactory.getInstance();
    this.infoSecteurDao = daoFactory.getInfoSecteurDao();

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
        ServletException, IOException {

    int site_id = Integer.parseInt(request.getParameter("ID"));
    request.setAttribute("site_id", site_id);
    request.setAttribute("infoSecteurs", infoSecteurDao.lister(site_id));
    this.getServletContext().getRequestDispatcher("/WEB-INF/views/secteurs.jsp").forward(request, response);
}


public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    InfoSecteur infoSecteur = new InfoSecteur();
    infoSecteur.setName(request.getParameter("name"));
    infoSecteur.setSite_id(Integer.parseInt(request.getParameter("site_id")));
    infoSecteur.setDescription(request.getParameter("description"));

    infoSecteurDao.ajouter(infoSecteur);
    String site_id = String.valueOf(Integer.parseInt(request.getParameter("site_id")));
    request.setAttribute("site_id", site_id);
    request.setAttribute("infoSecteurs", infoSecteurDao.lister(Integer.parseInt(site_id)));
    this.getServletContext().getRequestDispatcher("/WEB-INF/views/secteurs.jsp").forward(request, response);

}

}

我的 DAO Impl 如下所示:

package org.oc.dao;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;


import org.oc.beans.InfoSecteur;


public class InfoSecteurDaoImpl implements InfoSecteurDao {
    private DaoFactory daoFactory;

InfoSecteurDaoImpl(DaoFactory daoFactory) {
    this.daoFactory = daoFactory;
}

@Override
public void ajouter(InfoSecteur infoSecteur) {
    Connection connexion = null;
    PreparedStatement preparedStatement = null;

    try {
        connexion = daoFactory.getConnection();

        preparedStatement = connexion.prepareStatement("INSERT INTO sector( name, description, site_id) VALUES(?, ?, ?);");
        preparedStatement.setString(1, infoSecteur.getName());
        preparedStatement.setString(2, infoSecteur.getDescription());
        preparedStatement.setInt(3, Integer.parseInt(String.valueOf(infoSecteur.getSite_id())));

        preparedStatement.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

@Override
public List<InfoSecteur> lister(int siteID) {
    List<InfoSecteur> infoSecteurs = new ArrayList<InfoSecteur>();
    Connection connexion = null;
    PreparedStatement ps = null;
    ResultSet resultat = null;

    try {
        connexion = daoFactory.getConnection();
        ps = connexion.prepareStatement("SELECT name, description, site_id FROM sector WHERE site_id=?");
        ps.setString(1, String.valueOf(siteID));

        while (resultat.next()) {

            String name = resultat.getString("name");
            String description = resultat.getString("description");
            int site_id = resultat.getInt("site_id");


            InfoSecteur infoSecteur = new InfoSecteur();
            infoSecteur.setName(name);
            infoSecteur.setDescription(description);
            infoSecteur.setSite_id(Integer.parseInt(String.valueOf(site_id)));


            infoSecteurs.add(infoSecteur);

        }
    } catch (SQLException e) {
        e.printStackTrace();
    } return infoSecteurs;

}


}

我只需要一件事,获取 url 的参数 id=3,并将其放在我的 sql 查询选择中,以仅获取数据库中 site_id=3 的站点。 请不要在这里向我发送 tuto 或其他答案,我花了将近 2 天的时间试图弄清楚,但我没有成功。

非常感谢!

我有这个错误:

exception

java.lang.NullPointerException
org.oc.dao.InfoSecteurDaoImpl.lister(InfoSecteurDaoImpl.java:54)
org.oc.servlets.Secteur.doGet(Secteur.java:42)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

【问题讨论】:

    标签: java sql servlets jakarta-ee dao


    【解决方案1】:

    供您参考,这是我用来解决我的问题的代码(对不起,cmets 是法语,但您只需使用代码即可轻松理解):

    public void ajouter(InfoSecteur infoSecteur) {
        Connection connexion = null;
        PreparedStatement preparedStatement = null;
    
        try {
            connexion = daoFactory.getConnection();
            //On récupère l'objet daoFactory.getConnection(), qui représente la connexion,
            // Ainsi on n'a pas besoin de refaire la connexion systématiquement
            // On récupère la connexion qui a déjà été faite en amont dans la factory
            preparedStatement = connexion.prepareStatement("INSERT INTO sector( name, description, site_id) VALUES(?, ?, ?);");
            preparedStatement.setString(1, infoSecteur.getName());
            preparedStatement.setString(2, infoSecteur.getDescription());
            preparedStatement.setInt(3, infoSecteur.getSite_id());
    
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public List<InfoSecteur> lister(int ID) {
        List<InfoSecteur> infoSecteurs = new ArrayList<InfoSecteur>();
        Connection connexion = null;
        PreparedStatement ps = null;
        ResultSet resultat = null;
    
    
        try {
            connexion = daoFactory.getConnection();
            ps = connexion.prepareStatement("SELECT name, description, site_id, sector_id FROM sector WHERE site_id=?");
            ps.setInt(1, ID);
    
            resultat = ps.executeQuery();
    
    
    
            // Récupération des données
            // On récupère un résultat brut de la bdd difficilement manipulable, donc on en extrait les donnés pour les stocker de manière plus propre et facile à manipuler grace au while
            while (resultat.next()) {
                // on récupère les entrées grace à la méthode getString ou getInt qui permettent de récupérer des données de types string ou int
                //resultat.getString => je m'attends à récupérer une chaine de caractère ou un nombre ou une date etc... puis on les tocke dans des objets de type string, int, etc...
                String name = resultat.getString("name");
                String description = resultat.getString("description");
                int site_id = resultat.getInt("site_id");
                int sector_id =resultat.getInt("sector_id");
    
    
                // On créé un java bean et on lui définit un nom et un prénom correspond à ceux que l'on vient de récupérer dans la bdd
                InfoSecteur infoSecteur = new InfoSecteur();
                infoSecteur.setName(name);
                infoSecteur.setDescription(description);
                infoSecteur.setSite_id(site_id);
                infoSecteur.setSector_id(sector_id);
    
                // on ajoute cet objet à un array (ou liste) grace à la méthode add. on ajout infoSecteur à infoSecteurs
                infoSecteurs.add(infoSecteur);
                // ensuite on boucle encore et encore grace au while jusqu'à tout récupérer
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } return infoSecteurs;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-22
      • 2015-03-13
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多