1. Vorbereitung
Bevor Sie beginnen, lesen Sie bitte den vorherigen Artikel:
Struts2.3.24 + Spring4.1.6 + Hibernate4.3.11 + MySQL5.5.25 Die Konstruktion der Entwicklungsumgebung und die damit verbundenen Erklärungen sind gleich, aber Struts2 wird durch Spring MVC ersetzt
2. Verschiedene Orte
Projektverzeichnis und JAR -Paket:
Ändern Sie das Aktionspaket in Controller.
Löschen Sie das Struts2 -Jar -Paket und fügen Sie das Spring MVC -Paket hinzu (wenn bereits vorhanden, müssen Sie es nicht hinzufügen).
Web.xml -Konfiguration:
Der Unterschied zu zuvor besteht darin, dass der Struts2 -Filter durch ein Servlet ersetzt wird. Der Hauptzweck besteht darin, die URL zu vermitteln und MVC an Spring MVC zur Verarbeitung zu übergeben.
<? 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-app-app-app-app- = <diagdo.-Name> ssh </display-name> <context-param> <PARAM-NAME> contextConFigLocation </param-name> <param-value> classPath: applicationContext.xml </param-value> </context-param </listener> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping></web-app>
applicationContext.xml Konfiguration:
Der Unterschied besteht hauptsächlich bei der Konfiguration des automatischen Scannens. Die @Controller -Komponente muss ausgeschlossen werden. Diese Bohnen werden durch Frühlings -MVC erzeugt;
Andere Konfigurationen sind die gleichen wie im vorherigen Artikel.
<? xmlns: context = "http://www.springframework.org/schema/context" xmlns: tx = "http://www.spingframework.org/schema/tx xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: jdbc = "http://www.spingframework.org/schema/jdbc" xsi: schemalocation = "http 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/sping-tx- http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc http://www.springFramework.org/schema/jdbc/spring-jdbc-441.xsd http://www.springframework.org/schema/context/spring-context-4.1.xsd "> <!-Scans den ClassSpatated-Komponenten (einschließlich @Repostory und @Service, die auto-registriert sein werden-ausschließend-> <contexte: contexted: contexte: contexte: contexte: contexte: contexte: component-scan-package wird nach SpringMVC-Konfigurationsdatei gescannt-> <Kontext: filter type = "Annotation" Expression = "org.springFramework.steretype.Controller" /> < /context: component-scan> <!-Auswahl der Datenquelle-> <Beanname = "dataSource" destous-method = "> < value = "com.mysql.jdbc.driver" /> <Eigenschaft name = "jdbcurl" value = "jdbc: mysql: // localhost: 3306 /Demo" /> <Eigenschaft name = "Benutzer" value = "root" /> <Eigenschaft name = "Passwort" Value = "Wurzel". name = "initialPoolSize" value = "80"> </Eigenschaft> <Eigenschaft name = "maxidletime" value = "60"> </property> <Eigenschaft name = "maxpoolsize" value = "80"> </Property> <Eigentum name = "minpoolsize" value = "50"> </property> </property> </acquireretry = "acquireretry" = "1000"> </comenti> </ubmotentius name = "acrireretry" name = "accocireretryattempts" value = "60"> </property> <Eigenschaft name = "breakafteracquireFailure" value = "false"> </property> <!-Wenn zu viele Verbindungen erscheinen, achten Sie auf die Änderung der Konfigurationsdatei my.ini von MySQL, um die Maximum-Nummer der Konfigurationen zu erhöhen. name = "dataSource" ref = "dataSource"/> <Eigenschaft name = "hibernateProperties"> <props> <prop key = "hibernate.dialect"> org.hibernate.dialect key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="connection.pool_size">10</prop> <prop key="current_session_context_class">thread</prop> <prop key = "hibernate.cache.use_second_level_cache"> true </prop> <prop key = "hibernate key="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</prop> </props> </property> <property name="mappingLocations"> <list> <value>classpath:ssh/model/User.hbm.xml</value> </list> </property> <!-- <property name="annotatedClasses"> <list> <wert> ssh.model.user </value> </list> </property>-> </bean> <!-transaktionsmanager konfigurieren-> <bean id = "transactionManager"> <property name = "sesactionfactory" ref = "Sessionfactory"/> </bean> <! transaction-Manager = "transactionManager"> <tx: Attribute> <tx: Methode name = "add*" Propagation = "Erforderlich" schreibüberschreitend = "false" rollback-for = "java.lang.Exception"/> <tx: method name = "delete*" propagation = "erfordert" read-only "-Modal". Propagation = "Erforderlich" nur schreibgeschützt = "false" rollback-for = "java.lang.Exception"/> <tx: method name = "update*" Propagation = "Erforderlich" schreibgeschützt = "false" rollback-for = "java.lang.Exception.Exception"/> <Tx: method name = "savagation </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="pcMethod" expression="execution(* ssh.service..*.*(..))" /> <aop:advisor pointcut-ref="pcMethod" advice-ref="txadvice" /> </aop:config> <!-- Custom aop processing Test --> <bean id = "aoptest"> </bean> <bean id = "myaop"> </bean> <aop: config proxy-target-class = "true"> <aop: Aspekt ref = "myaop"> <aop: pointcut id = "pcMetestest" Expression = "Execution (* ssh.aop.aop.aop.aop.test pointcut-ref = "pcMethodetest" methode = "vor"/> <aop: After pointcut-ref = "pcMethodetest" methode = "nach"/> </aoP: Aspekt> </aop: config> </beans>
SpringMVC-Service.xml Konfiguration:
Konfigurieren Sie das automatische Scannen von @Controller unter dem SSH.Controller -Paket. Hier müssen Sie den in ApplicationContext.xml konfigurierten Exkludenfilter wiederherstellen.
Konfigurieren Sie View Parser, es gibt viele Parsers. Hier nehmen wir als Beispiel InternalResourceViewResolver ein.
<? xmlns: mvc = "http://www.springframework.org/schema/mvc" xmlns: p = "http://www.spingframework.org/schema/p" xmlns: xsi = "http://wwwwww.w.w.w.w.w.2001/xml xmlns: tx = "http://www.springframework.org/schema/tx" xsi: schemalocation = "http://www.spingframework.org/schema/beans http://www.spingframework.org/schema/beans/ 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 "> <!-Automatisch Scaning aller Bohnen unter diesem Paket (für Beispiele)-> <contexs)-> < > <!-Wiederherstellen Sie den vom übergeordneten Container festgelegten Ausschlussfilter und achten Sie auf den Paket-Scan-Pfad ssh.controller-> <context: include-filter type = "Annotation" Expression = "org.springFramework.steretype.controller" /> < /context: component-scan> <!- <wert>/web-inf/jsp/</value> </property> <Eigenschaft name = "suffix"> <wert> .jsp </value> </property> </beans>
Controller schreiben:
Da Spring MVC zum Ersetzen von Struts2 verwendet wird, gibt es kein Aktionspaket. Löschen und erstellen Sie ein neues Controller -Paket. Erstellen Sie eine neue UserController -Klasse unter dem Paket.
@RequestMapping: MAP URL;
@ResponseBody: Der Inhalt wird direkt als Körper zurückgegeben.
UserController.java
Paket ssh.controller; import Java.io.printwriter; import Java.util.list; import Javax.annotation org. com.google.gson.gson;@controller@requestmaping ("/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 (httpServletRequest -Anforderung, HttpServletResponse -Antwort) {Prinzipel Out = null; try {response.setContentType ("text/html; charSet = utf-8"); String account = request.getParameter ("Konto"); String name = request.getParameter ("Name"); String address = request.getParameter ("Adresse"); User user = new user (); user.setAccount (Konto); user.setAddress (Adresse); user.setName (name); userService.add (Benutzer); out = response.getWriter (); out.write (New GSON (). Tojson ("Erfolg")); } catch (Ausnahme e) {e.printstacktrace (); logger.Error (e.getMessage ()); if (out! = null) out.write (new gson (). tojson ("fail")); } endlich {out.flush (); out.close (); }} @RequestMapping (value = "/queryUser") @RespondeBody public void queryAlluser (httpServletRequest -Anforderung, httpServletResponse -Antwort) {printwriter out = null; Aoptest.Test1 (); Aoptest.Test2 (); try {response.setContentType ("text/html; charSet = utf-8"); Gson gson = new gson (); Liste <Unters> userList = userService.queryalluser (); String Gserstr = gson.tojson (Benutzerliste); out = response.getWriter (); out.write (Gserstr); } catch (Ausnahme e) {e.printstacktrace (); logger.Error (e.getMessage ()); if (out! = null) out.write (new gson (). tojson ("fail")); } endlich {out.flush (); out.close (); }}} 3. Führen Sie das Programm aus
Führen Sie das Programm aus, fügen Sie Benutzer hinzu und fragen Sie Benutzer. Die Funktion ist normal;
Darüber hinaus funktioniert der sekundäre Cache auch normal, und die Datenbank wird in der zweiten Abfrage nicht mehr betrieben.
@Author ein windartiger Coder
Das obige ist der gesamte Inhalt dieses Artikels. Ich hoffe, es wird für das Lernen aller hilfreich sein und ich hoffe, jeder wird Wulin.com mehr unterstützen.