The three main frameworks of SSM(SpringMVC+Spring+MyBatis) use Maven to quickly build integration (database data to page presentation)

Posted by adamjones on Tue, 03 Sep 2019 20:39:52 +0200

This paper describes the process of quickly building a demo using Maven using the three main frameworks of SpringMVC+Spring+MyBatis to display data from queries in the database back to the page.

Technology selection: SpringMVC+Spring+MyBatis+MySql+Maven+JSP+IDEA+Tomcat7+JDK1.8+Navicat for MySql

Start building the project below:

1. Setting up database environment

1. First use Navicat for MySql to connect to the MySql database, create a new database or use an existing database. Here I create a new test database, and create a new user table with the following SQL tables and the SQL to insert the test data:

<!--SQL Table building statement-->
CREATE TABLE `user` (
    `id` INT (50) NOT NULL,
    `name` VARCHAR (100) NOT NULL,
    `age` INT (50) NOT NULL,
    `address` VARCHAR (200) NOT NULL,
    PRIMARY KEY (`id`)
);
<!--insert data-->
INSERT INTO USER (id,name,age,address)VALUES(1,'angelina',18,'Shanghai');
INSERT INTO USER (id,name,age,address)VALUES(6,'Xiao Shang',18,'Shanghai');
INSERT INTO USER (id,name,age,address)VALUES(2,'Yaco',18,'Tianjin');
INSERT INTO USER (id,name,age,address)VALUES(3,'Xiaoxun',18,'Zhengzhou City');
INSERT INTO USER (id,name,age,address)VALUES(4,'Little Joe',18,'Zhengzhou City');
INSERT INTO USER (id,name,age,address)VALUES(5,'Serena Williams',18,'Zhengzhou City');
INSERT INTO USER (id,name,age,address)VALUES(7,'Xiao Huan',18,'Wuhan City');

2. Create a Maven project and complete the project catalog and related package names

1. Open IDEA and create a new project;

 

2. Create a new Maven project for ssmDemo, use idea to create skeleton, select webapp to create:

 

3. Project GroupId and ArtifactId can be defined by themselves:

 

4. Configure local Maven paths:

 

5. Configure the project name and path, click the Finish button to create the project, and wait for the project initialization to complete:

 

6. After project initialization, the project directory structure is as follows:

 

7. Complete the supplementary project path by creating java and resources folders under the main folder as project resource folders; create a new test folder under the src directory, and create java and resources folders under the test folder as project resource folders, which are reserved for unit testing:

 

8. Create controller, dao, domain, service, service.impl package under src/java directory;

3. SSM Configuration File Integration

1. The coordinates of the jar package in the pom.xml file. Maven will automatically download the jar package after adding the jar package coordinates to the pom.xml. The description of the jar package required for SSM integration is already noted in the comments.

<?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.xyfer</groupId>
    <artifactId>ssmTest</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
 
    <!-- unified management jar Package Version -->
    <properties>
        <spring.version>5.0.2.RELEASE</spring.version>
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <shiro.version>1.2.3</shiro.version>
        <mysql.version>5.1.6</mysql.version>
        <mybatis.version>3.4.5</mybatis.version>
        <spring.security.version>5.0.1.RELEASE</spring.security.version>
    </properties>
 
    <dependencies>
        <!-- Mybatis and mybatis and spring Integration -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!-- MySql drive -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <!-- springMVC core-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- spring Relevant -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</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-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <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-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</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-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--junit test-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <!--servlet-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <!--jstl-->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- log -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</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>
        <!--alibaba Connection Pool-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
    </dependencies>
</project>

If there is a red wavy line under the project name, the corresponding jar package is missing and can be resolved by updating the jar with Maven:

 

2. Add springmvc.xml and applicationContext.xml files under the src/resources folder

 

3. Configure Dispatcher Servlet and spring listener in web.xml file, load springmvc.xml and applicationContext.xml files;

<?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/web-app_2_5.xsd" id="WebApp_ID"
         version="2.5">
  <!-- Front End Controller Loading springmvc container -->
  <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.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
  <!-- Listener Loading spring container -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext.xml</param-value>
  </context-param>
</web-app>

4. Configure the controller package scan and view parser in springmvc.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-4.2.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.2.xsd">
    <!--To configure controller Annotation Scan-->
    <context:component-scan base-package="com.xyfer.controller"></context:component-scan>
    <!-- Configure the prefix and suffix of the view parser -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

5. Configure database connection information in applicationContext.xml and scan dao and service packages;

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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
                http://www.springframework.org/schema/context/spring-context.xsd
                http://www.springframework.org/schema/aop
                http://www.springframework.org/schema/aop/spring-aop.xsd
                http://www.springframework.org/schema/tx
                http://www.springframework.org/schema/tx/spring-tx.xsd
                http://www.springframework.org/schema/mvc
                http://www.springframework.org/schema/mvc/spring-mvc.xsd">
 
    <!-- Database Connection Pool -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- drive -->
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <!-- url -->
        <property name="url" value="jdbc:mysql://localhost:3306/test" />
        <!-- User name -->
        <property name="username" value="root" />
        <!-- Password -->
        <property name="password" value="root" />
    </bean>
    <!-- mapper To configure -->
    <!-- Give Way spring Administration sqlsessionfactory Use mybatis and spring In Integration Package -->
    <bean id="sqlSessionFactory"
          class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- Database Connection Pool -->
        <property name="dataSource" ref="dataSource" />
        <!--pojo position-->
        <property name="typeAliasesPackage" value="com.xyfer.domain"></property>
        <!--mapper file location-->
        <property name="mapperLocations" value="classpath:com.xyfer.dao/*Mapper.xml"/>
    </bean>
    <!-- mapper Scanner: used to generate proxy objects-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.xyfer.dao"></property>
    </bean>
    <!--Configure Annotation Scan dao Configuration instead of package name above-->
    <!--<context:component-scan base-package="com.xyfer.dao"/>-->
    <!--Configure Annotation Scan service-->
    <context:component-scan base-package="com.xyfer.service"/>
 
</beans>

6. The log file log4j.properties is placed under the src/resources folder;

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5
p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to
'debug' ###
#Using debug at the development-phase log level
log4j.rootLogger=debug, stdout
### Output in Log sql Input parameters ###
log4j.logger.org.hibernate.type=TRACE

So far, the three main frameworks of SSM(SpringMVC+Spring+MyBatis) have been integrated and the configuration files have been integrated.

Begin by creating java classes and interfaces to showcase database data on front-end jsp pages:

4. Creation of entity classes and controller, service and dao interfaces;

1. Create the entity class User.java under src/main/java/com/xyfer/domain according to the mapping relationship between user table fields and entity classes in the database;

package com.xyfer.domain;
 
public class User {
    public int id;
    public String name;
    public int age;
    public String address;
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String getAddress() {
        return address;
    }
 
    public void setAddress(String address) {
        this.address = address;
    }
 
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }
 
}

2. Create UserDao under src/main/java/com/xyfer/dao, and create a method of findUserById;

package com.xyfer.dao;
 
import com.xyfer.domain.User;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
 
/**
 * dao layer
 */
@Repository
public interface UserDao {
    /**
     * Query user based on id
     * @param id
     * @return
     */
    public User findUserById(int id);
}

The location of the mapper file is configured in applicationContext.xml:

 

So create a package of com.xyfer.dao under src/main/resources, create a UserDaoMapper.xml file, note the namespace configuration in the mapper file, and write an SQL statement that asks getUserById for id

<?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.xyfer.dao.UserDao">
    <select id="findUserById" parameterType="int" resultType="com.xyfer.domain.User">
        select * from user where id=#{id}
    </select>
</mapper>

3. Create the UserService interface in src/main/java/com/xyfer/service, and create the implementation class UserServiceImpl in src/main/java/com/xyfer/service/impl;

UserService interface:

package com.xyfer.service;
 
import com.xyfer.domain.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
 * UserService layer
 */
public interface UserService {
    /**
     * Query user based on id
     * @param id
     * @return
     */
    public User findUserById(int id);
 
}

Implement class UserServiceImpl:

package com.xyfer.service.impl;
 
import com.xyfer.dao.UserDao;
import com.xyfer.domain.User;
import com.xyfer.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
/**
 * UserServiceImpl service Implementation Class
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    public UserDao userDao;
 
    /**
     * Query user based on id
     * @param id
     * @return
     */
    public User findUserById(int id) {
        return userDao.findUserById(id);
    }
 
}

4. Create UserController in src/main/java/com/xyfer/controller:

package com.xyfer.controller;
 
import com.xyfer.domain.User;
import com.xyfer.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
/**
 * controller layer
 */
@Controller
@RequestMapping("/xyfer")
public class UserController {
    @Autowired
    public UserService userService;
 
    /**
     * Query user based on id
     * @param id
     * @return
     */
    @RequestMapping("/findUserById")
    public String findUserById(int id, Model model){
        User user = userService.findUserById(id);
        model.addAttribute("user",user);
        return "userInfo";
    };
}

5. Front-end page display;

Because the view resolver configured in springmvc.xml is shown in the figure, and the controller controller controller returns "userInfo":

 

So create a JSP folder under src/main/webapp/WEB-INF and a userInfo.jsp file;

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!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>user information</title>
</head>
<body>
<form>
    <table width="100%" border=1>
        <tr>
            <td>Full name</td>
            <td> ${user.name } </td>
        </tr>
        <tr>
            <td>Age</td>
            <td> ${user.age } </td>
        </tr>
        <tr>
            <td>address</td>
            <td>${user.address} </textarea>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

At this point, all the classes and interfaces required by the project have been written, and the project path is shown in the diagram:

6. Publish the deployment project and access it through the browser to get the expected data returned from the database;

1. Open the Deployment Project page:

 

2. Add a tomcat service;

 

3. Configure Server and Deployment

 

Select Artifact

 

Select a war package

 

Configure access paths:

 

Enter the access address in the browser: http://localhost:8080/ssm/, return, the following page appears, the project publishing deployment is successful:

 

The following queries the data we want by sending a request with parameters through an address:

The address is as follows: http://localhost:8080/ssm/xyfer/findUserById.action?id=1

Dispatcher Servlet intercepts the action request and gets the userInfo page when the page jumps back:

 

 

When the browser appears on this page, it proves that we have queried the user data with an id value of 1 from the database and displayed the user's information on the front-end page.

At this time, we have completed the three main frameworks of SSM(SpringMVC+Spring+MyBatis) using Maven to quickly build, integrate and display database data to the page.

Topics: Java Spring xml Mybatis