Préface
Aujourd'hui, je vais passer en revue la construction de SpringMVC + Hibernate. Je pensais à l'origine que le cadre de contrôle des autorisations de Spring-Sécurité y sera également inclus, mais j'ai trouvé qu'il y avait trop de contenu. Laissons le prochain article. Cet article construit principalement Springmvc4.1.4 et Hibernate4.3.8. J'ai également utilisé beaucoup de SpringMVC auparavant. Cette partie le connaît très bien. Après tout, SpringMVC est développé depuis plus d'un an. Cette fois, la couche de persistance utilise Hibernate, la source de données utilise C3P0 et la base de données utilise temporairement MySQL. Je veux principalement revoir Hibernate. L'idée de construire le cadre de SpringMVC + Hibernate est la suivante:
1. Conception de la base de données: concevez la structure de la table, il est préférable de rencontrer 3NF et d'utiliser des outils Hibernate pour générer automatiquement l'entité d'entité correspondante.
1. Créez un projet Maven et entrez les dépendances du package Maven selon les besoins.
2. Bâtier le ressort: configurer l'injection de ressort de haricots de couche de commande.
3. Créez HiberNate: configurer les sources de données, configurer SessionFactory, configurer les transactions et configurer le cache secondaire ehcache.
4. Testez la construction du cadre de Spring + Hibernate, Write Unit Test Junit, Test Transaction Configuration, etc.
5. Entrée Springmvc: configurer les informations de configuration de SpringMVC.
6. Configurer le conteneur web.xml
7. Testez l'intégration de trois cadres: Maven compile, packages et déploie des serveurs et des tests.
1. Conception de la base de données
Concevez un tableau des autorisations, des rôles et des utilisateurs. Bien sûr, si un utilisateur peut avoir plusieurs rôles, un rôle possède plusieurs utilisateurs; Un rôle a plusieurs autorisations et une autorisation correspond à plusieurs rôles. Par conséquent, selon la conception de la structure de la table de base de données, si elle rencontre le 3NF, nous avons besoin de 5 tables pour exister. Les informations spécifiques de la table ne sont pas répertoriées (vous pouvez les télécharger dans le code source, et il y a aussi une base de données), et la relation du tableau est la suivante:
Ce n'est que dans cet ID utilisé par l'UUID (36 bits)
2. Créez un projet Maven et écrivez un fichier pom.xml
Créez un projet Maven WebApp, écrivez un fichier pom.xml et introduisez les dépendances de package requises. Je vais cartographier tous les obligatoires ici.
Le contenu du fichier pom.xml est le suivant:
<project xmlns = "http://maven.apache.org/pom/4.0.0" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalation = "http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd "> <ModelVersion> 4.0.0 </ Modelversion> <ProupID> org.andy.sh </proncId> <ArtifActid> Springmvc_hibernate_Demo </ptifactid> <packaging> war </packaging> <name> springmvc_hibernate_demo maven webapp </name> <url> http://maven.apache.org </url> </projet.build.build.sourceending> utf-8 </project.build.sourceension> <printemps> 4.1.4. <hibernate.version> 4.3.8.final </hibernate.version> <jackson.version> 2.5.0 </jackson.version> </properties> <dépendances> <! - Junit -> <dependency> <proupId> junit </proupId> <Artifactid> Junit </rtifactive> <version> 4.12 </Derson> <De version> <! - Spring -> <Dedency> <GroupId> org.springFramework </rom grouped> <ArtifActid> printemps-core </ artifactid> <version> $ {printemps.version} </-version> </pedency> <dependency> <proupId> org.springframework </proupId> <ArtifActid> Spring Beans </trifactid> <version> $ {printemps.version} </ version> </dependency> <dependency> <proupId> org.springFramework </proupId> <ArtifActid> Spring-Context </ ArtifactId> <De version> $ {Spring.Version} </ version> </ Dependency> <Dedidency> <ProupId> ORG.SPRINGFRAMEWRAWNWORK </ GroupId> <ArtefactId> Spring-Tx </ ArfactId> <Dersion> $ {printemps.version} </ version> </ Dependency> <Dedency> <ProupId> org.springFramework </proupId> <ArtefactId> Spring-Web </ ArtifactId> <Desentency> $ {printemps.version} </ version> </pedency> <dependency> <GroupId> org.springFramework </proncId> <Artifactid> Spring-test </lefactive> <in version> $ {printemps.version} </-version> <ccope> Test </cope> </Dedency> <! - Configuration avec Springmvc -> <Dedency> <ProupId> Org.SpringFramework </proupId> <ArtefactId> printemps-webmvc </ artifactid> <version> $ {printemps.version} </-version> </dependency> <! - Lors de l'intégration d'une base de données relationnelle, vous devez configurer comme Hibernate JPA. -> <dependency> <proupId> org.springframework </rombasid> <ErtingActid> printemps-normal </ artifactid> <version> $ {printemps.Version} </ version> </Dependency> <! - HiberNate -> <Dependency> <proupId> org.hibernate </proupId> <ArtifActid> Hibernate-Core </ ArfactId> <version> $ {hibernate.version} </ version> </dependency> <dependency> <proupId> org.hibernate </rombasid> <artifactId> hibernate-ehcache </ artifactid> <version> $ {Hibernate.version} </Derence> </Dedency> <! - Secondary Cache ehcache -> <fedency> <GroupId> net.sf.ehcache </proupId> <Artifactid> ehcache </artifactid> <version> 2.9.0 </ version> </pedigency> <! - Log4j -> <dependency> <proupId> LOG4J </rom grouped> <eRtifActid> Log4j </Rifactid> <version> 1.2.17 </Dero version> </Dedency> <Dependance> <GroupId> MySQL </rom grouped> <ArtifActid> MySQL-Connector-Java </Retifactid> <DERVIÈRE> 5.1.34 </ Version> </Dependency> <! - C3P0 Data Source -> <Dedency> <proupId> com.mchange </prouprid> <ArtifactId> C3P0 </rtificd> </Dependency> <! - JSON -> <Dedency> <ProupId> com.alibaba </proncId> <ArtifActid> FastJson </ ArtifactId> <DERVERSE> 1.2.3 </DERNIFRIENCE> </DENDENCENCE> <DENSEDENCY> <ProupID> com.fasterxml.jackson.core </proupId> <ArtifActid> jackson-Annotingations </ ArfactId> <version> $ {jackson.version} </ version> </ dépendance> <dependency> <proupId> com.fasterxml.jackson.core </prouvenid> <Artifactid> jackson-core </lefactive> <in version> $ {jackson.version} </preentency. <ArtefactId> Jackson-Databind </letefactive> <Severk <GroupId> javax.servlet </rom grouped> <Artifactid> servlet-api </retifactid> <version> 3.0-alpha-1 </ version> <ccope> fourni </ccope> </Dependency> <Dedency> <proupId> javax.servlet </proped> <e Artifactid> JSTL </tatifactid> <frision> <Dudition> 1.2 </ version> </predences> </ptetifactid> <fri version>> 1.2 </ version> <Duild> <inalName> Springmvc_hibernate_demo </ finalName> <Glugins> <! - Exécutez les tests de l'unité Junit dans un Classloader isolé -> <plugin> <proupId> org.apache.maven.plugins </proupId> <Artifactid> Maven-Surefire-Plugin </ Artifactid> <Skiptests> true </ skiptests> </ configuration> </ plugin> <plugin> <proupId> org.apache.maven.plugins </prôdId> <Artifactid> maven-war-plugin </ artifactid> <version> 2.3 </-version> <finiguration> <webxl> src / main / webapp / web-inf / web.xml </ webxl> src / main / webapp / web-inf / web.xml </ webxl> src / main / webApp / web-inf / web.xml </ webxl> src / Main / WebApp </configuration> </plugin> <!-- generate java doc --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>2.9.1</version> <configuration> <javadocDirectory>target/javadoc</javadocDirectory> <reportoutputDirectory> Target / javadoc </portoutUpputDirectory> <Charset> UTF-8 </CHARSet> <Ocoding> UTF-8 </coding> <Docencoding> UTF-8 </ DoCencoding> <Quali> Private </ Show> </FIFIGROUGE> </Glugin> <! <GroupId> org.codehaus.cargo </prôdId> <Artifactid> Cargo-Maven2-Plugin </ ArfactId> <Dersion> 1.0 </ Version> <frainguration> <Container> <Containerid> Tomcat6x </ Containerid> <home> d: /webserver/apache-tomcat-6.0.39 </ home> </ contenant> <Type> existant </pype> <home> d: / /webserver/apache-tomcat-6.0.39 </ home> </ configuration> </ configuration> </gingin> </glugins> </ build> </ project>3. Introduire la configuration du ressort
Écrivez un fichier de configuration et placez le fichier de configuration dans le répertoire des ressources SRC / Main / Resources (même ci-dessous).
Informations de configuration requises par le projet Config.properties
#Application Configs # JDBC C3P0 CONFIGJDBC.DRIVER = com.mysql.jdbc.Driverjdbc.url = jdbc: mysql: // localhost: 3306 / work? useucicode = true & caractères) ConfighiberNate.Dialect = org.hibernate.dialect.mysqldidialisecthibernate.show_sql = truehibernate.format_sql = falsehibernate.hbm2ddl.auto = updatehibernate.cache.use_second_level_cache = trueHibernate.Cache.Use_Query_Cache = truehibernate.cache.region.factory_class = org.hibernate.cache.ehcache.ehcacheRegionfactoryhibernate.cache.provider_configuration_file_resource_path = ehcache.xml
3.1. Configuration de ressort
Le fichier de configuration de Spring.xml est le suivant:
<? xml version = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd "> <! - Fichier de configuration de chargement -> <contexte: propriété-location de la location =" Classpath: config.properties "/ <! <Context: Component-Scan Base-Package = "org.andy.work.service.impl, org.andy.work.dao.impl" /> </ beans>
Le ressort ci-dessus configure la gestion automatique de l'injection de haricots des haricots composants correspondants sous le package. Nous devons remettre la classe d'implémentation de DAO et de service à Spring pour gérer, comme (@Repository, @Service).
3.2. Introduire la configuration du fichier journal log4j
Le fichier de configuration de log4j.properties est le suivant: ### Set Log Niveaux ### log4j.rootlogger = info, c, d, e ### Console ### log4j.apprender.c = org.apache.log4j.consoleaPenderLog4 org.apache.log4j.patternlayoutlog4j.appender.c.layout.conversionPattern = [springmvc_hibernate_demo] [% p] [% -d {yyyy-mm-dd hh: mm: ss}]% C.% m (% l) | % m% n ### Fichier journal ### log4j.appendender.d = org.apache.log4j.dailyrollingfileAppenderLog4j.appender.d.file = ../logs/springmvc_hibernate_demo.loglog4j.apprender.d.append = TROLOG4J.APPENDER log4j.appender.d.layout = org.apache.log4j.patternlayoutlog4j.appender.d.layout.conversionpattern = [printempsmvc_hibernate_demo] [% p] [% -d {yyyy-mm-dd hh: mm: ss}]% C.% m (% l) | % m% n ### Exception ### log4j.appender.e = org.apache.log4j.dailyrollingfileAppenderLog4j.appender.e.file = ../logs/springmvc_hibernate_demo_error log4j.appender.e.layout = org.apache.log4j.patternlayoutlog4j.appender.e.layout.conversionpattern = [sspringmvc_hibernate_demo] [% p] [% -d {yyyy-mm-dd HH: mm: ss}]% C.% m (% L) | % m% n 4. Configuration d'hibernate
La configuration de Hibernate comprend principalement: la configuration de la source de données C3P0, la configuration de sessionfactory, la configuration de Transaction Manager et la configuration de la gestion des transactions. Le fichier Spring-Hibernate.xml est le suivant:
<? xml version = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: aop = "http://www.springframework.org/schema/aop" xsi: schemalation = "http://www.spring http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsdd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd "> <! id = "dataSource" destrie-méthod = "close"> <propriété name = "driverclass" value = "$ {jdbc.driver}" /> <propriété name = "jdbcurl" value = "$ {jdbc.Userlame}" /> <propriété = "user" value = "$ {jdbc.ausera}" /> <propriété = "Name =" Nom " Value = "$ {jdbc.password}" /> <! - Demande Timeout -> <propriété name = "CheckoutTimeout" value = "30000" /> <! - Vérifiez toutes les connexions inactives dans le pool de connexions toutes les 60 secondes. Valeur par défaut: 0, non vérifiez -> <propriété name = "idleConnectionTestPeriod" value = "30" /> <! - maximum inactif temps pour la base de connexion de la base de données Pool de connexion -> <propriété name = "maxidletime" value = "30" /> <! - Nombre de connexions connexes initialisées dans le pool de connexion -> <propriété name <propriété name = "maxpoolSize" value = "20" /> <! - Nombre de connexions obtenues par C3P0 en même temps à la fois lorsque la connexion dans le pool de connexions est épuisée. Valeur par défaut: 3 -> <propriété name = "AcquireIncrement" value = "5" /> </ank> <! - Configurer Hibernate SessionFactory -> <bean id = "SessionFactory"> <! - Voir le code source pour l'injection de données de données -> <propriété name = "DataSource" Ref = "DataSource" /> <! <props> <prop key = "hibernate.dialect"> $ {hibernate.dialect} </ prop> <prop Key = "hibernate.show_sql"> $ {hibernate.show_sql} </ prop> <prop key = "hibernate.format_sql"> $ {hibernate.format key = "hibernate.hbm2ddl.auto"> $ {hibernate.hbm2ddl.auto} </prop> <! - Activez le cache de niveau 2 ehcache -> <prop Key = "hibernate.cache.use_second_level_cache"> $ {Hibernate.cache.Use_Second_level_cache "> $ {Hibernate.cache.Use_Second_level_cache"> $ {Hibernate.Cache.Use_Second_level_cache} key = "hibernate.cache.use_query_cache"> $ {hibernate.cache.use_query_cache} </ prop> <prop key = "hibernate.cache.region.factory_class"> $ {Hibernate.cache.region.factory_class} </prop> <prop. key = "hibernate.cache.provider_configuration_file_resource_path"> $ {hibernate.cache.provider_configuration_file_resource_path} </ prop> </props> </ propriété> <! - Scannez l'entité de la configuration d'annotation hiberneuse -> <propriété Nom = "Packagstoscan" Value = "org.andy.work.entity" /> </ank> <! - Configurer le gestionnaire de transaction -> <bean id = "transactionManager"> <propriété name = "sessionfactory" Ref = "SessionFactory" /> </Ean> <! - Configurer les transactions de transaction de transaction et Spécifier le gestionnaire transaction Sémantique -> <tx: attributs> <tx: méthode name = "insert *" propagation = "required" /> <tx: méthode name = "update *" propagation = "required" /> <tx: méthode name = "delete *" propagation = "required" /> <tx: méthode name = "get *" propagation = "supports" readly = "true" /> <tx: méthode = "procédure * propagation = "supports" read-only = "true" /> <tx: méthode name = "find *" propagation = "supports" read-only = "true" /> <! - D'autres utilisent des méthodes de transaction par défaut -> <tx: méthode name = "*" /> </ tx: attributes> </ tx: conseils> <! - Spring Aop Transaction Management-> <aop: config> <! - Configurer les points de pointcut - <aop transaction: <aop: Configin id = "transactionpointcut" expression = "exécution (* org.andy.work.service .. * impl. * (..))" /> <! - Spécifiez pour appliquer le traitement d'amélioration des transactions TXADVIC Ce qui précède est configuré avec le cache secondaire et l'Ehcache. Pour les informations spécifiques pertinentes, veuillez consulter l'article précédent Hibernate Hibernate Secondary Cache et Ehcache Construction Configuration. Ce qui suit est la configuration du cache secondaire.
4.1. Configuration ehcache.xml
<? xml version = "1.0" Encoding = "utf-8"?> <ehcache xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: nonamespaceschemalation = "../ / config / ehcache.xsd"> <diskstore path = "d: / ehc" Paramètre defaultCache. -> <defaultCache maxElementsInMemory = "1000" eternal = "false" TimeToidleSEconds = "120" TIMETOLIVESCONDS = "120" MaxElementsonDisk = "1000000" OverflowTodisk = "True" MemoryStoreeVictionPolicy = "LRU"> </ defaultCache> <! - Paramètres d'objets spéciaux. -> <cache name = "org.andy.work.entity.acctUser" maxElementsInMemory = "2" MemoryStoreevictionPolicy = "LRU" eternal = "true" diskpersistent = "false" overflowtodisk = "false" maxelementsondisk = "1000000" /> </ehCache>
Le cache secondaire hibernate ci-dessus ehcache est d: / ehcache
5. Générer une entité commerciale
Après la conception de la table de données, les entités Hibernate ont généré automatiquement les outils Hibernate d'outils. Eclipse nécessite le plug-in Installation of Hibernate Tools (je l'ai installé en ligne plusieurs fois, mais il n'est pas réussi. Il est recommandé d'utiliser des liens pour installer hors ligne, et l'annexe le présentera). Par conséquent, il n'est pas nécessaire d'écrire manuellement. Voici une entité avec des informations d'utilisateur, Accuser.java
Package org.andy.work.entity; // Généré 2015-2-3 10:43:00 par Hibernate Tools 4.0.0Import Java.util.date; Importer Java.util.hashset; Importer Java.util.Set; Import Javax.Persistence.column; import javax.persistence.id; importer javax.persistence.joincumn; import javax.persistence.jointable; import javax.persistence.manytomany; import javax.persistence.table; import javax.persistence.temporal; importer javax.persistence.temporalise; org.hibernate.annotations.cache; import org.hibernate.annotations.cacheCurrencystrategy; import com.fasterxml.jackson.annotation.jsonignoreproperties; / ** * accuSer généré par HBM2java * / @ entity @ table (name = "acct_user", catalogne = "work"). CacheConcurrencystrategy.read_write) Classe publique AccTUser implémente java.io.serializable {/ ** * * / private static final SerialVersionUID = 6980093847795726310l; ID de chaîne privée; surnom de cordes privées; Téléphone de chaîne privée; Date privé Registertime; set privé <Cctrole> actroles = new HashSet <Cctrole> (0); public AccTuser () {} public AccTuser (String id, String Nowname) {this.id = id; this.nickName = surnom; } public acccuser (String id, String Surnom, String Telephone, Date RegisterTime, set <Cctrole> Acctroles) {this.id = id; this.nickName = surnom; this.telephone = téléphone; this.RegisterTime = RegisterTime; this.acctroles = Acctroles; } @Id @Column (name = "id", unique = true, nullable = false, longueur = 36) public String getID () {return this.id; } public void setid (String id) {this.id = id; } @Column (name = "nick_name", nullable = false) public String getNickName () {return this.nickName; } public void setNickName (String Nelname) {this.nickName = Nontes; } @Column (name = "téléphone") String public gettelephone () {return this.telephone; } public void Settelephone (String Telephone) {this.telephone = téléphone; } @Temporal (temporaltype.timestamp) @Column (name = "registre_time", longueur = 19) public date getRegistertime () {return this.registertime; } public void setRegisterTime (Date RegisterTime) {this.registertime = registretime; } @Jsonignoreproperties (value = {"Accusers", "AccTuthorities"}) @ManyToMany (fetch = fetchType.lazy) @cache (usage = cacheCurrencystrategy.read_write) @jointable (name = "acct_use_role", catloc = "work", joincolumns = {@joinn (nom = "user_id", nullable = false, updateable = false)}, inversejoinColumns = {@joincomn (name = "role_id", nullable = false, updateable = false)}) public set <cctrole> getAcCtrole () {return this.acctrole; } public void setAcCtroles (set <cctrole> actroles) {this.acctrole = actroles; }} Il y a quelques éléments à noter ci-dessus:
La plupart des éléments ci-dessus sont générés automatiquement par des outils Hibernate, mais il y en a plusieurs qui doivent être ajoutés manuellement:
1. Si cette entité utilise le cache de niveau 2, vous devez ajouter l'annotation @Cache;
2. S'il y a des éléments définis (set, map, list) dans l'entité, et si l'entité souhaite utiliser un cache secondaire, ces éléments définis doivent également être ajoutés avec @Cache Annotation.
3. @Jsonignoreproperties L'annotation doit empêcher SpringMVC de produire une sortie de boucle lorsque JSON revient. S'il n'est pas configuré, JSON Dead Loop se produira (et des propriétés de plusieurs à plusieurs).
4. @Jsonignore se convertit en JSON pour ignorer cette propriété, tandis que @jsonignoreproperties (value = {"AcctUsers", "AcctaThorities"}) ignore les propriétés des accteurs et des accapésissements en acctras.
6. Créer une couche Dao
Interface 6.1dao
Nous devons adopter l'idée de la programmation d'interface faciale dans la couche DAO et la couche de service, nous définissons donc d'abord une interface General Dao, Genericdao.java
Package org.andy.work.dao; Importer java.io.serializable; import java.util.list; / ** * Temps créé: 2015-2-6 2:26:42 PM * * @Author Andy * @version 2.2 * * Dao General Interface * / Interface générique); T get (pk id); List <t> findall (); vide persiste (entité t); PK SAVE (entité T); void SaveorUpdate (Tente T); void delete (pk id); void flush ();}
Définissez l'interface Userdao.java spécifique
Package org.andy.work.dao; import org.andy.work.entity.acctuser; / ** * temps de création: 2015-2-6 2:43:50 PM * * @Author Andy * @version 2.2 * * Interface Dao * / public interface userdao étend générique
6.2. Classe d'implémentation de la couche Dao
Nous devons injecter la classe d'implémentation de la couche DAO en beans, nous devons donc ajouter l'annotation @Repository, UserDaoimpl est la suivante:
Package org.andy.work.dao.impl; import java.util.list; import org.andy.work.dao.userdao; import org.andy.work.entity.acctuser; import org.hibernate.sses; import org.hibernate.SessionFactory; import org.springframeworkwork.beans.factory.factory.aUtowired; org.springframework.sterreotype.repository; / ** * Temps de création: 2015-2-6 2:45:14 PM * * @Author Andy * @version 2.2 * / @ Repository ("userdao") public class userDaoimpl implémente userdao {@Autowired Private SessionFactory SessionFactory; Session privée getCurrentession () {return this.sessionfactory.getCurrentession (); } @Override Public AccTuser Load (String id) {return (AccTuser) this.getCurrentession (). Load (AccTuser.class, id); } @Override public AcctUser get (String id) {return (AccTuser) this.getCurrentession (). Get (Accuser.class, id); } @SuppressWarnings ("Unchecked") @Override public list <cccuser> findall () {list <accTuser> AccTusers = this.getCurrentession (). CreateQuery ("from AccuSer"). SetCacheable (true) .list (); RETOUR ACCTUSERS; } @Override public void persist (AccTuser Entity) {this.getCurrentession (). Persist (entité); } @Override public String Save (entité AccTUser) {return (String) this.getCurrentession (). Save (entité); } @Override public void SaveorUpDate (entité Accuser) {this.getCurrentession (). SaveorUpDate (entité); } @Override public void Delete (String id) {AccTuser Entity = this.load (id); this.getCurrentession (). Delete (entité); } @Override public void flush () {this.getCurrentession (). Flush (); }}7. Créer une couche de service
7.1. Interface de couche de service
Package org.andy.work.service; import java.util.list; import org.andy.work.entity.acctuser; / ** * temps de création: 2015-2-6 3:18:57 PM * * @Author Andy * @version 2.2 * Interface de service utilisateur * / interface publique UserstService {Accuser Load (String ID); AcctUser get (String ID); List <cccuser> findall (); vide persister (entité accruante); String Save (entité AccTUser); void SaveorUpDate (entité AccTUser); void delete (String id); void flush ();}7.2. Classe d'implémentation de la couche de service
UserServiceIMPL doit injecter le haricot de couche DAO défini ci-dessus.
package org.andy.work.service.impl; import java.util.list; import org.andy.work.dao.userdao; import org.andy.work.entity.acctuser; import org.andy.work.service.uservice; import org.springframework.beans.factory.annotation.autowired; import; org.springframework.sterreotype.service; / ** * temps de création: 2015-2-6 3:24:16 PM * * @Author Andy * @version 2.2 UserService Implémentation * / @ Service ("UserService") public Class ServiceIMPL implémente userService {@Autowired Userdao userdao; @Override public AcctUser Load (String id) {return userdao.load (id); } @Override public AcctUser get (String id) {return userdao.get (id); } @Override public list <cccuser> findall () {return userdao.findall (); } @Override public void persist (AccTuser Entity) {userdao.persiste (entité); } @Override public String Save (entité AccTUser) {return userdao.save (entité); } @Override public void SaveorUpDate (entité Accuser) {userdao.saveorupDate (entité); } @Override public void Delete (String id) {userdao.delete (id); } @Override public void flush () {userdao.flush (); }}8. Testez l'intégration du printemps et de l'hibernate
Nous pouvons écrire une classe de test dans SRC / Test / Java pour tester la configuration ci-dessus. Si le test réussit, il sera essentiellement terminé.
package org.andy.work.service; import java.util.date; import java.util.list; import java.util.uuid; import org.andy.work.entity.acctuser; import org.apache.log4j.logger; import org.junit.test; import org.junit.runner.runwith; import org.springframework.beans.factory.annotation.autowired; import org.springframework.test.context.contextConfiguration; import org.springframework.test.context.junit4 3:31:07 pm * * @author andy * @version 2.2 */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-hibernate.xml" })public class TestUserService { private static final Logger LOGGER = Logger .GetLogger (TestUserService.class); @Autowired Private UserService UserService; @Test public void Save () {Accuser AccTuser = new AccTuser (); acccuser.setid (uUid.randomuuid (). toString ()); acccuser.setNickName ("Andy"); acccuser.setRegisterTime (new Date ()); acccuser.settelephone ("13022221111"); String id = userService.save (Accuser); Logger.info (JSON.TojSontring (ID)); }}9. Introduire Springmvc
Ajouter le fichier printemps-mvc.xml
<? xml version = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: mvc = "http://www.springframework.org/schema/mvc" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns: p = "http://www.springframework.org/schema/p" xmlns: context = "http://www.springframework.org/schema/context" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/springframeworks-4.1.xssd http://www.springframework.org/schema/contex http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring Scan @Controller Injection As Bean -> <Context: Component-Scan Base-Package = "org.andy.work.Controller" /> <! - Ce qui suit est SpringMvc Configuration -> <MVC: annotation-Drived <stist> <value> text / html; charset = utf-8 </value> <value> application / json; charset = utf-8 </value> </sist> </ propriété> </ank> </mvc: Message-Converters> </mvc: annotation-drive> <! - PARE le nom de vue du modèle, Ajouter pré- et suffixe au nom de la vue du modèle - <Bean> name = "ViewClass" value = "org.springframework.web.servlet.view.jstlview" /> <propriété name = "prefix" value = "/ web-inf / vues" /> <propriété name = "suffix" value = ". jsp" /> </ bean> </ beans>
Le contrôleur de balayage de package, [Protégé par e-mail] ��, et les configurations de calque d'affichage sont configurées ci-dessus.
10. Configurer le conteneur web.xml
Les conteneurs Web sont le cerveau des projets Web, de sorte que les conteneurs Web doivent d'abord introduire le printemps, laisser le printemps gérer divers cadres et les injecter dans les haricots. Configurez ensuite les informations de filtre de la couche de contrôle. Et l'URL interceptée par SpringMVC est configurée pour les demandes se terminant par .hmls.
Le fichier web.xml est le suivant:
<? xml version = "1.0" Encoding = "utf-8"?> <web-app xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: web = "http://java.sun.com/xml/ns/javaee" xmlns: web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" XSI: ScheMalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id = "webapp_id" version = "2.5"> <splay-name> Springmvc_Demo </ Display-Name> <param-name> ContextConfiglocation </ param-name> <param-valeur> classpath: spring.xml, classpath: printemps-hibernate.xml </ param-value> </ context-param> <filter> <filter-name> EncodingFilter </filter-name> <Filter-Class> org.springFramework.web.filter.CaracTerencodingFilter </ Filter-Class> <Init-Param> <Amam-Name> Encoding </ Param-Name> <Anit-Value> UTF-8 </ Param-Value> <param-valeur> true </ param-valeur> </ init-param> </filter> <filter-mapping> <filter-name> EncodingFilter </filter-name> <Url-poatn> / * </url-dattern> </filter-mapping> <! - La configuration d'OpenSessionInview est pour retarder la fermeture de la session vers le calqueur de vue -> <filter> <filter-name> openssesseInViewFilter </ Filter-Name> <Filter-Class> org.springframework.orm.HiberNate4.Support.OpenSessionInViewFilter </ Filter-Class> <Init-Param> <Am param-name> SingleSession </ Param-Name> <Param-Value> True </ param-Value> Pour servirtcontext et démarrer les informations de configuration de Spring dans ContextConfiglocation -> <ouciner> <écouteur-classe> org.springframework.web.context.contextLoaderListener </ écouteur-classe> </ auteur> <! - écouteur> <auditeur-classe> org.springframework.web.context Spring Memory Overflow Écouteur -> <ousiner> <écouteur-class> org.springframework.web.util.introspectorcleanupListener </ auteur-class> </diner> <vrlet> <description> Spring MVC Servlet </ Description> <Servlet-Name> REST </Servlet-Name> <Servlet-Class> org.springframework.web.servlet.dispatcherServlet </vrlett-Class> <Init-Param> <Am param-name> ContextConfiglocation </ Param-Name> <! - Voici le fichier de configuration Springmvc -> <Am param-Value> CLASSPATH: Spring-Mvc.xml </ param-Value> <Charot-on-startup> 1 </ Load-on-startup> </ servlet> <servlet-mapping> <servlet-mapping> <servlet-name> rest </vrlett-name> <url-potern> *. htmls </url-potern> </ servlet mapping> <filter-mapping> <filter-name> opensessioninViewFilter </filter-name> <URL-PATTERN> *.
11. Créer un contrôleur de couche de contrôle
Contrôle de la couche UserController
package org.andy.work.Controller; import java.util.list; import org.andy.work.entity.acctus; import org.andy.work.service.userservice; import org.apache.log4j.logger; import org.sprice org.springframework.sterreotype.Controller; import org.springframework.ui.modelmap; import org.springframework.web.bind.annotation.pathvariable; import org.springframework.web.bind.annotation.requestmapping; org.springframework.web.bind.annotation.ResponseBody; / ** * Temps de création: 2015-2-7 11:49:00 AM * @Author Andy * @version 2.2 * Description: Contrôleur d'utilisateur * / @ Controller @ Recorder Logger = Logger.getlogger (UserConder. @Autowired Private UserService UserService; @RequestMapping("/showInfo/{userId}") public String showUserInfo(ModelMap modelMap, @PathVariable String userId){ LOGGER.info("Query user: " + userId); AcctUser userInfo = userService.load(userId); modelMap.addAttribute("userInfo", userInfo); return "/user/showInfo"; } @RequestMapping("/showInfos") public @ResponseBody List<AcctUser> showUserInfos(){ LOGGER.info("Query all users of the user"); List<AcctUser> userInfos = userService.findAll(); return userInfos; }}12、创建视图层
在src/main/webapp/WEB-INF/views下创建user/showInfo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%><% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><base href="<%=basePath%>" /><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><script type="text/javascript" src="js/jquery-1.9.1.min.js"></script><title>userInfo</title></head><body> User information nickname: ${userInfo.nickName} User id: ${userInfo.id} User phone: ${userInfo.telephone } Registration time: <fmt:formatDate value="${userInfo.registerTime }" pattern="yyyy-MM-dd HH:mm:ss" /> Role: [ <c:forEach items="${ userInfo.acctRoles}" var="role"> ${role.name } Permissions[ <c:forEach items="${ role.acctAuthorities}" var="authority"> ${authority.name } </c:forEach> ] </c:forEach> ] <br /> ajax displays all user information: <div id="show_all_user"></div></body><script type="text/javascript"> $.ajax({ type : "get", url : "user/showInfos.htmls", dataType : "json", success : function(data) { $(data).each( function(i, user) { var p = "<p>Nickname:" + user.nickName + " Phone:" + user.telephone + " Registration time:" + user.registerTime + " id:" + user.id + "</p>"; $("#show_all_user").append(p); }); }, async : true });</script></html>13、部署服务器测试
使用Maven打包部署:clean compile package
部署到tomcat,测试主要测试上面的http://localhost:8080/springmvc_hibernate_demo/user/showInfo/6e5afb1d-50e1-45fe-b6fe-b9e399415387.htmls
和http://localhost:8080/springmvc_hibernate_demo/user/showInfos.htmls (json数据返回)
上面视图层就包含了这两条url请求的测试:
ok,到此Spring+SpringMVC+Hibernate搭建完毕。
博客来源:http://blog.csdn.net/fengshizty?viewmode=list
项目源码:http://download.csdn.net/detail/fengshizty/8432647
I hope to help friends in need and continue to add relevant information in the future. Merci pour votre soutien à ce site!