Java - Manual build SSM (Maven)

Posted by harrylt on Fri, 16 Aug 2019 06:40:47 +0200

I. Environmental deployment

  • Operating System: Windows 10 Professional Edition
  • jdk:1.8.0_144
  • IDE: eclipse-oxygen
  • Server: tomcat 9.0
  • Database: mysql 5.7.18
  • Maven: 3.54

"If you want to do a good job, you must first use your tools." The environment must be built in advance.

II. New Maven Project

In the menu bar, click File-New-Maven Project in turn

Select maven-archetype-webapp and click next.

Fill in Group Id,Artifact Id,Package, click Finish, and wait a moment.

The project has been created here, but there is a red fork on the project node (figure below), and Markers reported that the parent class HttpServlet could not be found. Let's solve this problem.

 

Add a running environment to the project, right-click on the project node, and then click Build Path-Configure Build Path in turn. Open Java Build Path, switch to the Libraries tab, click the Add Library button, select Server Runtime in Add Library and click Next;

If there is no problem with the configuration, the server runtime that has been added is listed, Tomcat that has already been set up is selected, and then Finish is clicked.

 

You can see that Apache Tomcat has been added, and other options are left out for the time being. I'll talk about them later. Click apply and close application and close the interface.

In case of problems, we resynchronize the version information in the menu, click Window-Show View-Navigator in turn, and open Navigator.

 

Jump to the Navigator tab, open org.eclipse.jdt.core.prefs under the. settings folder, change the parameters in the red box to the data shown in the figure, and save the file.

 

Open org.eclipse.wst.common.component, change the parameters in the red box to the data shown in the figure, and save the file.

Open org.eclipse.wst.common.project.facet.core.xml, change the parameters in the red box to the data shown in the figure, and save the file.  

Delete the contents of the red box in the web.xml (mentioned later refers to the file in the image directory) as shown in the figure directory, and the warning information will be ignored for the time being.

Modify JRE System Library to JavaSE-1.8.

Open pom.xml under the project root node and add the following code.

 1 <build>
 2         <plugins>
 3             <plugin>
 4                 <groupId>org.apache.maven.plugins</groupId>
 5                 <artifactId>maven-compiler-plugin</artifactId>
 6                 <version>3.0</version>
 7                 <configuration>
 8                     <!-- Appoint source and target Version of _____________ -->
 9                     <source>1.8</source>
10                     <target>1.8</target>
11                 </configuration>
12             </plugin>
13         </plugins>
14     </build>

Right-click on the project node, click Maven-Update Project in turn, check the current project, and click the OK button. Wait a moment, the red fork in the project should disappear. If it doesn't disappear, go through all the previous steps in detail and look at the mistakes in Markers.

Open the pom.xml file in the project root directory and add the necessary dependencies, as shown below.

  1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3     <modelVersion>4.0.0</modelVersion>
  4     <groupId>cn.stevengo</groupId>
  5     <artifactId>ssm-test</artifactId>
  6     <packaging>war</packaging>
  7     <version>0.0.1-SNAPSHOT</version>
  8     <name>ssm-test Maven Webapp</name>
  9     <url>http://maven.apache.org</url>
 10     <dependencies>
 11         <dependency>
 12             <groupId>org.springframework</groupId>
 13             <artifactId>spring-webmvc</artifactId>
 14             <version>4.3.13.RELEASE</version>
 15         </dependency>
 16         <dependency>
 17             <groupId>org.springframework</groupId>
 18             <artifactId>spring-context</artifactId>
 19             <version>4.3.13.RELEASE</version>
 20         </dependency>
 21         <!--spring control module -->
 22         <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
 23         <dependency>
 24             <groupId>org.springframework</groupId>
 25             <artifactId>spring-aspects</artifactId>
 26             <version>4.3.13.RELEASE</version>
 27         </dependency>
 28         <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
 29         <dependency>
 30             <groupId>org.springframework</groupId>
 31             <artifactId>spring-jdbc</artifactId>
 32             <version>4.3.13.RELEASE</version>
 33         </dependency>
 34         <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
 35         <dependency>
 36             <groupId>org.springframework</groupId>
 37             <artifactId>spring-test</artifactId>
 38             <version>4.3.13.RELEASE</version>
 39             <scope>test</scope>
 40         </dependency>
 41 
 42         <!-- mybatis -->
 43         <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
 44         <dependency>
 45             <groupId>org.mybatis</groupId>
 46             <artifactId>mybatis</artifactId>
 47             <version>3.4.5</version>
 48         </dependency>
 49         <!-- mybatis integration spring The adapter package of the -->
 50         <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
 51         <dependency>
 52             <groupId>org.mybatis</groupId>
 53             <artifactId>mybatis-spring</artifactId>
 54             <version>1.3.1</version>
 55         </dependency>
 56         <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
 57         <dependency>
 58             <groupId>org.mybatis.generator</groupId>
 59             <artifactId>mybatis-generator-core</artifactId>
 60             <version>1.3.5</version>
 61         </dependency>
 62 
 63         <!-- Database connection pool -->
 64         <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
 65         <dependency>
 66             <groupId>com.mchange</groupId>
 67             <artifactId>c3p0</artifactId>
 68             <version>0.9.5.2</version>
 69         </dependency>
 70         <!-- Database Driver -->
 71         <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
 72         <dependency>
 73             <groupId>mysql</groupId>
 74             <artifactId>mysql-connector-java</artifactId>
 75             <version>5.1.40</version>
 76         </dependency>
 77         <!-- jstl -->
 78         <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
 79         <dependency>
 80             <groupId>javax.servlet</groupId>
 81             <artifactId>jstl</artifactId>
 82             <version>1.2</version>
 83         </dependency>
 84         <!-- servlet api -->
 85         <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
 86         <dependency>
 87             <groupId>javax.servlet</groupId>
 88             <artifactId>javax.servlet-api</artifactId>
 89             <version>4.0.0</version>
 90         </dependency>
 91         <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
 92         <dependency>
 93             <groupId>com.alibaba</groupId>
 94             <artifactId>fastjson</artifactId>
 95             <version>1.2.28</version>
 96         </dependency>
 97 
 98         <!-- junit -->
 99         <!-- https://mvnrepository.com/artifact/junit/junit -->
100         <dependency>
101             <groupId>junit</groupId>
102             <artifactId>junit</artifactId>
103             <version>4.12</version>
104             <scope>test</scope>
105         </dependency>
106     </dependencies>
107     <build>
108         <plugins>
109             <plugin>
110                 <groupId>org.apache.maven.plugins</groupId>
111                 <artifactId>maven-compiler-plugin</artifactId>
112                 <version>3.0</version>
113                 <configuration>
114                     <!-- Appoint source and target Version of _____________ -->
115                     <source>1.8</source>
116                     <target>1.8</target>
117                 </configuration>
118             </plugin>
119         </plugins>
120     </build>
121 </project>

Modify the information of web.xml, add spring container, front-end controller, character encoding controller and so on. Modify the code as follows.

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app  version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"  
 3                         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4                         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 5                                             http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 6      <!-- start-up spring Container -->   
 7      <context-param>
 8         <param-name>contextConfigLocation</param-name>
 9         <param-value>classpath:applicationContext.xml</param-value>
10      </context-param>
11      <listener>
12         <listener-class>
13             org.springframework.web.context.ContextLoaderListener
14         </listener-class>
15      </listener>
16    <!-- Spring MVC Front-end controller -->
17     <servlet>
18         <servlet-name>springMVC</servlet-name>
19         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
20         <init-param>
21             <param-name>contextConfigLocation</param-name>
22             <param-value>classpath:SpringMVC-servlet.xml</param-value>
23         </init-param>
24         <load-on-startup>1</load-on-startup>
25     </servlet>
26 
27     <servlet-mapping>
28         <servlet-name>springMVC</servlet-name>
29         <url-pattern>/</url-pattern>
30     </servlet-mapping>
31     <!-- Character Coding Filter -->
32     <filter>
33         <filter-name>characterEncodingFilter</filter-name>
34         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
35         <init-param>
36             <param-name>encoding</param-name>
37             <param-value>utf-8</param-value>
38         </init-param>
39         <init-param>
40             <param-name>forceRequestEncoding</param-name>
41             <param-value>true</param-value>
42         </init-param>
43         <init-param>
44             <param-name>forceResposeEncoding</param-name>
45             <param-value>true</param-value>
46         </init-param>
47     </filter>
48     <filter-mapping>
49         <filter-name>characterEncodingFilter</filter-name>
50         <url-pattern>/*</url-pattern>
51     </filter-mapping>
52     <!-- Use rest Stylistic URI -->
53     <filter>
54         <filter-name>HiddenHttpMethodFilter</filter-name>
55         <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
56     </filter>
57     <filter-mapping>
58         <filter-name>HiddenHttpMethodFilter</filter-name>
59         <url-pattern>/*</url-pattern>
60     </filter-mapping>
61     <display-name>Archetype Created Web Application</display-name>
62 
63 </web-app>

Create a new file named applicationContext.xml in src main resources directory. (Note: File name does not have to be this, depending on personal habits, file name and file path are related to configuration in web.xml). Add the following code, and note that the package name in the code is changed to set. At the same time, a folder named mapper is created under this directory to save the database mapping files.

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 4     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 6                            http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
 7                            http://www.springframework.org/schema/context 
 8                            http://www.springframework.org/schema/context/spring-context-4.3.xsd
 9                            http://www.springframework.org/schema/mvc
10                            http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
11                            http://www.springframework.org/schema/aop
12                            http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
13                            http://www.springframework.org/schema/tx
14                            http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
15     <context:component-scan base-package="cn.stevengo">
16         <context:exclude-filter type="annotation"
17             expression="org.springframework.stereotype.Controller" />
18     </context:component-scan>
19     <!--sping Configuration files and business logic related -->
20     <context:property-placeholder location="classpath:jdbc.properties" />
21     <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
22         <property name="jdbcUrl" value="${jdbc.url}"></property>
23         <property name="driverClass" value="${jdbc.driver}"></property>
24         <property name="user" value="${jdbc.user}"></property>
25         <property name="password" value="${jdbc.password}"></property>
26     </bean>
27     <!-- Configuration and mybatis Integration -->
28 
29     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
30         <!-- Appoint mybatis Location of global configuration files -->
31         <property name="configLocation" value="classpath:mybatis-config.xml"></property>
32         <property name="dataSource" ref="pooledDataSource"></property>
33         <!-- Appoint mybatis mapper Location of files -->
34         <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
35     </bean>
36     <!-- Configure Scanner -->
37     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
38         <!-- Scanning dao Implementation of the interface, added to the container -->
39         <property name="basePackage" value="cn.stevengo.ssmtest.dao"></property>
40     </bean>
41     <bean id="transactionManager"
42         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
43         <property name="dataSource" ref="pooledDataSource"></property>
44     </bean>
45     <!-- Open annotation-based transactions -->
46     <aop:config>
47         <!-- Pointcut expression -->
48         <aop:pointcut expression="execution(* cn.stevengo.ssmtest.service..*(..))"
49             id="txPoint"></aop:pointcut>
50         <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint" />
51     </aop:config>
52     <!-- Configuration transaction enhancement -->
53     <tx:advice id="txAdvice">
54         <tx:attributes>
55             <tx:method name="*" />
56             <tx:method name="get*" read-only="true" />
57         </tx:attributes>
58     </tx:advice>
59 </beans>

Create a file named jdbc.properties in src main resources in the following format. Note that url, driver,user,password are all information you set up in the database.

1 jdbc.url=jdbc:mysql://localhost:3306/testDB?useUnicode=true&characterEncoding=utf-8
2 jdbc.driver=com.mysql.jdbc.Driver
3 jdbc.user=testUser
4 jdbc.password=123456

Create a file named SpringMVC-servlet.xml in src main resources. (The name is the same as applicationContext.xml)

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 7                         http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
 8                         http://www.springframework.org/schema/mvc 
 9                         http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd 
10                         http://www.springframework.org/schema/context 
11                         http://www.springframework.org/schema/context/spring-context-4.3.xsd 
12                         http://www.springframework.org/schema/aop 
13                         http://www.springframework.org/schema/aop/spring-aop-4.3.xsd 
14                         http://www.springframework.org/schema/tx 
15                         http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
16     <!-- spring MVC Configuration, including site jump logic control, configuration -->
17     <context:component-scan base-package="cn.stevengo"
18         use-default-filters="false">
19         <!-- Scan Only Controller -->
20         <context:include-filter type="annotation"
21             expression="org.springframework.stereotype.Controller"></context:include-filter>
22     </context:component-scan>
23     <!-- Definition without Controller Of path<->view Direct mapping -->
24     <!-- Define View File Resolution -->
25     <bean
26         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
27         <property name="prefix" value="/WEB-INF/view" />
28         <property name="suffix" value=".jsp" />
29     </bean>
30     <!-- Access to static resource files will not be possible mapping reach Controller Of path Hand default servlet handler Handle -->
31     <mvc:default-servlet-handler />
32   <!-- Configured with Alibaba's fastJson,Entities can be json Formal return -->
33     <mvc:annotation-driven>
34         <mvc:message-converters register-defaults="false">
35             <bean
36                 class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
37                 <property name="supportedMediaTypes">
38                     <list>
39                         <!-- avoid IE Download prompt appears on return! -->
40                         <value>text/html;charset=UTF-8</value>
41                         <value>application/json;charset=UTF-8</value>
42                     </list>
43                 </property>
44             </bean>
45         </mvc:message-converters>
46     </mvc:annotation-driven>
47 </beans>

Create a file named mybatis-config.xml in src main resources. Note to replace the name with your own.

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3   PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4   "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6     <settings>
 7         <setting name="mapUnderscoreToCamelCase" value="true" />
 8     </settings>
 9     <typeAliases>
10         <package name="cn.stevengo.ssmtest.bean" />
11     </typeAliases>
12 </configuration>

The directory structure is shown in the figure. Execute the update Project in turn to see if the project has a red fork (check the error message to see where the error occurred), and then run to see if the "Hello World!" can appear. (Documents written by themselves)

chart

III. Test environment

"Hello World!" The SSM environment has been built. The test consists of two parts: Spring MVC and Mybatis.

1. Let's test Spring MVC first.

Create TestBean.java under the Bean package

 1 /**
 2  * Beans for testing
 3  */
 4 public class TestBean {
 5     private String testStr;
 6     private int testInt;
 7 
 8     public String getTestStr() {
 9         return testStr;
10     }
11 
12     public void setTestStr(String testStr) {
13         this.testStr = testStr;
14     }
15 
16     public int getTestInt() {
17         return testInt;
18     }
19 
20     public void setTestInt(int testInt) {
21         this.testInt = testInt;
22     }
23 
24 }

Create TestController.java under the Controller package

 1 import org.springframework.stereotype.Controller;
 2 import org.springframework.web.bind.annotation.RequestMapping;
 3 import org.springframework.web.bind.annotation.ResponseBody;
 4 
 5 import cn.stevengo.ssmtest.bean.TestBean;
 6 
 7 @Controller
 8 public class TestController {
 9     @RequestMapping("stringTest")
10     @ResponseBody
11     public String returnStr() {
12         return "hello,Even Chinese is OK";
13     }
14 
15     @RequestMapping("entityTest")
16     @ResponseBody
17     public TestBean returnEntify() {
18         TestBean testBean = new TestBean();
19         testBean.setTestStr("Test Entities");
20         testBean.setTestInt(12);
21         return testBean;
22     }
23 }

Running the test, the URL is the value in the address +@RequestMapping. If the data returns to normal, the environment spring MVC is normal.

2. Testing Mybatis

Test scenario: MyBatis's Generator reverse engineering generates beans, Dao and mapper, which are tested in junit unit.

Create a database and corresponding tables, the database name is testDB, the data table is test_t, there are two fields in the table, the sub-table is testStr,testInt, representing integer and string type data, respectively. (Preparations must be made first)

Create the generatorConfig.xml file under the project root directory, which reads as follows

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE generatorConfiguration
 3   PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
 4   "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
 5 
 6 <generatorConfiguration>
 7     <context id="DB2Tables" targetRuntime="MyBatis3">
 8         <!-- Do not add comments -->
 9         <commentGenerator>
10             <property name="suppressAllComments" value="true" />
11         </commentGenerator>
12         <!-- Database Connection Information -->
13         <jdbcConnection driverClass="com.mysql.jdbc.Driver"
14             connectionURL="jdbc:mysql://localhost:3306/testDB"
15             userId="testUser" password="123456">
16         </jdbcConnection>
17 
18         <javaTypeResolver>
19             <property name="forceBigDecimals" value="false" />
20         </javaTypeResolver>
21         <!-- Appoint javabean Generated location -->
22         <javaModelGenerator targetPackage="cn.stevengo.ssmtest.bean"
23             targetProject=".\src\main\java">
24             <property name="enableSubPackages" value="true" />
25             <property name="trimStrings" value="true" />
26         </javaModelGenerator>
27         <!-- Specify the location where the mapping file is generated -->
28         <sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
29             <property name="enableSubPackages" value="true" />
30         </sqlMapGenerator>
31         <!-- Appoint dao Location of interface generation -->
32         <javaClientGenerator type="XMLMAPPER"
33             targetPackage="cn.stevengo.ssmtest.dao" targetProject=".\src\main\java">
34             <property name="enableSubPackages" value="true" />
35         </javaClientGenerator>
36         <table tableName="test_t" domainObjectName="TestBean"></table>
37     </context>
38 </generatorConfiguration>

Create the MBGTest.java file under the test package, as follows

 1 import java.io.File;
 2 import java.io.IOException;
 3 import java.sql.SQLException;
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 
 7 import org.mybatis.generator.api.MyBatisGenerator;
 8 import org.mybatis.generator.config.Configuration;
 9 import org.mybatis.generator.config.xml.ConfigurationParser;
10 import org.mybatis.generator.exception.InvalidConfigurationException;
11 import org.mybatis.generator.exception.XMLParserException;
12 import org.mybatis.generator.internal.DefaultShellCallback;
13 
14 public class MBGTest {
15     public static void main(String args[])
16             throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
17            List<String> warnings = new ArrayList<String>();
18            boolean overwrite = true;
19            File configFile = new File("generatorConfig.xml");
20            ConfigurationParser cp = new ConfigurationParser(warnings);
21            Configuration config = cp.parseConfiguration(configFile);
22            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
23            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
24            myBatisGenerator.generate(null);
25     }
26 
27 }

Right-click on the file and run as java application. After running, the project list is refreshed, and a package file is generated under the corresponding package (note that the last test may be invalid due to changes in the bean structure, then modify the controller's code). The result is as follows:

The generated file mapper file and dao interface provide many ways for us to test only the insertion. Create a file named TestDao.java under the test package with the following contents:

 1 import org.junit.runner.RunWith;
 2 import org.junit.Test;
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.test.context.ContextConfiguration;
 5 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 6 
 7 import cn.stevengo.ssmtest.bean.TestBean;
 8 import cn.stevengo.ssmtest.dao.TestBeanMapper;
 9 
10 @RunWith(SpringJUnit4ClassRunner.class)
11 @ContextConfiguration(locations = { "classpath:applicationContext.xml" })
12 public class TestDao {
13     @Autowired
14     TestBeanMapper testBeanMapper;
15 
16     @Test
17     public void testInsert() {
18         TestBean testBean = new TestBean();
19         testBean.setTeststr("mybatisInsert");
20         testBean.setTestint(343);
21 
22         testBeanMapper.insert(testBean);
23 
24     }
25 }

Run the above code with junit, open the database after completion, and check whether the record has been inserted. This is the end of the test.

Topics: Java Mybatis Spring xml