IDEA uses maven to build SSM framework integration project (super detailed, worth a visit)

catalogue

reminder

This article is a long one. I believe that after reading this article, you will at least get twice the result with half the effort. It is impeccable. Please read it patiently. 😀

Super detailed!

dried food! dried food! dried food!

Briefly introduce SSM

SSM (Spring + spring MVC + MyBatis), a more mainstream enterprise architecture scheme at present. The standard MVC design pattern divides the whole system into four layers: display layer, Controller layer, Service layer and Dao layer. Spring MVC is used to forward requests and manage views. Spring realizes business object management, and MyBatis is used as the data object persistence engine.

Construction process

1, Frame introduction

  • Spring

    Spring is an open source framework created by Rod Johnson. It is created to solve the complexity of enterprise application development. Spring uses basic JavaBean s to do things that previously could only be done by EJB s. However, the use of spring is not limited to server-side development. From the perspective of simplicity, testability and loose coupling, any Java application can benefit from spring. Simply put, spring is a lightweight inversion of control (IoC) and aspect oriented (AOP) container framework.

  • SpringMVC

    Spring MVC is a lightweight web framework based on Java that implements the request driven type of MVC design pattern. It uses the idea of MVC architecture pattern to decouple the responsibilities of the web layer. Request driven refers to the use of request response model. The purpose of the framework is to help us simplify development.

  • MyBatis

    MyBatis is an excellent persistence layer framework, which supports customized SQL, stored procedures and advanced mapping. MyBatis avoids almost all JDBC code and manually setting parameters and getting result sets. MyBatis can use simple XML or annotations to configure and map native information, and map interfaces and Java POJOs (plain ordinary Java objects) into records in the database.

2, Download Maven

  • Download address :

    https://maven.apache.org/download.cgi

  • Unzip the downloaded installation package. I unzip the installation package in my directory. After unzipping, I create the Maven repository directory of the local warehouse.

  • Modify the maven configuration file, enter the maven folder directory just extracted, enter conf, and use the editor to open settings XML file, I use BBEdit here, and EditPlus can be used for window

  • After opening, configure the local warehouse path instead of the default maven warehouse. Configure the maven warehouse to download the domestic image source, otherwise the download is particularly slow, and sometimes the download of jar package fails, as shown in the following figure. Modify the path corresponding to your computer.

  • maven warehouse Path

<localRepository>/Users/wht/maven/mavenrepository</localRepository>
  • Alibaba's image warehouse
<!-- Configuring alicloud's image warehouse can improve jar Download speed of package -->   
  <mirror>
     <id>alimaven</id>
     <name>aliyun maven</name>
     <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
     <mirrorOf>central</mirrorOf>        
  </mirror>

  • The download and configuration of maven are completed. Next, let's create the project.

3, Create Maven project

  • First open IDEA and click Create New Project

  • Find Maven and click Next

  • Fill in the corresponding information. Groupid is the unique identifier of the project organization and actually corresponds to the package structure of JAVA.

    Artifactid is the unique identifier of the project. The actual name of the corresponding project is the name of the project root directory.

  • After filling in, click Next directly

  • Continue to click Finish

  • Next, the completed project directory is displayed in front of us. You will find that there is no webapp in it.

  • Next, because we are creating maven project, we need to configure maven warehouse in IDEA. The interface of MacBook I use may be a little different from that of Windows, but the interface is functional. Click IntelliJ IDEA in the upper left corner to find Preferences, Click to enter

  • Enter the upper left corner of the setting interface to search 🔍 maven, enter the maven setting interface

  • be careful ⚠️ If you have to download maven

  • Next, click the ellipsis behind the yellow box area Find the maven folder downloaded from your computer, select it and click OK.

  • At this time, you can see the following figure. It has been set successfully, and my maven warehouse path will change accordingly. Because I configured my own settings XML file.

  • Next, we modify maven's default settings in IDEA The XML configuration file is your own local configuration file, which can be modified according to the operation steps in the figure.

  • Next, the project of idea needs to be manually configured. The MacBook I use may have a slightly different interface from Windows, but the interface is functional. Click File in the upper left corner to find Project Structure Click to enter project configuration

  • Click Project and select the JDK of your computer. I use jdk1 here 8. Select 8 - Lambdas

  • Next, configure Modules, click Modules, click your own project, and then click the "+" sign to pull down to find the Web.

  • Next, configure the Web, click the path under Deployment Descriptors, select it, and click the modify icon

  • Next, change the path to the path shown below and click OK

  • After modification, you will see that the above path has been modified successfully. Next, click the web resource directories icon below

  • Similarly, change the original path to the path shown in the figure below, and click OK

  • After the modification, you will see the following screen. See the yellow exclamation icon below and click create artificet in the lower right corner. Web expanded is automatically added to the Artifacet

  • Next, click Apply and click OK.

  • Return to the editing interface, as shown in the following figure. Compared with the screenshot of the newly created project, there are more webapp folders here, with a small blue circle and web XML, indicating that the creation was successful.

  • Screenshot of the newly created project

  • Screenshot of the configured project

4, Jar package to be introduced for Maven project

  • pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.top</groupId>
    <artifactId>ssmDemo</artifactId>
    <version>1.0-SNAPSHOT</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>
		

		<!--introduce pageHelper Paging plug-in PageInfo -->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>5.0.0</version>
		</dependency>

		

		<!-- springwebmvc -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- return json String support -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.8.8</version>
		</dependency>

		<!-- Spring integration Jdbc -->

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!--Spring-test spring Test package -->

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>


		<!-- Spring Aspect oriented programming -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!--MyBatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>

		<!-- MyBatis integration Spring Adaptive package for -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>${mybatisspring.version}</version>
		</dependency>

		<!-- Alibaba data source druid -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.10</version>
		</dependency>

		<!-- mysql Driver package -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.41</version>
		</dependency>

		<!-- servlet api package -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>


		<!-- junit Test package -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>

		<!-- Log package -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
		</dependency>

		<!-- excel Batch import and export -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.9</version>
		</dependency>

		<!-- Alibaba fastjson json and java Quick conversion kit -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.47</version>
		</dependency>

		<dependency>
			<groupId>org.jetbrains</groupId>
			<artifactId>annotations</artifactId>
			<version>RELEASE</version>
			<scope>compile</scope>
		</dependency>

	</dependencies>
	<build>
		<finalName>ssmDemo</finalName>
	</build>
</project>

5, Integrate SSM framework, relevant required configuration files and configuration items

  • web.xml

    Modify the web under WEB-INF under webapp xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
		  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
           version="3.0">
    
    <!--  spring -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:/spring/beans_core.xml</param-value>
    </context-param>
    <!--  Listen to whether there are abnormal problems in the loaded configuration file -->
    <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> 


    <!--  Front end controller -->
    <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/springmvc.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- spring A character encoding filter is provided 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>


    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>


</web-app>

  • Spring configuration file

    I call it beans_core.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/context"
		xmlns:aop="http://www.springframework.org/schema/aop"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="
			http://www.springframework.org/schema/context 
			http://www.springframework.org/schema/context/spring-context-3.2.xsd
			http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
			http://www.springframework.org/schema/mvc 
			http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
			http://www.springframework.org/schema/aop 
			http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
			http://www.springframework.org/schema/tx 
			http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">


	<!-- Enable annotation mode -->
	 <context:annotation-config/>
	<!-- Scan annotation package -->
	<context:component-scan base-package="com.top.*"></context:component-scan>

	<!-- Database connection pool object -->
	<context:property-placeholder
		location="classpath:jdbc.properties"></context:property-placeholder>
	<!-- Ali druid Database connection pool -->
	<bean id="dataSource"
		class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
		<!-- Basic database information configuration -->
		<property name="url" value="${url}" />
		<property name="username" value="${jdbc_username}" />
		<property name="password" value="${jdbc_password}" />
		<property name="driverClassName" value="${driverClassName}" />
		<property name="filters" value="${filters}" />
		<!-- Maximum concurrent connections -->
		<property name="maxActive" value="${maxActive}" />
		<!-- Number of initialization connections -->
		<property name="initialSize" value="${initialSize}" />
		<!-- Configure the timeout time for getting connections -->
		<property name="maxWait" value="${maxWait}" />
		<!-- Minimum number of free connections -->
		<property name="minIdle" value="${minIdle}" />
		<!-- How often is the configuration interval detected? Idle connections that need to be closed are detected in milliseconds -->
		<property name="timeBetweenEvictionRunsMillis"
			value="${timeBetweenEvictionRunsMillis}" />
		<!-- Configure the minimum lifetime of a connection in the pool, in milliseconds -->
		<property name="minEvictableIdleTimeMillis"
			value="${minEvictableIdleTimeMillis}" />
		<property name="validationQuery" value="${validationQuery}" />
		<property name="testWhileIdle" value="${testWhileIdle}" />
		<property name="testOnBorrow" value="${testOnBorrow}" />
		<property name="testOnReturn" value="${testOnReturn}" />
		<property name="maxOpenPreparedStatements"
			value="${maxOpenPreparedStatements}" />
		<!-- open removeAbandoned function -->
		<property name="removeAbandoned" value="${removeAbandoned}" />
		<!-- 1800 Seconds, that is, 30 minutes -->
		<property name="removeAbandonedTimeout"
			value="${removeAbandonedTimeout}" />
		<!-- close abanded Output error log when connecting -->
		<property name="logAbandoned" value="${logAbandoned}" />
	</bean>


	<!-- spring integration mybatis Tool classes used -->
	<bean id="sqlSessionFactory"
		class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<!-- Scan the files in our directory mapper.xml file -->
		<property name="mapperLocations"
			value="classpath:mybatis/mapper/*.xml"></property>
		<!-- load mybatis Configuration file for -->
		<property name="configLocation"
			value="classpath:mybatis/sqlMapConfig.xml"></property>
		<!-- introduce pagehelper Paging plug-in -->
		<property name="plugins">
			<array>
				<bean class="com.github.pagehelper.PageInterceptor">
					<property name="properties">
						<value>
							helperDialect=mysql
							reasonable=true
							supportMethodsArguments=true
							params=count=countSql
							autoRuntimeDialect=true
						</value>
					</property>
				</bean>
			</array>
		</property>
	</bean>

	<!-- Load our mapper xml and mapper Interface -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

		<property name="basePackage" value="com.top.mapper"></property>
	</bean>

	<!--<import resource="classpath:beans_transaction.xml"></import> -->
	<!--<bean name="customerController" class ="com.ujiuye.cus.controller.CustomerController"></bean> -->


	<!-- introduce spring Transaction management provided -->
	<bean id="tm"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

	<!-- transaction-manager: Value is spring Of the transaction manager provided id value -->
	<tx:advice id="myadvice" transaction-manager="tm">
		<tx:attributes>
			<tx:method name="add*" isolation="READ_COMMITTED"
				propagation="REQUIRED" />
			<tx:method name="save*" isolation="READ_COMMITTED"
				propagation="REQUIRED" />
			<tx:method name="delete*" isolation="READ_COMMITTED"
				propagation="REQUIRED" />
			<tx:method name="update*" isolation="READ_COMMITTED"
				propagation="REQUIRED" />
			<tx:method name="drop*" isolation="READ_COMMITTED"
				propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>



	<aop:config>
		<aop:pointcut
			expression="execution(* com.top.service.*(..))" id="pt" />
		<aop:advisor advice-ref="myadvice" pointcut-ref="pt" />
	</aop:config>

</beans>
  • Spring MVC configuration file

    I name it 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:mvc="http://www.springframework.org/schema/mvc"
		xmlns:context="http://www.springframework.org/schema/context"
		xmlns:aop="http://www.springframework.org/schema/aop"
		xmlns:tx="http://www.springframework.org/schema/tx"
		xsi:schemaLocation="
			http://www.springframework.org/schema/context 
			http://www.springframework.org/schema/context/spring-context-3.2.xsd
			http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
			http://www.springframework.org/schema/mvc 
			http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
			http://www.springframework.org/schema/aop 
			http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
			http://www.springframework.org/schema/tx 
			http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

	<context:annotation-config />
	<!-- Which packages are scanned -->
	<context:component-scan base-package="com.top.*" />


	<bean name="conversionService"
		class="org.springframework.context.support.ConversionServiceFactoryBean">
		<property name="converters">
			<set>
				<bean class="com.top.util.DateConvertor"></bean>
				<bean class="com.top.util.MyTrimString"></bean>
			</set>
		</property>
	</bean>


	<!-- open springmvc Annotation operations for -->
	<mvc:annotation-driven
		conversion-service="conversionService" />

	<!-- take dispatcherServlet Requests that cannot be processed are pushed to the default servlet implement -->
	<mvc:default-servlet-handler />

	
	
	<!-- view resolver  -->
	<bean
			class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>


</beans>

Instead of writing data access object (DAO) code manually using SqlSessionDaoSupport or SqlSessionTemplate, mybatis spring provides an implementation of dynamic proxy: MapperFactoryBean. This class allows you to directly inject the data mapper interface into your service layer bean. When using mappers, you can just call them like calling your Dao, but you don't need to write any code for Dao implementation, because mybatis spring will create a proxy for you.

  • MyBatis profile

    I name it sqlmapconfig 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>

  • Log profile
    log4j.properties
# Global logging configuration\uff0c\u5efa\u8bae\u5f00\u53d1\u73af\u5883\u4e2d\u8981\u7528debug
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

  • Database configuration file
    jdbc.properties
url:jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8 
driverClassName:com.mysql.jdbc.Driver
jdbc_username:root
jdbc_password:123
       
filters:stat
   
maxActive:20
initialSize:1
maxWait:60000
minIdle:10
maxIdle:15
   
timeBetweenEvictionRunsMillis:60000
minEvictableIdleTimeMillis:300000
   
validationQuery:SELECT 'x'
testWhileIdle:true
testOnBorrow:false
testOnReturn:false

maxOpenPreparedStatements:20
removeAbandoned:true
removeAbandonedTimeout:1800
logAbandoned:true


  • All configuration files have been configured, and the project directory is shown in the figure below.

6, Importing Jar package and configuring tomcat project

  • Next, click File in the upper left corner to find Project Structure Click to enter the project configuration, find Libraries, enter the view, and you will find your POM The maven jar package imported by XML has been downloaded.

  • Continue to click on Artifacts and you will find Available There are also maven jar packages

  • Next, look at the operation steps in the figure

  • Right click the ssmDemo folder and click Put into Output Root

  • At this time, you can see the changes shown in the figure below

  • Then, all the jar packages have been deployed in the lib directory of WEB-INF. next, click Apply and then click OK.

  • Next, let's configure tomcat, click OK, enter the editing area and click "Add Config..."

  • Click the Add icon ➕

  • Pull down to find Tomcat Server and select Local to enter the interface shown in the figure below.

  • Next, edit the tomcat configuration and configure it according to the operation steps in the figure.

  • At this time, observe that tomcat has been configured.

7, Reverse engineering using MyBatis (Generator)

  • MyBatis Generator can automatically create entity classes, Mapper mapping files and DAO interfaces

  • There are three kinds of reverse engineering of MyBatis: command line, eclipse Plug-in and maven plug-in.

  • I use the maven plug-in here

  • Both Eclipse and IDEA can be used. Let's use IDEA in the tutorial here

In POM Add plugin to XML

<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.2</version>
    <configuration>
        <configurationFile>src/main/resources/mybatis-generator/generatorConfig.xml</configurationFile>
        <verbose>true</verbose>
        <overwrite>true</overwrite>
    </configuration>
    <executions>
        <execution>
            <id>Generate MyBatis Artifacts</id>
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>
</plugin>
  • generatorConfig. The location of XML is Src / main / resources / mybatis generator / generatorconfig XML, you can adjust the path yourself.

  • generatorConfig.xml configuration file

<?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>
	
	<classPathEntry location="/Users/wht/maven/mavenrepository/mysql/mysql-connector-java/5.1.41/mysql-connector-java-5.1.41.jar"/>

	<context id="DB2Tables" targetRuntime="MyBatis3">
		

		<commentGenerator>
			<property name="suppressAllComments" value="true"></property>
		</commentGenerator>


		<!-- Set database connection -->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://localhost:3306/test"
			userId="root"
			password="root">
		</jdbcConnection>

		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<!-- generate bean Storage location -->
		<javaModelGenerator targetPackage="com.top.bean"
			targetProject="./src/main/java">
			<property name="enableSubPackages" value="true" />
			<property name="trimStrings" value="true" />
		</javaModelGenerator>

		<!-- Generated mapper File location -->
		<sqlMapGenerator targetPackage="com.top.mapper"
			targetProject="./src/main/java">
			<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>

		<!-- Generated mapper.xml The corresponding one mapper Storage location of interface -->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.top.mapper" targetProject="./src/main/java">
			<property name="enableSubPackages" value="true" />
		</javaClientGenerator>

		<!-- Set reverse generated table -->
		<table tableName="test"></table>


	</context>
</generatorConfiguration>
  • After configuration, see the figure below

  • Click mybatis generator: generate to automatically generate entity classes, Mapper mapping files and DAO interfaces, as shown in the following figure.

  • I'm used to reverse generated * * mapper The XML file is placed in the mapper folder under mybatis in the configuration file resources, as shown in the following figure.

  • The code generated by reverse engineering has been completed. Isn't it Nice 😄, Go and have a try

8, Establish Service layer and conrorller layer

Service layer interface

package com.top.service;

import com.top.bean.Test;

public interface TestService {
    
    Test login(String name, String password);
}

Service layer interface implementation class

package com.top.service;

import com.top.bean.Test;
import com.top.mapper.TestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TestServiceImpl implements TestService  {

    @Autowired
    private TestMapper testMapper;
    
    @Override
    public Test login(String name, String password) {
        return testMapper.login(name, password);
    }
}

Controller layer

package com.top.controller;

import com.alibaba.fastjson.JSON;
import com.top.bean.Test;
import com.top.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.Map;


@Controller
@RequestMapping("/test")
public class TestController {


    @Autowired
    private TestService testService;


    @RequestMapping("login")
    public String login(String name ,String password){
        Test login = testService.login(name, password);
        if (login != null ) {
            return "redirect:/index.jsp";
        } else {
            return "redirect:/login.jsp";
        }
    }


}

The database is created by ourselves. I won't create it in detail here. I simply wrote a login page here

Remember to create a database and change the database name of the database configuration file to the name you created

9, Run test

  • At this time, run tomcat and the browser will load automatically. If not, access the URL

  • http://localhost:8080/ssmDemo

  • You will see the following page, log in your name and password to verify login.

  • The project structure is as follows:

summary

So far, the whole SSM project has been perfectly integrated. If you have any needs, you can continue to write on this basis. If you need any questions, you can comment below. thank you 🙏

I hope it can help more scholars 💪, You can continue to learn a lot of follow-up articles 😁 Don't worry, there are more secrets and interesting code waiting for you to explore!

Share Hi, pass on virtue, point a star, and then the road of exploration will not be confused!

Scan the QR code on wechat, follow my original official account, and you can view the secrets of more programs!

Tags: Java

Posted by Eugene on Tue, 17 May 2022 08:33:50 +0300