This article mainly introduces the integration of Maven, Mybatis, and Spring MVC (pictures and texts) of Java framework construction. It is shared with you. The details are as follows:
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.
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 of control (IoC) and section-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 uses simple XML or annotations for configuration and raw mappings to map interfaces and Java to records in the database.
1. Download eclipse
Download http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/marsr
Choose the version you want
2. Create a new Maven project
Select File > New > Maven Project
You can see the following interface
Click Next to see the following interface. We select maven-archetype-webapp
Click Next to see. Group Id is the package name, and Artifact Id is the project name. Here we enter Group Id=com.cjt, Artifact Id=MyMaven.
Finally, click Finish to successfully create the project
3. Preparation before project operation
After creating a new project, you can see an error, which is caused by the build path and the failure to introduce the javaee package.
1) Set the build path
Right-click the project > Build Path --> Configure Build Path…
Then select Libraries
Maven selects a Library by default. This is wrong. Let's double-click this to edit.
In the following interface, we choose Alternate JRE or Workspace default JRE. Here we choose Alternate JRE.
2) Introduce javaee package
Introducing javaee package on pom.xml
<!-- Import java ee jar package --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency>
4. Project configuration file settings
1) Set pom.xml
We now set up pom.xml and download the jar package. This process may be a bit slow
Pom.xml:
<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.cjt</groupId> <artifactId>MyMaven</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>TestMaven01 Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring version number --> <spring.version>4.0.2.RELEASE</spring.version> <!-- mybatis version number --> <mybatis.version>3.2.6</mybatis.version> <!-- log4j log file management package version --> <slf4j.version>1.7.7</slf4j.version> <log4j.version>1.2.17</log4j.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- Import java ee jar package --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- spring core package --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</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-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis core package--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring package--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- Import java ee jar package --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> </dependency> <!-- Import Mysql database link jar package --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <!-- Import the jar package of dbcp to configure the database in applicationContext.xml --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- JSTL tag class --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- Log file management package --> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <!-- Format the object to facilitate log output--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <!-- Input JSON --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <!-- Upload component package --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency> </dependency> </build> <finalName>TestMaven01</finalName> </build></project>2) Create jdbc.properties
driver=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306/testusername=rootpassword=#Define initial connection number initialSize=1#Define maximum connection number maxActive=20#Define maximum idle maxIdle=20#Define minimum idle minIdle=1#Define maximum waiting time maxWait=60000
3) log4j.properties
### set log levels ####log4j.rootLogger = debug , stdout , D , Elog4j.rootLogger = debug , stdout , D### output to the console ###log4j.appender.stdout = org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target = System.outlog4j.appender.stdout.layout = org.apache.log4j.PatternLayout#log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE} %5p %c{ 1 }:%L - %m%nlog4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n### Output to the log file ###log4j.appender.D = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.D.File = ${springmvc.root}/WEB-INF/logs/log.loglog4j.appender.D.Append = truelog4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayoutlog4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n### Save exception information to separate file ###log4j.appender.D = org.apache.log4j.DailyRollingFileAppenderlog4j.appender.D.File = ${springmvc.root}/WEB-INF/logs/error.log log4j.appender.D.Append = truelog4j.appender.D.Threshold = ERROR log4j.appender.D.layout = org.apache.log4j.PatternLayoutlog4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n4) 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/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- Automatically scan the package so that SpringMVC thinks that the class annotated by @controller under the package is the controller --> <context:component-scan base-package="com.cjt.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> <!-- Start SpringMVC annotation function to complete the mapping of requests and annotations POJOs --> <bean > <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON converter--> </list> </property> </bean> <!-- Define the pre-suffix of the jumped file, view mode configuration--> <bean> <!-- My understanding of the configuration here is to automatically prefix and suffix the string returned by 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 the upload component package in the configuration file --> <bean id="multipartResolver" > <!-- Default encoding--> <property name="defaultEncoding" value="utf-8" /> <!-- Maximum file size --> <property name="maxUploadSize" value="10485760000" /> <!-- Maximum value in memory --> <property name="maxInMemorySize" value="40960" /> </bean> </beans>
5) spring-mybatis.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/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- Automatic scan --> <context:component-scan base-package="com.cjt.service" /> <!-- Introduce configuration files --> <bean id="propertyConfigurer" > <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- Initialize the connection size --> <property name="initialSize" value="${initialSize}"></property> <!-- Maximum number of connection pools--> <property name="maxActive" value="${maxActive}"></property> <!-- Maximum free connection pool --> <property name="maxIdle" value="${maxIdle}"></property> <!-- Minimum idle connection pool--> <property name="minIdle" value="${minIdle}"></property> <!-- Get the maximum connection waiting time--> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- Perfect integration of spring and MyBatis, no mybatis configuration mapping file--> <bean id="sqlSessionFactory"> <property name="dataSource" ref="dataSource" /> <!-- Automatic scanning of mapping.xml files--> <property name="mapperLocations" value="classpath:com/cjt/mapping/*.xml"></property> </bean> <!-- The package name where the DAO interface is located, Spring will automatically find the class under it --> <bean> <property name="basePackage" value="com.cjt.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (Transaction Management) transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" > <property name="dataSource" ref="dataSource" /> </bean> </beans>All the above files are created in the resources folder
5. Automatically generate database code
1) Create a new table
First, we create a new table user_t, and the fields are as follows:
2) Download package
Download packages include: mybatis-3.2.6.jar , mybatis-generator-core-1.3.3.jar, mysql-connector-java-5.1.39-bin.jar
3) Run - Automatically generate code
Create a new folder, including the following files
generatorConfig.xml is the xml file that generates the code, and the content is as follows:
<?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.39-bin.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://localhost:3306/test" userId="root" password=""> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- Generate the package name and location of the model --> <javaModelGenerator targetPackage="com.cjt.domain" 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.cjt.mapping" targetProject="src"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- Generate the package name and location of the DAO --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.cjt.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="user_t" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration>
Then we use the cmd command to enter the newly created folder and enter:
java -jar mybatis-generator-core-1.3.3.jar -configfile generatorConfig.xml -overwrite
Finally, the code is generated.
Note: The code is automatically generated here through the command line, and readers can also generate it through the eclipse plug-in.
6. Code start
Create a new package, as follows: (The arrows are all automatically generated codes above)
IUserService.java
public interface IUserService { public User getUserById(int id); }UserServiceImpl.java
@Servicepublic class UserServiceImpl implements IUserService { @Autowired private IUserDao userDao; public UserServiceImpl() { System.out.println("UserServiceImpl"); } public User getUserById(int id) { return userDao.selectByPrimaryKey(id); }}UserController.java
@Controller@RequestMapping("/user")public class UserController { public UserController() { System.out.println("UserController"); } @Resource private IUserService userService; @RequestMapping("/showUser") public String toIndex(HttpServletRequest request,Model model) { System.out.println("UserController showUser"); int id = Integer.parseInt(request.getParameter("id")); User user = userService.getUserById(id); model.addAttribute("user", user); return "showUser"; } }Create a new directory jsp under WEB-INF, and create a new file showUser.jsp below
showUser.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" import="java.util.*,com.cjt.domain.*"%><!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> ${user.userName}</body></html>Finally, attach 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/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" version="3.0"> <display-name>Archetype Created Web Application</display-name> <!-- Spring and mybatis configuration files --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <!-- Encoding filter--> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring listener--> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Prevent Spring memory from overflowing listener--> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- Spring MVC servlet --> <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> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <!-- Here you can configure *.do, corresponding to the suffix habit of struts--> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> </web-app>
Above, the code generation is complete.
Projects can be downloaded: https://github.com/cjt321/MavenSpirngmvcMybatis
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.