Partage
  • Partager sur Facebook
  • Partager sur Twitter

Récupération d'une instance dao

    28 février 2021 à 0:25:58

    Bonsoir à tous,

    Je suis en train de développer une application Web en J2EE, et je suis complètement bloquer depuis 3 jours. C'est une bibliothèque en ligne, j'essaie simplement d'ajouter des livres via un formulaire mais je n'arrive pas à récupérer mon bean AuthorForm dans ma servlet. Je ne sais pas si mon problème vient de l'instance dao que j'essaie de récupérer ou non mais je n'ai meme pas de message d'erreur. 

    Servlet

    package controller;
    
    import java.io.IOException;
    import java.util.Map;
    
    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;
    
    import model.AbstractDaoFactory;
    import model.Author;
    import model.dao.interfaces.AuthorDao;
    import model.dao.mysql.MysqlDaoFactory;
    import model.form.AuthorForm;
    
    
    @WebServlet("/AuthorServlet")
    public class AuthorServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    	public static final String ATT_AUTHOR       = "author";
    	public static final String ATT_FORM         = "form";
    	public static final String SESSION_CLIENTS  = "authors";
    	public static final String VUE_SUCCES       = "/WEB-INF/authorsList.jsp";
    	public static final String VUE_FORM         = "/WEB-INF/createAuthor.jsp";
    	private AuthorDao authorDao;
    
    
    
    	    public void init() throws ServletException {
    	        /* Récupération d'une instance */
    	    	MysqlDaoFactory daoFactory = MysqlDaoFactory.getInstance();
    	    	authorDao = daoFactory.getAuthorDao();
    	    	
    	    }
    
       
        public AuthorServlet() {
        }
    
    	
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.getServletContext().getRequestDispatcher( VUE_FORM ).forward( request, response );	}
    
    	
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		
        	AuthorForm form = new AuthorForm(authorDao);
            Author author = form.createAuthor(request);
    
            request.setAttribute( ATT_FORM, form );
            request.setAttribute( ATT_AUTHOR, author );
    
            if ( form.getErrors().isEmpty() ) {
                this.getServletContext().getRequestDispatcher( VUE_SUCCES ).forward( request, response );
            } else {
                this.getServletContext().getRequestDispatcher( VUE_FORM ).forward( request, response );
            }
        }
    }
    
    
    AbstractDaoFactory
    package model;
    
    import java.sql.Connection;
    
    import model.dao.interfaces.AuthorDao;
    import model.dao.interfaces.BookDao;
    import model.dao.interfaces.CategoryDao;
    import model.dao.interfaces.ExemplaireDao;
    import model.dao.interfaces.LanguageDao;
    import model.dao.interfaces.UserDao;
    
    public abstract class AbstractDaoFactory {
    
    	private static AbstractDaoFactory factory;
    	   
        public static AbstractDaoFactory getFactory(){
            return factory;
        }
        
        public static void setFactory(AbstractDaoFactory factory) {
        	
        	AbstractDaoFactory.factory = factory;
        }
        
        
        public abstract Connection getConnection();
        public abstract BookDao createBookDao();
        public abstract UserDao createUserDao();
        public abstract CategoryDao createCategoryDao();
        public abstract AuthorDao createAuthorDao();
        public abstract LanguageDao createLanguageDao();
        public abstract ExemplaireDao createExemplaireDao();
    }
    

    Bean Author

    package model;
    
    import model.dao.interfaces.AuthorDao;
    
    public class Author {
    	
    	private int idAuthor;
    	private String firstName;
    	private String lastName;
    	
    	public Author(int idAuthor, String firstName, String lastName) {
    		
    		this.idAuthor = idAuthor;
    		this.firstName = firstName;
    		this.lastName = lastName;
    		
    	}
    
    	public Author() {
    	}
    
    	public int getIdAuthor() {
    		return idAuthor;
    	}
    
    	public void setIdAuthor(int idAuthor) {
    		this.idAuthor = idAuthor;
    	}
    
    	public String getFirstName() {
    		return firstName;
    	}
    
    	public void setFirstName(String firstName) {
    		this.firstName = firstName;
    	}
    
    	public String getLastName() {
    		return lastName;
    	}
    
    	public void setLastName(String lastName) {
    		this.lastName = lastName;
    	}
    	
    	public Author findById(int id) {
    		AbstractDaoFactory factory = AbstractDaoFactory.getFactory();
    		AuthorDao authorDao = factory.createAuthorDao();
    		return authorDao.findById(id);
    	}	
    	
    }
    

    Interface

    package model.dao.interfaces;
    
    import java.util.List;
    
    import model.Author;
    
    public interface AuthorDao {
    	
    	String addAuthor(Author author);
    	String updateAuthor(Author author);
    	void deleteAuthor(int idAuthor);
    	List<Author> getAllAuthors();
    	Author findById(int id);
    }
    

    AuthorForm

    package model.form;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    
    import model.Author;
    import model.dao.interfaces.AuthorDao;
    
    public class AuthorForm {
    	
    	private static final String CHAMP_PRENOM 	  = "firstName";
    	private static final String CHAMP_NOM		  = "lastName";
    
    	private String result;
    	private AuthorDao authorDao;
    	
    	private Map<String, String> errors = new HashMap<String,String>();
    	
    	public Map<String,String> getErrors(){
    		return errors;	
    	}
    	
    	public String getResult(){
    		return result;	
    	}
    	public AuthorForm(AuthorDao authorDao) {
    		this.authorDao = authorDao;
    	}
    
    	public AuthorForm() {
    		// TODO Auto-generated constructor stub
    	}
    
    	public Author createAuthor(HttpServletRequest request) {
    		String firstName = getFieldValue(request, CHAMP_PRENOM);
    		String lastName = getFieldValue(request, CHAMP_NOM);
    		Author author = new Author();
    		
    		treatFirstName(firstName, author);
    		treatLastName(lastName, author);
    		
                if ( errors.isEmpty() ) {
                    authorDao.addAuthor(author);
                    result = "Succès de la création de l'auteur.";
                } else {
                    result = "Échec de la création de l'auteur.";
                }
    		
    
            return author;
        }
    
    
    	private void treatLastName(String lastName, Author author) {
    		try {
    			validLastName(lastName);
    		}catch (Exception e) {
    			setError( CHAMP_NOM, e.getMessage());
    		}
    		author.setLastName(lastName);
    		
    	}
    
    	private void treatFirstName(String firstName, Author author) {
    		try {
    			validFirstName(firstName);
    		}catch (Exception e) {
    			setError( CHAMP_PRENOM, e.getMessage());
    		}
    		author.setFirstName(firstName);
    		
    	}
    	private void validLastName(String lastName) throws Exception {
    		if(lastName != null && lastName.length()<2) {
    			throw new Exception("Le nom doit contenir au moins 2 caractères");
    			}
    		}
    	
    	
    
    	private void validFirstName(String firstName) throws Exception {
    		if(firstName != null && firstName.length()<2) {
    			throw new Exception("Le prénom doit contenir au moins 2 caractères");
    			}
    		}
    	
    	private String getFieldValue(HttpServletRequest request, String fieldName) {
    		String value = request.getParameter( fieldName );
            if ( value == null || value.trim().length() == 0 ) {
                return null;
            } else {
                return value;
            }
        }
    	
    	private void setError(String champNom, String message) {
    		errors.put(champNom, message);
    	}
    
    }
    
    package model.dao.mysql;
    
    import java.sql.Connection;
    import java.sql.SQLException;
    
    import model.AbstractDaoFactory;
    import model.dao.interfaces.AuthorDao;
    import model.dao.interfaces.BookDao;
    import model.dao.interfaces.CategoryDao;
    import model.dao.interfaces.ExemplaireDao;
    import model.dao.interfaces.LanguageDao;
    import model.dao.interfaces.UserDao;
    
    public class MysqlDaoFactory extends AbstractDaoFactory{
    
    	
        private static MysqlDaoFactory instance;
        private MysqlDaoFactory(){};
        
        public static MysqlDaoFactory getInstance(){
            if(instance == null)
                instance = new MysqlDaoFactory();
            return instance;
        }
        
        @Override
        public Connection getConnection(){
            Connection c = null;
            try {
                c = MysqlConnectionFactory.getConnection(); 
            } catch (SQLException ex) {
                System.out.println("Error>> Driver non installer"+ex.getMessage());
            } 
            return c;
        } 
    
    	@Override
    	public BookDao createBookDao() {
    		return BookDaoImpl.getInstance();
    				
    	}
    
    	@Override
    	public UserDao createUserDao() {
    		return UserDaoImpl.getInstance();
    	}
    
    	@Override
    	public CategoryDao createCategoryDao() {
    		return CategoryDaoImpl.getInstance();
    	}
    
     
    	
    	@Override
    	public AuthorDao createAuthorDao() {
    		return AuthorDaoImpl.getInstance();
    	}
    	
    	@Override
    	public LanguageDao createLanguageDao() {
    		return LanguageDaoImpl.getInstance();
    	}
    
    	 public CategoryDao getCategoryDao() {
    		  return new CategoryDaoImpl( this );
    		  
    	  }
    	 public AuthorDao getAuthorDao() {
    		  return new AuthorDaoImpl( this );
    		  
    	  }
    	 public LanguageDao getLanguageDao() {
    		  return new LanguageDaoImpl( this );
    		  
    	  }
    	 public UserDao getUserDao() {
    		 return new UserDaoImpl(this);
    	 }
    
    	@Override
    	public ExemplaireDao createExemplaireDao() {
    		return new ExemplaireDaoImpl(this);
    	}
    	
    }
    

    Désolé j'ai mis un peu trop de code mais c'est pour que ce soit compréhensible.

    Merci d'avance pour vos réponses




    • Partager sur Facebook
    • Partager sur Twitter
      1 mars 2021 à 18:37:37

      Et lorsque je change le contenu de la methode init();

        public void init() throws ServletException {
      	        /* Récupération d'une instance */
      	    	this.authorDao = ((MysqlDaoFactory)getServletContext().getAttribute(DAO_FACTORY)).getAuthorDao();   	
      	    }


      J'obtiens le message d'erreur suivant : 

      Type Rapport d'exception
      
      message "Servlet.init()" pour la servlet [controller.AuthorServlet] a généré une exception
      
      description Le serveur a rencontré une erreur interne qui l'a empêché de satisfaire la requête.
      
      exception
      javax.servlet.ServletException: "Servlet.init()" pour la servlet [controller.AuthorServlet] a généré une exception
      	org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
      	org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
      	org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
      	org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
      	org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
      	org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
      	org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770)
      	org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
      	org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
      	java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
      	java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
      	org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      	java.base/java.lang.Thread.run(Thread.java:832)
      
      
      cause mère
      java.lang.NullPointerException: Cannot invoke "model.dao.mysql.MysqlDaoFactory.getAuthorDao()" because the return value of "javax.servlet.ServletContext.getAttribute(String)" is null
      	controller.AuthorServlet.init(AuthorServlet.java:34)
      	javax.servlet.GenericServlet.init(GenericServlet.java:158)
      	org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
      	org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
      	org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
      	org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
      	org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
      	org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
      	org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:770)
      	org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
      	org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
      	java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
      	java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
      	org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
      	java.base/java.lang.Thread.run(Thread.java:832)
      
      



      • Partager sur Facebook
      • Partager sur Twitter
        8 mars 2021 à 13:10:07

        Auriez-vous une idée svp?
        • Partager sur Facebook
        • Partager sur Twitter

        Récupération d'une instance dao

        × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
        • Editeur
        • Markdown