1. Preparation
- mysql database
- idea tool
Note: this time is to build an SSM framework. First of all, make sure that the computer is configured with jdks above 1.8 (because some jdks below 1.8 are not supported). It is inconvenient to use mysql database directly. You can install a visualization tool (such as SQLyog, Navicat). I use SQLyog here. We use maven to manage the construction projects. The detailed steps are as follows
2. Detailed steps
2.1 new project
(1) file -> new -> Project
(2) Select maven project, check Create from archetype, select maven's webapp template, click next, and then the name of the project will be displayed. The next step will be finished. I won't expand here
2.2 create some necessary configuration files
(1) The overall structure of the project as well as several necessary xml files and properties files are placed in resources. If the automatically generated template does not contain some files, you can create them yourself. If it is special, remember to select the corresponding files, right-click and select one of them Mark Directory as changes the type of file.
2.3 import corresponding dependencies
Open the pom.xml file for the project
The internal dependencies and plug-in codes are as follows. Since there are many, they are not explained one by one. Most of the codes have corresponding notes. After that, we can reload the maven project in order to download these packages from the remote maven warehouse to our project.
<?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.shao</groupId> <artifactId>LibraryManagement</artifactId> <version>1.0</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <!--spring rely on--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.15.RELEASE</version> </dependency> <!--springMVC Correlation dependency--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.2.15.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.15.RELEASE</version> </dependency> <!-- mysql drive --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> <!-- servlet rely on --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- jsp rely on --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.2.1</version> </dependency> <!-- spring Transaction dependency --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.2.15.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.15.RELEASE</version> </dependency> <!--mybatis Dependence of--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <!-- mybatis and spring Integration dependency --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <!-- mybatis Log of--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.30</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <!-- mysql drive --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> <!-- introduce lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> </dependency> <!-- Ali connection pool --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.6.1</version> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.6.1</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory><!--Directory--> <includes> <!--Including the.properties.xml All files will be scanned--> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory><!--Directory--> <includes> <include>**/*</include> </includes> </resource> </resources> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/</path> <port>8080</port> <uriEncoding>UTF-8</uriEncoding> </configuration> </plugin> </plugins> </build> </project>
Select the project we built, right click - > Maven - > reload project, wait a moment, and then all the dependencies are not red, indicating that our dependencies have been downloaded.
2.4 configure the configuration files of spring, mybatis, spring MVC, web and jdbc
The spring configuration file is called applicationContext.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:jdbc.properties"/> <!--Declare data source DataSource--> <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${database.url}"/> <property name="username" value="${database.username}"/> <property name="password" value="${database.password}"/> </bean> <!--statement SqlSessionFactoryBean,Inside this class, create SqlSessionFactory--> <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--specify data source--> <property name="dataSource" ref="myDataSource"/> <!--appoint mybatis Master profile resource Can be used directly value assignment --> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--appoint SqlSessionFactory Name of--> <property name="sqlSessionFactoryBeanName" value="factory"/> <!--Specify the base package, Dao Package name of the interface--> <property name="basePackage" value="com.shao.dao"/> </bean> <bean id="TestService" class="com.shao.service.impl.TestServiceImpl"> <property name="testDao" ref="testDao"/> </bean> </beans>
The JDBC configuration file is called jdbc.properties , The url here is configured according to its own database name. For example, my database here is called library management My database user name is root and my password is 1363890363. These are configured according to your own database name and user password
database.driver=com.mysql.jdbc.Driver database.url=jdbc:mysql://localhost:3306/librarymanagement database.username=root database.password=1363890363
The configuration file of mybatis is called mybatis-config.xml , There are many notes and configurations here. If you are interested, you can search and have a look
<?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> <!--introduce jdbc.properties configuration file--> <properties resource="jdbc.properties"/> <settings> <!--Configure running sql Print out on console--> <setting name="logImpl" value="STDOUT_LOGGING"/> <!--Set mapping method autoMappingBehavior attribute NONE: Do not map automatically PARTIAL: By default, no nested result sets are automatically mapped FILL: Automatically map all result sets. Generally, if there are result sets, we also use them ReaultMap,therefore FULL Rarely used --> <setting name="autoMappingBehavior" value="PARTIAL"/> <!--Hump mapping After hump mapping is enabled: for example, in the database field nick_name,stay PO The attribute in is nickName It can also be automatically matched( mybatis Automatically change underline to hump type) --> <setting name="mapUnderscoreToCamelCase" value="true"/> <!--Define alias--> <!--Turn on the switch of delayed loading. The default is false --> <setting name="lazyLoadingEnabled" value="true"/> <!-- <!–When delayed loading occurs, the default is whether to load completely false (3.1.4 After version) Generally, it is not configured. You can use the default–> <setting name="aggressiveLazyLoading" value="true"/>--> </settings> <typeAliases> <package name="com.saho.po"/> </typeAliases> <!--Injection mapper--> <mappers> <!--Package of mapper--> <package name="com.shao.dao"/> </mappers> </configuration>
The configuration file of spring MVC is called pring-mvc.xml , The static resource spring here is turned off by default. I've been stuck for a long time when configuring myself. You can pay attention to it
<?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: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.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- Automatic registration component --> <mvc:annotation-driven /> <!--Scanner--> <context:component-scan base-package="com.shao.controller"/> <!--Turn on static resources--> <mvc:resources location="/jsp" mapping="/**"/> </beans>
The web.xml file is the configuration file generated by the web project itself, as follows
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <!--Configure global filtering filter--> <filter> <filter-name>CharacterEncodingFilter</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> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--to configure springMVC Front end controller--> <servlet> <servlet-name>DispatcherServlet</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>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <!-- contextConfigLocation: The name is fixed, indicating custom spring Path to configuration file --> <param-name>contextConfigLocation</param-name> <!-- Path to custom profile --> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
OK, so far, our basic configuration has been completed. It may feel more and cumbersome to write in the past few times. In fact, these things can be written before copy ing. Just change some configurations.
Here's a point because the configuration file involves packages in the project. If the name is different from mine, you should change some package names in the corresponding configuration file, otherwise an error will be reported
2.5 build corresponding class interfaces and mapped xml files
TestController.java in controller package
package com.shao.controller; import com.shao.po.Test; import com.shao.service.TestService; 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.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import java.io.IOException; @Controller @RequestMapping("/Test") public class TestController { @Autowired private TestService testService; @RequestMapping("/add") public ModelAndView addOneTest(Test test){ ModelAndView modelAndView = new ModelAndView(); testService.addTest(test); System.out.println("addTest Method execution completed"); modelAndView.setViewName("/OK.jsp"); return modelAndView; } }
In dao package Testdao.java (Interface) Interface and TestDao.xml. The names of the two files must be the same
package com.shao.dao; import com.shao.po.Test; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Component; @Component public interface TestDao { /** * Add a test * @param test * @return */ int addTest(Test test); }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.shao.dao.TestDao"> <insert id="addTest" parameterType="com.shao.po.Test" useGeneratedKeys="true" keyProperty="id"> insert into test values (null,#{name},#{age}) </insert> </mapper>
Test.java in PO entity class package This part uses lombok annotation @ Data @Builder @All... @No.. To generate get set method, Builder method, all parameter constructor and no parameter constructor respectively
package com.shao.po; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @AllArgsConstructor @NoArgsConstructor public class Test { /** * Self increasing id */ private Integer id; /** * full name */ private String name; /** * Age */ private Integer age; }
The service package has an interface TestService interface and an implementation class impl package TestServiceImply.java
package com.shao.service; import com.shao.po.Test; public interface TestService { int addTest(Test test); }
package com.shao.service.impl; import com.shao.dao.TestDao; import com.shao.po.Test; import com.shao.service.TestService; public class TestServiceImpl implements TestService { private TestDao testDao; public void setTestDao(TestDao testDao) { this.testDao = testDao; } @Override public int addTest(Test test) { int row = testDao.addTest(test); return row; } }
The database is a very simple test table, with the structure shown in the figure below