Untitled - MaurizioCozzetto.it
Transcript
Untitled - MaurizioCozzetto.it
Laboratorio di sistemi JSTL e database Jsp [NetBeans] Elenco dei film ottenuti usando la libreria JSTL 1.1 elenco_film_jstl.pdf Pag. 1/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] Inserisco i dati di un film. Prima dell'inserimento i dati vengono confrontati con quelli della tabella film_tbl database film_db [assumiamo che se genere e titolo coincidono, allora si tratta dello stesso film]. Questo ci consente di evitare il problema del reload della pagina [se l'utente ricarica la pagina premendo il tasto Aggiorna del browser, il controllo su titolo e genere impedisce un nuovo inserimento]. elenco_film_jstl.pdf Pag. 2/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] L'elenco dei film aggiornato elenco_film_jstl.pdf Pag. 3/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] Modifica del titolo di un film [prima della modifica] elenco_film_jstl.pdf Pag. 4/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] Il titolo del film modificato elenco_film_jstl.pdf Pag. 5/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] Vogliamo ora cancellare il record con Id=488. Clicchiamo sul link Cancella. Il record viene eliminato immediatamente. In un applicativo reale, sarebbe preferibile consentire all'utente di confermare o meno l'eliminazione del record [di solito questa funzionalità si implementa scrivendo un po' di codice javascript]. NB I dati relativi alla connessione al db sono memorizzati nel deployment descriptor della web application, il file web.xml, come illustrato più avanti nella sezione “Gestire la connessione” elenco_film_jstl.pdf Pag. 6/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] index.jsp <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h3>Attendi per piacere...ti sto per ridirigerti verso la pagina elenco_film_jstl.jsp</h3> <jsp:forward page="elenco_film_jstl.jsp"/> </body> </html> elenco_film_jstl.jsp <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@page errorPage="errore_jstl.jsp" %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Lista film [JSTL]</title> <style type="text/css"> <!-body,td,th { font-family: Trebuchet MS; font-size: 10pt; } .grassetto { font-weight: bold; } elenco_film_jstl.pdf Pag. 7/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] .rosso { color: red; } --> </style> </head> <body> <h2>Lista film_tbl [JSTL]</h2> <c:if test="${!empty param.message}"> <span class="rosso"><c:out value="${param.message}" /></span> <br/> </c:if> <sql:query var="result" > SELECT * FROM film_tbl ORDER BY genere, titolo </sql:query> Numero di titoli disponibili: <c:out value="${result.rowCount}"/><br/><br/> <table border="0"> <tr> <th>Film ID</th> <th>Titolo</th> <th>Genere</th> <th>Luogo</th> <th>Visualizza</th> </tr> <c:forEach items="${result.rows}" var="row"> <tr> <td><c:out value="${row.film_id}" /></td> <td><c:out value="${row.titolo}" /></td> <td><c:out value="${row.genere}" /></td> <td><c:out value="${row.luogo}" /></td> <td><a href="mod_film_jstl.jsp?id=<c:out value='${row.film_id}' />">Modifica</a></td> <td><a href="can_film_jstl.jsp?id=<c:out value='${row.film_id}' />">Cancella</a></td> </tr> </c:forEach> </table> <br/> <a href="agg_film_jstl.html">Nuovo film</a> </body> </html> elenco_film_jstl.pdf Pag. 8/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] agg_film_jstl.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Inserimento film [JSTL]</title> <style type="text/css"> <!-body,td,th { font-family: Trebuchet MS; font-size: 10pt; } --> </style></head> <body> <h2>Nuovo film [JSTL]</h2> <p> <form name="frmInserisci" method="POST" action="eff_agg_film_jstl.jsp"> Genere: <input type="text" name="txt_genere" value="" /><br/> Titolo: <input type="text" name="txt_titolo" value="" /><br/> <input type="submit" value="Crea" name="btn_inserisci" /> </form> </p> <p> <a href="elenco_film_jstl.jsp">Elenco film</a> </p> </body> </html> eff_agg_film_jstl.jsp <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@page errorPage="errore_jstl.jsp" %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Inserimento di record tabella film_tbl [JSTL]</title> <style type="text/css"> elenco_film_jstl.pdf Pag. 9/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] <!-body,td,th { font-family: Trebuchet MS; font-size: 10pt; } --> </style> </head> <body> <h2>Nuovo film [JSTL]</h2> <c:choose> <c:when test="${empty param.btn_inserisci}"> <jsp:forward page="elenco_film_jstl.jsp"/> </c:when> <c:when test="${empty param.txt_titolo || empty param.txt_genere}"> <jsp:forward page="elenco_film_jstl.jsp?message=I campi titolo e genere non possono essere vuoti."/> </c:when> <c:otherwise> <sql:query var="result"> SELECT * FROM film_tbl WHERE titolo="${param.txt_titolo}" AND genere="${param.txt_genere}" </sql:query> <c:choose> <c:when test="${result.rowCount==1}"> <jsp:forward page="elenco_film_jstl.jsp?message=Record già esistente. L'Id vale ${result.rows[0].film_id}."/> </c:when> <c:otherwise> <sql:update var="result"> INSERT INTO film_tbl(titolo,genere) VALUES ("${param.txt_titolo}","${param.txt_genere}") </sql:update> <c:choose> <c:when test="${result==1}"> <jsp:forward page="elenco_film_jstl.jsp?message=Record registrato correttamente."/> </c:when> elenco_film_jstl.pdf Pag. 10/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] <c:otherwise> <jsp:forward page="elenco_film_jstl.jsp?message=Impossibile registrare il record."/> </c:otherwise> </c:choose> </c:otherwise> </c:choose> </c:otherwise> </c:choose> <p> <a href="elenco_film_jstl.jsp">Elenco film</a> </p> </body> </html> mod_film_jstl.jsp <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@page errorPage="errore_jstl.jsp" %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Modifica film</title> <style type="text/css"> <!-body,td,th { font-family: Trebuchet MS; font-size: 10pt; } --> </style> </head> <body> <h2>Modifica film [JSTL]</h2> <c:choose> <c:when test="${empty param.id}"> <jsp:forward page="elenco_film_jstl.jsp"/> </c:when> elenco_film_jstl.pdf Pag. 11/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] <c:otherwise> <sql:query var="result"> SELECT * FROM film_tbl WHERE film_id=${param.id} </sql:query> <c:choose> <c:when test="${result.rowCount==1}"> <c:set var="row" value="${result.rows[0]}" /> <form name="frm_modif" method="get" action="eff_mod_film_jstl.jsp"> Genere <input name="txt_genere" type="text" id="genere" value='<c:out value="${row.genere}" />' /><br/> Titolo <input name="txt_titolo" type="text" id="titolo" value='<c:out value="${row.titolo}" />' /><br/> <input name="id" type="hidden" id="id" value='<c:out value="${row.film_id}" />' /> <input name="btn_submit" type="submit" value="Salva" </form> </c:when> <c:otherwise> <jsp:forward page="elenco_film_jstl.jsp?message=Impossibile effettuare l'aggiornamento (probabilmente l'id non è valido)."/> </c:otherwise> </c:choose> </c:otherwise> </c:choose> <p> <a href="elenco_film_jstl.jsp">Elenco film</a> </p> </body> </html> eff_mod_film_jstl.jsp <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@page errorPage="errore_jstl.jsp" %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> elenco_film_jstl.pdf Pag. 12/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Modifica film [JSTL]</title> <style type="text/css"> <!-body,td,th { font-family: Trebuchet MS; font-size: 10pt; } --> </style> </head> <body> <h2>Modifica film [JSTL]</h2> <c:choose> <c:when test="${empty param.btn_submit}"> <jsp:forward page="elenco_film_jstl.jsp"/> </c:when> <c:otherwise> <sql:update var="result"> UPDATE film_tbl SET genere="${param.txt_genere}", titolo="${param.txt_titolo}" WHERE film_id=${param.id} </sql:update> <c:choose> <c:when test="${result==1}"> <jsp:forward page="elenco_film_jstl.jsp?message=Aggiornamento riuscito."/> </c:when> <c:otherwise> <jsp:forward page="elenco_film_jstl.jsp?message=Aggiornamento non riuscito o querystring non valida."/> </c:otherwise> </c:choose> </c:otherwise> </c:choose> <p> <a href="elenco_film_jstl.jsp">Elenco film</a> </p> </body> </html> elenco_film_jstl.pdf Pag. 13/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] can_film_jstl.jsp <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@page errorPage="errore_jstl.jsp" %> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Cancella film [JSTL]</title> <style type="text/css"> <!-body,td,th { font-family: Trebuchet MS; font-size: 10pt; } --> </style> </head> <body> <h2>Cancella film [JSTL]</h2> <c:choose> <c:when test="${empty param.id}"> <jsp:forward page="elenco_film_jstl.jsp"/> </c:when> <c:otherwise> <sql:update var="result"> DELETE FROM film_tbl WHERE film_id=${param.id} </sql:update> <c:choose> <c:when test="${result==1}"> <jsp:forward page="elenco_film_jstl.jsp?message=Cancellazione riuscita."/> </c:when> <c:otherwise> <jsp:forward page="elenco_film_jstl.jsp?message=Attenzione! Id non valido."/> elenco_film_jstl.pdf Pag. 14/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] </c:otherwise> </c:choose> </c:otherwise> </c:choose> <p> <a href="elenco_film_jstl.jsp">Elenco film</a> </p> </body> </html> errore_jstl.jsp <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <%@page isErrorPage="true"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSTL, gestione degli errori</title> <style type="text/css"> <!-body,td,th { font-family: Trebuchet MS; font-size: 10pt; } --> </style> </head> <body> <h2>Pagina di gestione degli errori [JSTL]</h2> Si è verificato il seguente errore: <c:out value="${pageContext.exception.message}" /> </body> </html> elenco_film_jstl.pdf Pag. 15/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] Gestire la connessione Per testare rapidamente il prototipo di una web application che fa uso, come in questo caso, di un database MySQL, possiamo provare a inserire nella pagina web il seguente codice: <sql:setDataSource driver="com.mysql.jdbc.Driver" url=" jdbc:mysql://localhost:3306/film_db" user="root" password="" /> Tuttavia la presenza nella pagina web di username e password in chiaro [in questo caso manca la password, dal momento che solitamente sviluppiamo usando Xampp] espone il sistema a possibili violazioni del codice. Si possono allora seguire 3 diverse strade per accedere alla base dati con una ragionevole sicurezza. Tecnica n. 1 La prima consiste nel fare ricorso ad un file di properties [config.db] da inserire nella cartella WEB-INF [che risulta protetta]. Il file di properties è così strutturato: driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/film_db user=root password= Carichiamo in memoria il file config.db mediante il seguente codice: <%! java.util.Properties p = new java.util.Properties(); public void init() { try { p.load(getServletConfig().getServletContext().getResourceAsStream("/WEBINF/config.db")); } catch (java.io.IOException e) { e.printStackTrace(); } } %> Modifichiamo poi l’istruzione di connessione ad database mediante il seguente codice: <sql:setDataSource driver="<%=p.getProperty("driver")%>" url="<%=p.getProperty("url")%>" user="<%=p.getProperty("user")%>" password="<%=p.getProperty("password")%>" /> Il resto del codice è immutato. Tecnica n. 2 La seconda tecnica consiste nel settare i parametri all’interno del file web.xml, detto deployment descriptor, aggiungendo le seguenti righe: elenco_film_jstl.pdf Pag. 16/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] <context-param> <param-name>driver</param-name> <param-value>com.mysql.jdbc.Driver</param-value> </context-param> <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/film_db</param-value> </context-param> <context-param> <param-name>user</param-name> <param-value>root</param-value> </context-param> <context-param> <param-name>password</param-name> <param-value></param-value> </context-param> Per estrarre questi parametri [detti parametri di contesto], utilizziamo il seguente codice: <% //leggo le informazioni dal file web.xml String driver=application.getInitParameter("driver"); String url=application.getInitParameter("url"); String user=application.getInitParameter("user"); String password=application.getInitParameter("password"); %> A questo punto è facile riscrivere l’istruzione di connessione al database. <sql:setDataSource driver="<%=driver%>" url="<%=url%>" user="<%=user%>" password="<%=password%>" /> elenco_film_jstl.pdf Pag. 17/18 Cozzetto © Laboratorio di sistemi JSTL e database Jsp [NetBeans] Tecnica n. 3 Possiamo in alternativa impostare [è il caso del nostro applicativo] i parametri della connessione all'interno del file web.xml in questo modo: web.xml <web-app> … <context-param> <param-name> javax.servlet.jsp.jstl.sql.dataSource </param-name> <param-value> jdbc:mysql://localhost:3306/film_db,com.mysql.jdbc.Driver,root, (nel caso di driver Jdbc-Odbc, scriviamo jdbc:odbc:film_db,sun.jdbc.odbc.JdbcOdbcDriver,root, dove film_db è il nome del DSN creato sulla macchina) </param-value> </context-param> … </web-app> In questa situazione, non è più necessario richiamare i parametri mediante codice. Soluzioni più affidabili consistono nel definire un pool di connessioni e di far uso di una tecnologia denominata JNDI, disponibile nei più moderni servlet container e application server (Tomcat,Resin, Bea WebLogic ecc). Rimandiamo l’argomento ad un prossimo articolo. elenco_film_jstl.pdf Pag. 18/18 Cozzetto ©