1. Préparation
Avant de commencer, veuillez vous référer à l'article précédent:
Struts2.3.24 + printemps4.1.6 + Hibernate4.3.11 + MySQL5.5.25 La construction de l'environnement de développement et les explications connexes sont les mêmes, mais Struts2 est remplacé par Spring MVC
2. Différents endroits
Répertoire de projet et package JAR:
Modifier le package d'action en contrôleur;
Supprimez le package JAR Struts2 et ajoutez le package Spring MVC (s'il existe déjà, vous n'avez pas besoin de l'ajouter);
Web.xml Configuration:
La différence avant est que le filtre Struts2 est remplacé par un servlet, l'objectif principal est d'acheter l'URL et de le remettre au Spring MVC pour le traitement;
<? 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" XSI: ScheMalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id = "webapp_id =" 3.0 " <splay-name> ssh </ display-name> <ftext-param> <param-name> contextConfiglocation </ param-name> <param-value> classpath: applicationContext.xml </ param-value> </ context-paam> <ouciner> <auditeur-class> org.springframework.web.context.contextoLoDerDerDidener </ écouteur-CLASS> </ écouteur> <Deencome-File-List> <Lelawear-File> index.jsp </ Welcome-File> </ Welcome-File-List> <Serplet> <Serplet-Name> Springmvc </Servlet-Name> <Servlet-Class> Org.SpringFramework.web.servlet.Dispatcherservlet </servlet-class> <init-param> <paramname> <Am param-Value> CLASSPATH: Springmvc-servlet.xml </ Param-Value> </ Init-Param> <Choad-on-Startup> 1 </ Load-on-Startup> </ Servlet> <Serplet-Mapping> <Serplet-Name> Springmvc </ Servlet-Name> <Url-Pattern> *. Do </ url-Pattern>
Configuration d'applicationContext.xml:
La différence est principalement lors de la configuration de la numérisation automatique, le composant @Controller doit être exclu. Ces haricots sont générés par Spring MVC;
Les autres configurations sont les mêmes que dans l'article précédent;
<? xml version = "1.0" Encoding = "utf-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: p = "http://www.springframework.org/schema/p" xmlns: context = "http://www.springframework.org/schema/context" xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/xmlma. xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: jdbc = "http://www.springframework.org/schema/jdbc" xsi: schemalocation = "http://www.springfrrame http://www.springframework.org/schema/beans http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsdd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsddd http://www.springframework.org/schema/context/spring-context-4.1.xsd "> <! - scanne le ClassPath pour les composants annotés (y compris @Repostory et @Service qui sera auto-réinscrit en tant que Spring Beans -> <Context: Component-Scan Base-Package =" SSH "> <! scanné par le fichier de configuration de SpringMvc -> <contexte: exclure-filter type = "annotation" expression = "org.springframework.steretype.controller" /> </ context: composant-scan> <! - Sélection de la source de données -> <bean name = "dataSource" destrust-méthod = "close"> <propriété name = "Driverclos /> <propriété name = "jdbcurl" value = "jdbc: mysql: // localhost: 3306 / démo" /> <propriété name = "user" value = "root" /> <propriété name = "passway" value = "property" /> <propriété = "InimalPoolsize" value "value =" 1 80 "> </ propriété> <propriété name =" initialPoolsize "value =" 80 "> </ propriété> <propriété name =" initialpoolsize "Value =" 80 "> </ Property name = "maxidleTime" value = "60"> </ propriété> <propriété name = "maxpoolSize" value = "80"> </ propriété> <propriété name = "minpoolsize" value = "50"> </ propriété> <propriété name = "acquirerityDempts" value = "60"> </ property name = "acquiretryTempts" value = "60"> </ </ property name = "BreakafteracQuireFailure" value = "false"> </ propriété> <! - Si trop de connexions apparaissent, faites attention à la modification du fichier de configuration My.ini de MySql pour augmenter le nombre maximum d'éléments de configuration de connexions (voir la commande de connexion actuelle: Show ProcessList) -> </ bean name = "HiberNateProperties"> <propS> <prop key = "hibernate.dialect"> org.hibernate.dialect.mysqldialect </prop> <prop key = "hibernate.show_sql"> true </ prop> <key = "hibernate.hbm2ddl.auto"> à la mise à jour </ project> key = "hibernate.hbm2ddl.auto"> update </ prop> <prop key = "connection.pool_size"> 10 </ prop> <prop key = "current_session_context_class"> thread </ prop> <pp key = "hibernate.cache.use_second_level_cache"> true </pp> </p> </ proP key = "hibernate.cache.region.factory_class"> org.hibernate.cache.ehcache.ehcacheRegionfactory </prop> <prop Key = "hibernate.cache.use_query_cache"> true </ prop> < key = "hibernate.cache.provider_configuration_file_resource_path"> ehcache.xml </ prop> </ props> </ propesse> <propriété name = "mappingLocations"> <sist> <value> classpath: ssh / model / user.hbm.xml </value> </sist> </tomamesh <sist> <value> ssh.model.user </value> </sist> </ propriété> -> </ bean> <! - Configurer le gestionnaire de transaction -> <bean id = "TransactionManager"> <propriété name = "SessionFactory" Ref = "SessionFactory" /> </ank> <! - Caractéristiques de propagation de transaction -> <tx: id = "TxAdvice" Transaction-Bransaction = "TRANSACTIONS: CONSEILLAGE =" TXADVIC <tx: attributs> <tx: méthode name = "add *" propagation = "requise" read-only = "false" rollback-for = "java.lang.exception" /> <tx: méthode name = "delete *" propagation = "requise" read-only = "false" rollback-for = "java.lang.exception" /> <tx: méthode name = "delete *" propagation = "exigée" read-only = "false" rollback-for = "java.lang.exception" /> <tx: méthode name = "update *" propagation = "requis" readly = "false" rollback-for = "java.lang.exception" /> <tx: méthode name = "Save *" propagation = "requis" read-y </ tx: attributs> </ tx: conseils> <aop: config> <aop: Pointcut id = "pcMethod" expression = "Execution (* ssh.service .. *. * (..))" /> <aop: conseiller PointCut-ref = "pcMethod" conseils-refi = "txadvice" /> </aop: config> <! id = "aoptest"> </ank> <bean id = "myaop"> </ bean> <aop: config proxy-target-class = "true"> <aop: aspect ref = "myaop"> <aop: Pointcut id = "pcMethodTest" expression = "Execution (* ssh.aop.aoptest.Test * (..))" /> <aop: avant PointCut-ref = "pcMethodTest" méthode = "avant" /> <aop: après Pointcut-ref = "pcMethodTest" Method = "After" /> </ aop: aspect> </ aop: config> </bans>
Springmvc-servlet.xml Configuration:
Configurez la numérisation automatique de @Controller dans le package SSH.Controller. Ici, vous devez restaurer le filtre excluant configuré dans ApplicationContext.xml;
Configurer l'analyse de vue, il existe de nombreux analyseurs, nous prenons ici INTERNALRESORCEVIEWRESOLVER comme exemple;
<? xml version = "1.0" Encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: context = "http://www.springframework.org/schema/context" XMLNS: MVC = "http://www.springframework.org/schema/mvc" xmlns: p = "http://www.springframework.org/schema/p" xmlns: xsi = "http://www.w3.org/2001/xmlma xmlns:tx="http://www.springframework.org/schema/tx" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsdd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd "> <! - Démarrez automatique > <! - Restaurez le défiltre exclut défini par le conteneur parent, faites attention au chemin de balayage de package ssh.Controller -> <context: include-filter type = "annotation" expression = "org.springframework.StereType.Controller" /> </ context: Component-scan> <! <value> / web-inf / jsp / </value> </ propriété> <propriété name = "suffixe"> <value> .jsp </value> </ propriété> </bans>
Contrôleur d'écriture:
Étant donné que Spring MVC est utilisé pour remplacer Struts2, il n'y a pas de package d'action. Supprimer et créer un nouveau package de contrôleur. Créez une nouvelle classe UserController sous le package;
@RequestMapping: URL de carte;
@ResponseBody: le contenu est renvoyé directement sous forme de corps;
UserController.java
package ssh.Controller; import java.io.printwriter; import java.util.list; import javax.annotation.resource; import javax.servlet.http.httpservletRest; org.springframework.sterreotype.Controller; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.responsebody; import ssh.aop.aoptest; import; com.google.gson.gson; @ contrôleur @ requestmapping ("/ user") public class userController {logger logger = logger.getLogger (userController.class); @Resource Private UserService UserService; @Resource Private AOPTEST AOPTEST; @RequestMapping (value = "/ addUser") @ResponseBody public void addUser (requête httpservletRequest, réponse httpservletResponse) {printwriter out = null; try {réponse.setContentType ("text / html; charset = utf-8"); String Account = request.getParameter ("Account"); String name = request.getParameter ("name"); String Address = request.getParameter ("Address"); Utilisateur utilisateur = nouveau utilisateur (); user.setAccount (compte); user.setAddress (adresse); user.setName (nom); userService.add (utilisateur); out = réponse.getWriter (); out.write (new gson (). tojson ("succès")); } catch (exception e) {e.printStackTrace (); Logger.Error (e.getMessage ()); if (out! = null) out.write (new gson (). tojson ("échec")); } enfin {out.flush (); out.close (); }} @RequestMapping (Value = "/ QueryUser") @ResponseBody public void queryAlUser (HttpServLetRequest Request, httpservletResponse Response) {printwriter out = null; aopTest.test1 (); aopTest.test2 (); try {réponse.setContentType ("text / html; charset = utf-8"); Gson gson = new gson (); List <ser user> userList = userService.QueryAllUser (); String gsonstr = gson.tojson (userList); out = réponse.getWriter (); out.write (Gsonstr); } catch (exception e) {e.printStackTrace (); Logger.Error (e.getMessage ()); if (out! = null) out.write (new gson (). tojson ("échec")); } enfin {out.flush (); out.close (); }}} 3. Exécutez le programme
Exécutez le programme, ajoutez des utilisateurs et interrogez les utilisateurs. La fonction est normale;
De plus, le cache secondaire fonctionne également normalement et la base de données ne fonctionne plus dans la deuxième requête;
@author un codeur de vent
Ce qui précède est tout le contenu de cet article. J'espère que cela sera utile à l'apprentissage de tous et j'espère que tout le monde soutiendra davantage Wulin.com.