Application de gestion des etudiants ب jsf الجزء الثاني

imadbelasri Java
JA

فهاد الجزء الثاني من Application de gestion des etudiants  ب jsf غادي نكملوا الملفات لي بقاونا ولي غادي يكونوا فيهم لفورم لي كيمكنوا من إضافة و تعديل الطلاب بالإضافة للصفحة الرئيسية لي غادي نسترجعوا فيها الطلاب وغادي نعرضهم فيها.


نظرة سريعة بالفيديو


1- الملف StudentController.java

فنفس المجلد لي هو
 Java Resources->src
كانزيد ملف جديد كنسميه StudentController.java فيه كن instancier l'objet من la classe StudentDb باش كندير la connexion مع la base منبعد عندي ل fonction getStudents  لي كنسترجع بها الطلاب لي غادي يكونوا ف List  منبعد عندي loadStud لي كنسترجع بها الطلاب وكنزيدهم ف List students من بعد عندي addStd لي كتزيد طالب فقاعدة البيانات من بعد مكنستقبلوه من الفورم لي غادي نزيدو من بعد ثم loadStd لي كنسترجع بها طالب بل id ديالو من بعد كنزيدو ف session باش كنخدم به فال update form ثم كاين studentUpdate  لي كتعدل المعلومات ديال طالب فقاعدة البيانات من بعد مكنستقبلوه من الفورم لي غادي نزيدو من بعد ثم كاين deleteStd لي كتمسح طالب اختارو المستخدم بل id ديالو وهاد les fonctions لي كانديرو بهم هاد les opérations كلهم راه سبقنا شفناهم ف StudentDb.java هنا غير كانعاودوا نعيطولهم  الكود ديال الملف هو:

                                                    
                                                        package com.darija.coding.jsf.jdbc;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class StudentController {

	private List<Student> students;
	private StudentDb studentDatabase;
	private Logger logger = Logger.getLogger(getClass().getName());
	
	public StudentController() throws Exception {
		students = new ArrayList<>();
		studentDatabase = StudentDb.getInstance();
	}
	public List<Student> getStudents() {
		return students;
	}

	public void loadStud() {
		students.clear();
		try {
			// get all students from database
			students = studentDatabase.getStd();
		} catch (Exception exc) {
			// send this to server logs
			logger.log(Level.SEVERE, "Erreur", exc);
			// add error message for JSF page
			addErrorMessage(exc);
		}
	}
	public String addStd(Student student) {
		try {
			
			// add student to the database
			studentDatabase.addStu(student);
			
		} catch (Exception exc) {
			// send this to server logs
			logger.log(Level.SEVERE, "Error adding students", exc);
			// add error message for JSF page
			addErrorMessage(exc);
			return null;
		}
		return "list-students?faces-redirect=true";
	}
    public String loadStd(int id) {
		try {
			// get student from database
			Student studentFound = studentDatabase.getStu(id);
			// put in the request attribute ... so we can use it on the form page
			ExternalContext externalContext = 
						FacesContext.getCurrentInstance().getExternalContext();		
			Map<String, Object> requestMap = externalContext.getRequestMap();
			requestMap.put("student",studentFound);	
			System.out.println(requestMap.toString());
		} catch (Exception exc) {
			// send this to server logs
			logger.log(Level.SEVERE, "Etudiant introuvable avec l'id suivant :" + id, exc);
			// add error message for JSF page
			addErrorMessage(exc);
			return null;
		}
				
		return "update-student.xhtml";
	}	
	
	public String studentUpdate (Student student) {
		try {
			// update student in the database
			studentDatabase.updateStu(student);
			System.out.println(student.toString());
		} catch (Exception exc) {
			// send this to server logs
			logger.log(Level.SEVERE, "Erreur modification impossible pour : " + student, exc);
			// add error message for JSF page
			addErrorMessage(exc);
			return null;
		}
		
		return "list-students?faces-redirect=true";		
	}
	public String deleteStd(int id) {
		try {
			// update student in the database
			studentDatabase.deleteStu(id);
		} catch (Exception exc) {
			// send this to server logs
			logger.log(Level.SEVERE, "Erreur suppression impossible pour : " + id, exc);
			// add error message for JSF page
			addErrorMessage(exc);
			return null;
		}
		return "list-students?faces-redirect=true";		
	}
	private void addErrorMessage(Exception exc) {
		FacesMessage message = new FacesMessage("Erreur: " + exc.getMessage());
		FacesContext.getCurrentInstance().addMessage(null, message);
	}
	
}

                                                    
                                                

2- الملف add-student.xhtml

غادي تزيد ملف جديد غادي دير click ب droit ديال la souris على WebContent منبعد new منبعد اختار HTML file سميه add-student.xhtml منبعد اختار
New Facelet Template
منبعد ميتزاد امسح الكود لي فيه وغادي نزيدو فيه كود جديد كيربط ل app ب bootstrap منبعد عندي الفورم ديالي فالفرق بين structure jsf وstructure html كنزيد فقط :h فكل tag فكنفتح الفورم منبعد كنزيد inputText كنعطيها الvalue ديال student.nom لي عندي فل class student ولي jsf اوتوماتيكيا كتخدم ب setNom باش كت créer objet جديد من la classe Student وكتعطيه الإسم لي دخل المستخدم فالفورم ونفس الشي بالنسبة للحقول الأخرى ثم كاين ميساج لي كيتعرض يلا كان الحقل خاوي منبعد عندي ال bouton لي ملي كنكليكي عليها كتنفد ل fonction addStd وكنعطيها student لي غادي يتزاد وفالأخير عندي رابط كيردني للصفحة الرئيسية الكود ديال الملف هو:

                                                        
                                                            <!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://xmlns.jcp.org/jsf/html"
	xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
	<title>Ajouter un etudiant</title>
</h:head>
<h:body>
	<div style="padding:10px;">
		<h2 class="text-info">Exemple Université</h2>
		<hr></hr>
	</div>
	<div class="container">
	    <div class="row" style="margin-top:10px;">
		    <div class="col-md-6 col-md-offset-3">
			    <div class="panel panel-default" >
					<h3 class="text-info text-center">Ajouter un etudiant</h3>
					<hr></hr>
					<h:messages globalOnly="true" />
					<h:form id="form" style="margin-top: 10px;padding:20px;" >
						<h:outputLabel>Nom:</h:outputLabel> <h:inputText value="#{student.nom}" id="nom" required="true" class="form-control"/> 
						<h:message for="nom" class="text-danger" />
						<br></br>
						<h:outputLabel>Prénom:</h:outputLabel> <h:inputText value="#{student.prenom}" id="prenom" required="true" class="form-control"/> 
						<h:message for="prenom" class="text-danger"  />
					    <br></br>
						<h:outputLabel>Filiére:</h:outputLabel> <h:inputText value="#{student.filiere}" id="filiere" class="form-control"
											required="true"
		            	/> 	<h:message class="text-danger" for="filiere" />
                        <br></br>
                        <h:commandButton value="Enregister" class="btn btn-success" style="margin-top:10px;" action="#{studentController.addStd(student)}"/>
					</h:form>
					<p class="lead"><h:outputLink value="list-students.xhtml" class="btn btn-link">Retour</h:outputLink></p>
			    </div>
			  </div>
         </div>
	</div>	
</h:body>
</html>

                                                        
                                                    

2- الملف list-student.xhtml

دائما ف WebContent غادي نزيد ملف جديد سميه 
list-student.xhtml هادا هو الصفحة الرئيسية ديالنا لي فيها les etudiants ديالنا معروضين فجدول فأول حاجة كن executer ل fonction loadStud لي كنسترجع بها les etudiants كاملين ملي كتشارجا la page ديالنا من بعد عندي dataTable لي هي table ف jsf وكنعطيها فل value students لي كنسترجعهم من List لي عندي ف studentController منبعد كنعرضهم فالجدول فهنا خدمنا بنفس خدمة foreach لي كانديرو ف php منبعد عندي روابط التعديل والحدف ملي كنكليكي على modifier كي executer ل fonction loadStd لي كتسترجع ل etudiant بل id ديالو وكتصيفطونا لل update form وملي كنكليكي على supprimer كيتحدف etudiant من بعد مكتنفد ل fonction deleteStd لي كتاخد ل id ديال ل etudiant لي اختارينا الكود ديال الملف هو : 

                                                        
                                                            <!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://xmlns.jcp.org/jsf/html"
	xmlns:f="http://xmlns.jcp.org/jsf/core">
<!-- equivalent au onload  -->
<f:metadata>
  <f:event type="preRenderView" listener="#{studentController.loadStud()}"/>
</f:metadata>
<h:head>
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
	<title>Gestion Etudiants</title>
	
</h:head>
<h:body>
	<div style="padding:10px;">
		<h2 class="text-info">Exemple Université</h2>
		<hr></hr>
	</div>
	<div id="container">
		<div style="padding:10px;">
			<h:messages globalOnly="true" />
		       <h:button value="Ajouter un etudiant" class="btn btn-primary" outcome="add-student"/>	
		    <hr></hr>
			<h:form  style="padding-left:100px;padding-right:100px;">		
				<h:dataTable value="#{studentController.students}" var="foundStd"
					class="table" style="padding:20px">
					<h:column>
						<!-- the column header -->
						<f:facet name="header">Nom:</f:facet>
						<!--  the value for each row -->
						#{foundStd.nom}
					</h:column>
					<h:column>
						<!-- the column header -->
						<f:facet name="header">Prénom:</f:facet>
						<!--  the value for each row -->
						#{foundStd.prenom}
					</h:column>
					<h:column>
						<!-- the column header -->
						<f:facet name="header">Filiére</f:facet>
						<!--  the value for each row -->
						#{foundStd.filiere}
					</h:column>
	                <h:column>
						<!-- the column header -->
						<f:facet name="header">Action</f:facet>
						<!--  the value for each row -->
						<h:commandLink value="Modifier" class="text-warning"
							action="#{studentController.loadStd(foundStd.id)}"/>
							|
						<h:commandLink value="Supprimer"
							action="#{studentController.deleteStd(foundStd.id)}" class="text-danger"/>
					</h:column>
				</h:dataTable>
			</h:form>
		</div>
	</div>
</h:body>
</html>

                                                        
                                                    

4- الملف update-student.xhtml

دائما ف WebContent غادي تزيد ملف جديد غادي دير click ب droit ديال la souris على WebContent منبعد new منبعد اختار HTML file سميه update-student.xhtml منبعد اختار
New Facelet Template
منبعد ميتزاد امسح الكود لي فيه وغادي نزيدو فيه كود جديد كيربط ل app ب bootstrap منبعد عندي الفورم لي كيتعرضوا فيها المعلومات ديال ل etudiant كيف قلنا من قبل وملي كنكليكي على ل bouton كن executer ل fonction studentUpdate لي كتاخد المعلومات الجديدة وكتزيدها فقاعدة البيانات الكود ديال الملف هو:

                                                        
                                                            <!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://xmlns.jcp.org/jsf/html"
	xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

	<title>Modifier un etudiant</title>
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
	
</h:head>

<h:body>
    <div style="padding:10px;">
		<h2 class="text-info">Exemple Université</h2>
		<hr></hr>
	</div>
	<div class="container">
	    <div class="row" style="margin-top:10px;">
		    <div class="col-md-6 col-md-offset-3">
			    <div class="panel panel-default" >
					<h3 class="text-info text-center">Modifier un etudiant</h3>
					<h:messages globalOnly="true" />
					<h:form id="form" style="margin-top: 10px;padding:20px;" >
						<h:outputLabel>Nom:</h:outputLabel> <h:inputText value="#{student.nom}" id="nom" required="true" class="form-control"/> 
						<h:message for="nom" class="text-danger" />
						<br></br>
						<h:outputLabel>Prénom:</h:outputLabel> <h:inputText value="#{student.prenom}" id="prenom" required="true" class="form-control"/> 
						<h:message for="prenom" class="text-danger"  />
					    <br></br>
						<h:outputLabel>Filiére:</h:outputLabel> <h:inputText value="#{student.filiere}" id="filiere" class="form-control"
											required="true"
		            	/> 	<h:message class="text-danger" for="filiere" />
                        <br></br>
                        <h:inputHidden value="#{student.id}" />
                        <h:commandButton value="Enregister" class="btn btn-success" style="margin-top:10px;" action="#{studentController.studentUpdate(student)}"/>
					</h:form>
					<p><h:outputLink value="list-students.xhtml" class="btn btn-link">Retour</h:outputLink></p>
				</div>
		    </div>
		</div>	
	</div>	
</h:body>
</html>