SSM (Spring+SpringMVC+Mybatis), currently a relatively mainstream enterprise-level architecture solution. The standard MVC design model divides the entire system into four layers: display layer, controller layer, service layer, and Dao layer. SpringMVC is used to be responsible for request forwarding and view management, Spring implements business object management, and MyBatis is used as the data object persistence engine.
1. Frame details
Spring is a lightweight Java development framework created to solve the complexity of enterprise application development. Spring's purpose is not limited to server-side development. From a simplicity, testability and loose coupling perspective, any Java application can benefit from Spring. Simply put, Spring is a lightweight inversion control (IoC) and tangent-oriented (AOP) container framework
SpringMVC is a subsequent product of SpringFrameWork, separating the roles of controllers, model objects, dispatchers and handler objects. This separation makes them easier to customize.
MyBatis is a Java-based persistence layer framework. MyBatis provides a persistence layer framework including SQL Maps and Data Access Objects (DAO) which eliminates the manual setting of almost all JDBC code and parameters and the retrieval of result sets. MyBatis maps interfaces and Java to records in databases using simple XML or annotations for configuration and raw mapping
2. Create a Maven project
1. Create a project using Maven in Eclipse
2. Press the default Next
3. After finding maven-archetype-webapp, click next
4. Fill in the corresponding information. GroupID is the unique identifier of the project organization, which actually corresponds to the JAVA package structure. ArtifactID is the unique identifier of the project. The name of the actual corresponding project is the name of the project root directory. After filling in the Package, you can create a package for you by default, and it is OK to not write it.
5. The newly built directory is as follows
6. Maven stipulates that the following Source Folder must be added:
src/main/resources
src/main/java
src/test/resources
src/test/java
Before this step, it is best to right-click the project and select properties, then click java build path, under Librarys, edit the JRE System Library, and select workspace default jre.
7. Change the output paths separately to, and the corresponding relationship is as follows:
8. Convert the project to Dynamic Web Project, right-click Properties on the project, and select Project Facets on the left.
9. Set the file publishing path during deployment and delete the two items of test, because test is used for testing and does not require deployment.
Settings publish Maven's jar package to lib. Add -> Java Build Path Entries -> Maven Dependencies -> Finish
3. Maven introduces the required JAR packages
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.yingjun.test</groupId> <artifactId>TradingState</artifactId> <packaging>war</packaging> <version>2.0.1</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format> <spring.version>3.2.9.RELEASE</spring.version> <mybatis.version>3.1.1</mybatis.version> <mybatisspring.version>1.1.1</mybatisspring.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatisspring.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.10</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.10</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> </dependencies> <build> <plugins> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.2</version> <configuration> <version>3.0</version> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> <finalName>${project.artifactId}_${project.version}_${maven.build.timestamp}</finalName> </build> </project>4. Related configuration files and integration of SSM framework
web.xml
<?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/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <!-- Configure Spring --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Prevent Spring memory overflow Listener--> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- Prevent Spring Memory Overflow Listener--> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- Configure springmvc --> <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:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- Character Set Filter--> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
spring.xml
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd "> <!-- Scan service, dao components--> <context:component-scan base-package="com.yingjun.test" /> <!-- Decomposition jdbc.properites --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- Data source c3p0 --> <bean id="dataSource"> <property name="driverClass" value="${jdbc.driverClassName}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxPoolSize" value="${c3p0.pool.size.max}" /> <property name="minPoolSize" value="${c3p0.pool.size.min}" /> <property name="initialPoolSize" value="${c3p0.pool.size.ini}" /> <property name="acquireIncrement" value="${c3p0.pool.size.increment}" /> </bean> <!-- sessionFactory Integrate spring and mybatis--> <bean id="sqlSessionFactory"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:spring-mybatis.xml" /> <property name="mapperLocations" value="classpath*:com/yingjun/test/mapping/**/*.xml" /> </bean> <bean> <property name="basePackage" value="com,yingjun.test.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <bean id="transactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="append*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="modify*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="repair" propagation="REQUIRED" /> <tx:method name="delAndRepair" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS" /> <tx:method name="find*" propagation="SUPPORTS" /> <tx:method name="load*" propagation="SUPPORTS" /> <tx:method name="load*" propagation="SUPPORTS" /> <tx:method name="search*" propagation="SUPPORTS" /> <tx:method name="datagrid*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.yingjun.test.service..*Impl.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> </beans>In order to replace the manual code of writing data access objects (DAOs) using SqlSessionDaoSupport or SqlSessionTemplate, MyBatis-Spring provides a dynamic proxy implementation: MapperFactoryBean. This class allows you to directly inject the data mapper interface into your service layer bean. When using mappers, you just call them like you do with your DAOs, but you don't need to write any DAO implementation code, because MyBatis-Spring will create a proxy for you.
spring-mybatis.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- No other configuration is required for the time being --> </configuration>
spring-mvc.xml
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- Default annotation mapping support --> <mvc:annotation-driven /> <!-- Automatically scan the package, making SpringMVC think that the class annotated by @controller under the package is the controller --> <context:component-scan base-package="com.yingjun.test.controller" /> <!--Avoid download files when IE executes AJAX and return to JSON--> <bean id="mappingJacksonHttpMessageConverter" > <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- Define the pre-suffix of the jumped file, view mode configuration --> <bean > <!-- The configuration here is to automatically add prefix and suffix to the return string of the method of the subsequent action to become an available url address --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- Configuration file upload, if you do not use file upload, you do not need to configure it. Of course, if you do not match, then there is no need to introduce upload component packages in the configuration file --> <bean id="multipartResolver" > <!-- Default encoding --> <property name="defaultEncoding" value="utf-8" /> <!-- Maximum file size value --> <property name="maxUploadSize" value="10485760000" /> <!-- Maximum value in memory --> <property name="maxInMemorySize" value="40960" /> </bean> </beans>
log4j.properties
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://192.168.1.194:3306/test?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=root c3p0.pool.size.max=20 c3p0.pool.size.min=5 c3p0.pool.size.ini=3 c3p0.pool.size.increment=2
jdbc.properties
log4j.rootLogger=info, console, debug, app, error ###Console ###log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern = %d %p[%C:%L]- %m%n ### debug ###log4j.appender.debug = org.apache.log4j.DailyRollingFileAppender log4j.appender.debug.File = log/debug.log log4j.appender.debug.Append = true log4j.appender.debug.Threshold = DEBUG log4j.appender.debug.DatePattern='.'yyyy-MM-dd log4j.appender.debug.layout = org.apache.log4j.PatternLayout log4j.appender.debug.layout.ConversionPattern = %d %p[%c:%L] - %m%n ### app ### log4j.appender.app = org.apache.log4j.DailyRollingFileAppender log4j.appender.app.File = log/app.log log4j.appender.app.Append = true log4j.appender.app.Threshold = INFO log4j.appender.app.DatePattern='.'yyyy-MM-dd log4j.appender.app.layout = org.apache.log4j.PatternLayout log4j.appender.app.layout.ConversionPattern = %d %p[%c:%L] - %m%n ### Error #### log4j.appender.error = org.apache.log4j.DailyRollingFileAppender log4j.appender.error.File = log/error.log log4j.appender.error.Append = true log4j.appender.error.Threshold = ERROR log4j.appender.error.DatePattern='.'yyyy-MM-dd log4j.appender.error.layout = org.apache.log4j.PatternLayout log4j.appender.error.layout.ConversionPattern =%d %p[%c:%L] - %m%n
5. Use MyBatis Generator to automatically create entity classes, mapping files and DAO interfaces
MyBatis belongs to a semi-automatic ORM framework, so its main job is to configure Mapping mapping files. However, since handwritten mapping files are prone to errors, the MyBatis generator can be used to automatically generate entity classes, DAO interfaces and Mapping mapping files. This saves a lot of effort and copy the generated code into the project.
Generate the files and jars required for the code and create the following directory structure:
Configure the relevant database connection in generatorl.xml, and the database table is already available:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!-- Database Driver--> <classPathEntry location="mysql-connector-java-5.1.34.jar" /> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true" /> <!-- Whether to remove the automatically generated comments true: Yes: false: No--> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--Database link URL, username, password--> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://192.168.1.194:3306/noc" userId="root" password="root"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- Generate the package name and location of the model --> <javaModelGenerator targetPackage="com.yingjun.test.model" targetProject="src"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- Generate the package name and location of the mapping file --> <sqlMapGenerator targetPackage="com.yingjun.test.mapping" targetProject="src"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- Generate the package name and location of the DAO--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.yingjun.test.dao" targetProject="src"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- The table to be generated is the table name in the database or the view name domainObjectName is the entity class name --> <table tableName="other_list" domainObjectName="OtherList" enableCountByExample="fasle" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" > </table> </context> </generatorConfiguration>
Open the CMD window and enter the directory structure and enter the command line:
java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite
After the run is completed, the corresponding dao mapper and model will be generated. Isn't it very good?
6. Establish the Service layer and the Controller layer
package com.yingjun.test.service; public interface OtherServiceI { public String getOterList(); } package com.yingjun.test.service; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import com.yingjun.test.dao.OtherListMapper; import com.yingjun.test.model.OtherList; import com.yingjun.test.model.OtherListDomain; @Service public class OtherServiceImpl implements OtherServiceI { @Autowired private OtherListMapper otherListMapper; @Override public String getOterList() { Set<String> set=new HashSet<String>(); List<OtherList> list=otherListMapper.selectAll(); List<OtherListDomain> jsonList=new ArrayList<OtherListDomain>(); for(OtherList other:list){ String title=other.getTitle(); if(set.contains(title)){ continue; }else{ List<OtherList> t_list=new ArrayList<OtherList>(); for(OtherList data:list){ if(title.equals(data.getTitle())){ t_list.add(data); } } OtherListDomain domain=new OtherListDomain(); domain.setTitle(title); domain.setItems(t_list); jsonList.add(domain); set.add(other.getTitle()); } } return JSON.toJSONString(jsonList, SerializerFeature.WriteMapNullValue); } } package com.yingjun.test.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSON; import com.yingjun.test.service.OtherServiceI; import com.yingjun.test.service.StockStatusServiceI; @Controller @RequestMapping(value = "/") public class TSSController { @Autowired private OtherServiceI otherService; @RequestMapping(value="/getOtherList",produces="text/html;charset=UTF-8" ) @ResponseBody private String getOtherList(){ String json=otherService.getOterList(); return json; } } 7. Create a test class
import java.util.List; import org.apache.log4j.LogManager; 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.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring.xml"}) public class TestMybatis { @Autowired private OtherServiceI service; @Test public void test() { String list=service.getOterList(); logger.info(list); } }8. Verify through the browser
http://localhost:8080/TzyjStateService/getOtherList
At this point, the test was successful and the integration of the three major SSM frameworks was completed. If you have any other needs, you can continue to add them on this basis.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.