Ich habe gerade das SpringMVC -Framework in letzter Zeit gelernt und es hat das Gefühl, dass es in der Tat viel bequemer ist und viel redundanter Code reduziert. Ich habe ein kleines Projekt zum Üben gemacht. Dies ist ein grundlegendes SpringMVC -Anwendungsprojekt. MyBatis wird nicht verwendet. Die Projektfunktionen sind ziemlich vollständig und die grundlegenden Funktionen von Addition, Löschung, Änderung und Suche werden realisiert.
Projektumgebung:
-System: Win10
-Developmentumgebung: EclipseoxygenReleaseCandidat3 (4.7)
-jdk Version: Java1.8 (121)
-Mysql: 5.7
-spring: 4.0
-Tomcat: 8.5
Verwendete Techniken:
SPRINGMVCSPRINGJSPJDBCJAVABEANJSJSTL
Zugangsadresse: http: // localhost: 8080/Ihr Projektname/All
Aussage: Ich bin nur ein Anfänger, der gerade angefangen hat, und es gibt unweigerlich alle Fehler in dem Code, den ich geschrieben habe. Wenn Sie es finden, weisen Sie bitte darauf hin. Vielen Dank an alle.
Der detaillierte Prozess ist unten veröffentlicht
1. Erstellen Sie zuerst ein Webprojekt (DynamicWebproject)
Ich habe den Projektnamen selbst geschrieben, nicht mehr detaillierter
2. Dies ist meine abgeschlossene Projektstruktur
Ich habe gerade die Funktion verwendet und die Schnittstelle nicht verwendet. Ich habe nur drei einfache Klassen verwendet, die Entitätsklasse unter dem Bean -Paket, die DAO Layer -Datenbankzugriffsklasse und die Schnittstellensteuerklasse der Controller -Ebene.
Alle referenzierten JAR-Pakete befinden sich im Ordner/webcontent/web-inf/lib, der sich von gewöhnlichen Java-Projekten unterscheidet.
3. spezifischer Java -Code
1.Student -Klasse, Entity -Klasse muss zunächst einen Javabäer schreiben. Meins ist ein Student als Javabäer. Der detaillierte Code lautet wie folgt:
Paket bean; öffentliche Klasse Student {private Integer id; // Student ID Private String Name; // Schülername Private Double Javascore; // Java Score Private Double htmlScore; // HTML Score Private Double CSSScore; // CSS -Score Private Double Totalscore; public Integer getid () {return id; } public void setId (Integer id) {this.id = id; } public String getName () {return name; } public void setName (String -Name) {this.name = name; } public double getJavascore () {return Javascore; } public void setjavascore (Double Javascore) {this.javascore = javascore; } public Double GethtmlScore () {return htmlScore; } public void sethtmlScore (double htmlScore) {this.htmlScore = htmlScore; } public double getCssScore () {return cSSScore; } public void setCSSCORE (double CSSScore) {this.cssscore = CSSScore; } public double gettotalscore () {return sotalscore; } public void settotalscore (double sumalscore) {this.totalscore = sotalscore; }}2. StudentDao, die Datenbankzugriffs -Operation -Klasse ist dann der Code der DAO -Schicht, dh die Datenzugriffsschicht. Hier ist eine Klasse, die von Spring (jdbctemplate) eingekapselt ist und einige Methoden zum Betrieb der Datenbank enthält. Es ist nicht erforderlich, selbst viele wiederholte Code zu schreiben. Schreiben Sie einfach SQL -Anweisungen. Hier ist der spezifische Code:
Paket dao; import Java.sql.resultset; Import Java.sql.sqLexception; import Java.sql.types; Import Java.util.List; StudentDao { / ** * @fields jdbCtemplate: toDo * / private jdbctemplate jdbCtemplate; / ** * Klasse von Spring * * @param jdbCtemplate * Rückgabewerttyp: void * @author janinus */ public void setjdbctemplate (jdbctemplate jdbctemplate) {this.jdbctemplate = jdbctemplate; } / ** * alle Schüler abfragen * * @Return Rückgabewerttyp: List <Student> * @author janinus * / publiclist <Student> queryAll () {String sql = "ID, Name, Javascore, HtmlScore, CSSScore von Student"; // Das Abfrageergebnis in die Schülerklasse abbilden, der Liste hinzufügen und zurückgeben. } / ** * Abfragen nach Namen * * @param name * @return return value type: list <Student> * @author janinus * / publiclist <Student> queryByName (String -Name) {String SQL = "ID, Name, Name, Javascore, htmlscore, csSscore aus student, wob return jdbctemplate.Query (SQL, New StudentMapper ()); } / ** * add Student * * @param student * @return return value type: boolean * @author janinus * / public boolean addstu (student student) {string sql = "in student (id, name, javascore, htmlscore, cssScore) Werte (0,?,? return jdbcTemplate.update(sql, new Object[] { student.getName(), student.getJavaScore(), student.getHtmlScore(), student.getCssScore() }, new int[] { Types.VARCHAR, Types.DOUBLE, Types.DOUBLE, Types.DOUBLE, Types.DOUBLE }) == 1; } / ** * Student löschen * * @param id * @return return value type: boolean * @author janinus * / public boolean deletestu (Integer id) {String SQL = "Von Studenten löschen wobei ID =?"; return jdbctemplate.update (SQL, ID) == 1; } / ** * Aktualisieren Sie Schülerinformationen * * @param student * @return return value type: boolean * @author janinus * / public boolean updatestu (Student Student) {String sql = "update student set name =?, Javascore =?, Htmlscore =? Object stuobj [] = new Object [] {student.getName (), student.getjavascore (), student.gethtmlScore (), student.getCssscore (), student.getId ()}; return jdbctemplate.update (SQL, stuobj) == 1; } / ** * Gibt die Gesamtpunktzahl der Top -N -Schüler zurück * * @param num * @return return value type: list <Student> * @author Janinus * / publiclist <Studenten> topnum (int num) {String sql = "Select id, Name, Name, Javascore+htmlscore+csscore von student by student by Javascore+htmore+csscore von jungen by student by Javascore+htmore+csScore von Javascore (Javascore). return jdbctemplate.Query (SQL, neuer RowMapper <Student> () {@Override Public Student Maprow (Ergebnisset RS, Int Rownum) löst SQLEXception {// todo auto-generierter Methode Stub Student = New Student (); Student.Settotalscore (Rs.GetDouble (3)); } / ** * * studentMapper Datenbankzuordnung * * @classname studentMapper * @author Janinus * @date 27. Juni 2017 * @Version v1.0 * / class studentMapper implements rowmapper <student> {@Override öffentlich student maprow (resultset rs, int strowns throws sqtexextex {// todo {/ todo alko-gern-modi sqthexex {/ todo {/ todo alko-gern Student(); student.setId (rs.getint (1)); student.setName (rs.getString (2)); student.setjavascore (rs.getDouble (3)); student.sethtmlScore (rs.getDouble (4)); student.setcssScore (rs.getDouble (5)); Rückkehrer; }}}3. StudentController, die Front-End-Interaktionsklasse ist schließlich die Steuerungsschicht-StudentController-Klasse im Zusammenhang mit der Benutzerinteraktion. Diese Klasse wird hauptsächlich verwendet, um das Front-End und das Back-End zu kombinieren, um eine vollständige Interaktion zu erzielen. Hier ist der spezifische Code:
Paketcontroller; import org.springframework.context.ApplicationContext; import org.springFramework.context.support.classPathXmlapplicationContext; import org.springframework.stereotype.Controller; org.springframework.web.bind.annotation.RequestMapping;import bean.Student;import dao.StudentDao;@Controllerpublic class StudentController { /** * * Get all student information from the database and return the data to the home page index,jsp * * @param model * @return Return value type: String * @author janinus */ @RequestMapping (value = "/all") public String queryAll (Modellmodell) {applicationContext context = new classPhodexMLApplicationContext ("applicationContext.xml"); // Dao Studentdao dao = (StudentDao) context.getbean ("Dao"); model.addattribute ("Studenten", Dao.Queryall ()); model.addattribute ("tops", dao.topnum (3)); return "index.jsp"; }/** * Finden Sie die Schüler nach Namen, verwenden Sie Fuzzy -Suche und senden Sie das Ergebnis an index.jsp * * @param name * @param modell * @return return value type: string * @author janinus */@RequestMapping (value = "/queryByName") Public String QueryByName (String name, Modellmodell) {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ ClassPathXmlApplicationContext ("ApplicationContext.xml"); // DAO vom IOC Container studentdao dao = (studentdao) context.getbean ("dao") holen; model.addattribute ("Studenten", Dao.QueryByName (Name)); model.addattribute ("tops", dao.topnum (3)); return "index.jsp"; }/** * Fügen Sie einen neuen Schüler hinzu und geben Sie das Ergebnis auf die All -Seite zurück, die von allen an die Homepage weitergeleitet wird htmlScore, String cSSScore, Modellmodell) {applicationContext context = new classMlMlApplicationContext ("applicationContext.xml"); Studentdao dao = (studentdao) context.getbean ("dao"); Student Student = New Student (); Student.SetName (Name); student.setjavascore (double.Parsedouble (Javascore)); student.sethtmlScore (double.ParsedoUble (htmlScore)); student.setCSSScore (double.ParsedoUble (CSSScore)); boolescher Ergebnis = Dao.Addstu (Student); if (result) model.addattribute ("msg", "script> alert ('erfolgreich hinzugefügt!') </script>"); else model.addattribute ("msg", "script> alert ('erfolgreich hinzugefügt!') </script>"); zurück "alles"; }/** * Student nach id * @param id * @param modell * @return return value type: string * @author janinus */@RequestMapping (value = "/deleteById") public String deleteById (String -ID, Modellmodell) {ApplicationContext context = new ClassPhoxmlApplicationConteContextext ("ApplicationContext.xml"). Studentdao dao = (studentdao) context.getbean ("dao"); boolean result = dao.deletestu (Integer.ParseInt (id)); if (result) model.addattribute ("msg", "script> alert ('erfolgreich löschen!') </script>"); else model.addattribute ("msg", "script> alert ('erfolgreich löschen!') </script>"); zurück "alles"; } /** * * @param id * @param name * @param javaScore * @param htmlScore * @param cssScore * @param model * @return Return value type: String * @author janinus */ @RequestMapping(value = "/update") public String updateStu(String id, String name, String javaScore, String htmlScore, String cssScore, Model Modell) {applicationContext context = new classSpathXmlApplicationContext ("ApplicationContext.xml"); Studentdao dao = (studentdao) context.getbean ("dao"); Student Student = New Student (); student.setId (Integer.ParseInt (id)); Student.SetName (Name); student.setjavascore (double.Parsedouble (Javascore)); student.sethtmlScore (double.ParsedoUble (htmlScore)); student.setCSSScore (double.ParsedoUble (CSSScore)); boolean result = dao.updatestu (Student); if (result) model.addattribute ("msg", msg ("erfolgreich modifiziert"); else model.addattribute ("msg", msg ("modification fehlgeschlagen")); zurück "alles"; }/** * Seitennachricht zum Pop -up * @param msg * @return return value type: string * @author janinus */public string msg (string msg) {return "<script> alert ('" + msg + "') </script>"; }}Der gesamte Java-Code wurde abgeschlossen, und nur die spezifische XML-Konfiguration und die Front-End-Seite bleiben unten.
4. Front-End-Seite
Da es sich um ein einfaches kleines Projekt handelt, sind meine JS und CSS alle auf derselben Seite, nicht getrennt, nur zwei Seiten,
1.Index.jsp
Startseite, Screenshot
bearbeiten
Detaillierter Code:
<%@ page Language = "java" contentType = "text/html; charset = utf-8" pageCoding = "utf-8"%> <%@ taglib prefix = "fn" uri = "http://java.sun.com/jsp/jstl/functions"%> <%@java.sun = "c" C. URI = "http://java.sun.com/jsp/jstl/core" %> <! docType html> <html Lang = "en"> <head> <meta charset = "utf-8"> <title> Student Management </title> </head> <style type } .All {width: 40%; Rand: 20px 100px; Text-Align: Mitte; Höhe: 300px; float: links; } Tabelle {Breite: 80%; Rand: 20px Auto; Schriftgröße: 14px; Überlauf: Auto; } #tab02 {Breite: 80%; Rand: 20px Auto; Schriftgröße: 14px; } Tabelle Th, Tabelle TD {Border-Bottom: 1px #000 Solid; Zeilenhöhe: 23px; } #edit_comm {width: 500px; Rand: 20px Auto; Border-Links: 3px fest #000; Anzeige: Keine; } #add_comm {width: 500px; Rand: 20px Auto; Border-Links: 3px fest #000; } #all_comm {Höhe: 600px; } .edit_stu {width: 200px; Höhe: 30px; Hintergrund: #fff; Schriftfamilie: "Microsoft Ya Black Light", "Arial Black"; Schriftgröße: 18px; Grenze: Keine; Grenzboden: 1PX Solid #000; Rand: 20px 10px; · $ ("input"). addClass ("edit_stu"); } Funktion add_reg () {var name = $ ("#add_edit_name"). val (); var javascore = $ ("#add_edit_java"). val (); var htmlScore = $ ("#add_edit_html"). val (); var cssscore = $ ("#add_edit_css"). Val (); var namenot = name! = null && name! = ''; var javascorenot = javascore! = null && javascore! = ''; var htmlscorenot = htmlScore! = null && htmlScore! = ''; var cssscorenot = CSSScore! = NULL && CSSSCORE! = ''; if (namenot & javascorenot && htmlscorenot && cssscorenot) return true; sonst return falsch; } Funktion Delete_stu (id) {var result = bestätigen ("wurde es gelöscht?"); if (result) window.location.href = "deleteById? id =" rel = "external nofollow" +id; } Funktion edit_stu (id) {var name = $ ("#name"+id) .Text (); var java = $ ("#java"+id) .Text (); var html = $ ("#html"+id) .Text (); var CSS = $ ("#CSS"+id) .Text (); $ ("#edit_id"). val (id); $ ("#Edit_Name"). Val (Name); $ ("#edit_java"). Val (Java); $ ("#edit_html"). val (html); $ ("#edit_css"). Val (CSS); $ ("#add_comm"). fadeout (); $ ("#edit_comm"). fadein (); } </script> <body> $ {msg} <h1 align = "center"> Studentenverwaltung </h1> <div id = "All_Comm"> <H2> All Student </H2> <table id = "items"> <tr> <td> id </td> <td> name </td> <td> java -Punktzahl </td> <td> </td> java </td> <td> <Td> CSS -Punktzahl </td> <td> Operation </td> </td> </tr> <c: foreach items = "$ {student <td id = "java $ {student.id}"> $ {student.javascore} </td> <td id = "html $ {student.id}"> $ {student.htmlscore} </td> <td id = "cs onclick="delete_stu(${student.id})">Delete</a>|<a onclick="edit_stu(${student.id})">Edit</a></td> </tr> </c:forEach> </table> <table id="tab02"> <h2>Top three</h2> <tr> <td>Ranking</td> <td> id </td> <td> Name </td> <td> Gesamtpunktzahl </td> </tr> <c: foreach items = "$ {tops}" var = "student" varstatus = "i"> <tr> <td> $ {Idindex+1} Name </td> <td id = "$ $ $ $ $" {{student }. <h2>Find student</h2> <form action="queryByName" method="post" > <input type="text" placeholder="Student name" name="name" > <input type="submit" value="Find student" > </form> <h2 id="edit_title">Add student</h2> <form action="add" method="post" > <input type="text" placeholder="Student name" name="name" /> <input type="text" placeholder="java score" name="javaScore" /> <input type="text" placeholder="html score" name="htmlScore" /> <input type="text" placeholder="css score" name="cssScore" /> <input type="submit" value="Confirm to add" /> </form></div><div id = "edit_comm"> <h2 id = "edit_title"> student bearbeiten </h2> <Formion = "update" method = "post"> <Eingabe type = "text" placeholder = "id zu modifiziert ist" id = "edit_id" name = "id" value = "value". id = "edit_name" name = "name" /> <input type = "text" placeholder = "java Score" id = "edit_java" name = "javascore"> <Eingabe type = "text" placeholder = "html Score" id = "edit_html" name = "htmlscore" /> <input type "tectholder name = "CSSScore"/> <Eingabe type = "sureichen" value = "Modification bestätigen"/> <Eingabe type = "button" value = "Abbrechen Modifikation" id "id" ID "/> </form> </div> </body> </html>2. Login.jsp
<%@ page Language = "java" contentType = "text/html; charset = utf-8" pageCoding = "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>Insert title here</title></head><body><h1 align="center"><a href="all" rel = "externer nofollow" rel = "external nofollow"> Homepage eingeben </a> </h1> </body> </html>
5. Detaillierte Dateikonfiguration
1. ApplicationContext.xml
Dies ist die Konfigurationsdatei des IOC -Containers von Spring, die zur Implementierung der Abhängigkeitsinjektion verwendet wird. Das Folgende ist der spezifische Code:
<? xmlns: context = "http://www.springframework.org/schema/context" xmlns: tx = "http://www.spingframework.org/schema/tx" xmlns: aoop = "http://wwwwww./wwww.Stx XSI: ScheMalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/contex http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd "Default-autowire =" Byname "Default-Lazy-Init =" TRUE "> TRUE" <!-DataBase DataSources DataSources "-DataSource"> <!-DataBase DataSources DataSources "-DataSource"> <! "-DataBase Data-Data-Data-Quelle"-> <"> <!-"-DataBase "-DataSource"> <! "-DataBase DataSources DataSource"-DataSource "> <!-DataBase-Data-Data-Data-Data-Data" -Indatabase-Data "-Indatabase"-> <!--DataBase ". <!-Treiberklasse laden-> <Eigenschaft name = "TRAVERCLASSNAME" value = "com.mysql.jdbc.driver"> </Property> <!-Datenbankzugriffsadresse-> <Eigenschaft name = "url" value = "jdbc: mysql: // localhost: 3306/test" ubmay "> </properien value="root"></property> <!--Database access password--> <property name="password" value="123123"></property> </bean> <!-- Database transaction management provided by spring--> <bean id="txManager"> <property name="dataSource" ref="dataSource"></property> </bean> <tx:annotation-driven transaction-Manager = "TxManager"/> <!-Konfigurieren Sie die Javabäe-Entitätsklasse-> <bean id = "studentbean"> <!-Zuschreibende automatische Konfiguration-> </bean> <!!-Datenbankzugriffs-Operationsklasse, die von Spring-> <bean id = "jdbctemPlate"> </bean> <!-DAHO-LACHE--DAO-DAO-DAO--DAO--DAO--DAO--DAO--DAO--DAO! Klasse, diese Konfiguration ist ungültig-> <bean id = "Controller"> <Eigenschaft name = "dao" ref = "dao"> </property> </bean> </beans>
2. SpringMVC-Service.xml, Spring MVC-Konfigurationsklasse,
Wir haben den größten Teil des Servlet -Code für uns implementiert und müssen nur eine Geschäftsimplementierung schreiben. Unten finden Sie den spezifischen Code
<? xmlns: p = "http://www.springframework.org/schema/p" xmlns: context = "http://www.springframework.org/schema/context" xsi: schemalocation = "http://www.spingframework.org/schema http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/context/sping/sping/sping-context- Scannen Sie die Klasse unter dem angegebenen Paket-> <Kontext: Komponenten-scan-Basis-Package = "Controller" /> < /beans>
A. Web.xml
Dies ist die Konfigurationsdatei des Webprojekts, und das Folgende ist der Hauptcode:
<? XSI: Schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><!-conefigure Charakter-Coding-Filter, die von FRESPRESS-> <Filter> <filters codieren, geliefert von Filter, der von FRESPRAGE-geliefert wurde, geliefert von FRINDE--> <Filter> <filter, geliefert von FRESPERS--< <Filter-name> codierungfilter </filter-name> <filterklasse> org.springFramework Interface-> <Welcome-File-List> <Welcome-File>/All </Welcome-File> <Welcome-File> Index.html </Welcome-File> <Welcome-File> Index.htm </Welcome-File> </Welcome-File-List> <!-Konfigurieren Sie SpringMVC-Servlet-> <Servlet> <Servlet-Name> SpringMVC </Servlet-Name> Servlet-Name> Servlet-name <servlet-classe> org.springFramework.web.servlet.dispatcherServlet </Servlet-Class> <Load-on-Startups> 1 </load-on-Startup> </Servlet> <Servlet-Mapping> <WERNLET-NAME> SpringMVC </servlet-name> <url-patter>/</</</</</</</</</</</</</</</</</</</</</</</</</</</</</</</</</</</</</</</url-pattern>
6. Projektzusammenfassung und Anhang
Dieses Projekt ist mein tägliches Praxisprogramm. Um kompetenter zu sein, habe ich den vollständigen Prozess erneut überprüft und viel damit vertraut.
Anhang zum JAR -Paket, das für das Projekt verwendet wird:
Zusätzlich zum Frühlingspaket gibt es auch MySQL-JBDC JAR-Paket und JSTL JAR-Paket
Adresse herunterladen:
Spring Framework JAR -Paket (optionale Version): Offizielle Spring -Website
MySQL-Jdbc.jar (optionale Version): Mysql Offizielle Website
JSTL.JAR (optionale Version): Maven Offizielle Adresse
Das obige ist der gesamte Inhalt dieses Artikels über das vollständige Beispiel für Spring MVC, die die Addition, Löschung, Änderung und Suche in der MySQL -Datenbank implementiert. Ich hoffe, es wird für alle hilfreich sein. Interessierte Freunde können weiterhin auf diese Seite verweisen:
Detaillierte Erläuterung der Konfiguration des Webmoduls im Frühjahr
SpringMVC REST STYLE EINLEITUNG UND Implementierungscode Beispiel
SpringMVC Interceptor implementiert einzelne Anmelde
Wenn es Mängel gibt, hinterlassen Sie bitte eine Nachricht, um darauf hinzuweisen. Vielen Dank an Freunde für Ihre Unterstützung für diese Seite!