Quickly integrate SSM from scratch, beginner's package will

Keywords: JavaEE SSM IDEA

 

        The key to integrating SSM is the configuration of several xml

get ready:

  1.     Idea (after tomcat is configured, the plug-in freeMybatis can be installed to improve efficiency. It's not difficult to install plug-ins. Baidu experience has it)

  2.     Download MySql database and visual management software

  3.     One hand, precious half an hour

  4.     If you know something about SSM, I will continue to write about these three frameworks later

Start:

 

First, clarify our work here:

Establish a general SSM project, or know how to quickly establish it, so that you can start directly after analysis, so as to avoid wasting time in initializing the project and integrating the framework

        Work objectives:

Later, if we print the table information stored in the database on the console, Spring and MyBatis are integrated successfully. If the database data is displayed on the front page, it can be said that the integration of the three frameworks is successful

   

Tip: after one success, you can build several more times again and again. When you are proficient, you can also save the template and use it directly later. I just write this blog while building the project from scratch. I have completed it. You should follow it

    Poisonous chicken soup: in this process, you may encounter a lot of troubles, but most of them can be solved by Baidu and may also be misled. However, the result is certain to be successful. After all, it is predictable and limited, and as long as it succeeds once, it can ensure success countless times

 

  I'm still a little white. I'm writing a blog for the first time (the final exam is coming soon, ha ha). I hope to record the pits I've stepped on in this way. They're all slowly discovered by myself. They're unscientific and nonstandard. I also hope the big guys can give more guidance

 

Step 1: create a new project on Idea:

 

 

  At this time, the item should be white, like this:

 

 

Here are several packages and configuration files:

 

  Create these configuration files under config (this is actually the core configuration. The contents of the file are ignored first and copied directly later):

 

Now import the jar package. You can choose to download it automatically or add it directly using Maven project. Here we add it manually:

 

 

 

 

  Just bring in your preparation Jar bag

 

Do a little more tricks and mark the file (the test package is just built, which is an ordinary package, so there is no screenshot):

 

 

This is what the project looks like:

 

 

So far, the first step of the initialization project has been completed, and 70% of it has been completed

 

   

Step 2: make the project run, and you can see the information stored in the database on the front page

1. Configure tomcat and add content to the configuration file just created

2. Add a new table in the database, insert a piece of test data, and establish mapper file and interface for the table (which can be completed by plug-in)

3. Simply write it and start the test

 

1. Configuring Tomcat is relatively simple, so we won't show it step by step. You can write it in detail later when you have a holiday

2. Contents of each configuration file:

  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"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        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.xsd
 8        http://www.springframework.org/schema/context
 9        https://www.springframework.org/schema/context/spring-context.xsd
10        http://www.springframework.org/schema/tx
11         http://www.springframework.org/schema/tx/spring-tx.xsd">
12     <!--Configure data sources-->
13     <context:property-placeholder location="classpath:config/db.properties"/>
14     <context:component-scan base-package="service"/>
15     <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
16         <property name="driverClassName" value="${jdbc.driver}"/>
17         <property name="url" value="${jdbc.url}"/>
18         <property name="username" value="${jdbc.username}"/>
19         <property name="password" value="${jdbc.password}"/>
20         <property name="maxIdle" value="${jdbc.maxIdle}"/>
21         <property name="initialSize" value="${jdbc.initialSize}"/>
22     </bean>
23     
24     <!--mybatis-->
25     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
26         <property name="basePackage" value="mapper"/>
27     </bean>
28     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
29         <property name="dataSource" ref="dataSource"/>
30         <property name="configLocation" value="classpath:config/Mybatis-config.xml"/>
31     </bean>
32     
33     <!--transaction management-->
34     <bean id="myTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
35         <property name="dataSource" ref="dataSource"/>
36     </bean>
37     <tx:annotation-driven transaction-manager="myTransactionManager"/>
38    <!-- <aop:aspectj-autoproxy proxy-target-class="true"/>-->
39 </beans>

Db.properties (to be changed according to your own database):

1 jdbc.driver=com.mysql.jdbc.Driver
2 jdbc.url=jdbc:mysql://localhost:3308/exam?useUnicode=true&characterEncoding=utf8&useSSL=false
3 jdbc.username=root
4 jdbc.password=123456
5 jdbc.maxTotal=30
6 jdbc.maxIdle=10
7 jdbc.initialSize=5

  log4j.properties :

1 # Global logging configuration
2 log4j.rootLogger=ERROR, stdout
3 # MyBatis logging configuration...
4 log4j.logger.org.mybatis.example.BlogMapper=DEBUG
5 # Console output...
6 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
7 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
8 log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

  mybatis-config.xml :

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     <typeAliases>
7         <package name="po"/>
8     </typeAliases>
9 </configuration>

  springmvc-config.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"
       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">

    <context:component-scan base-package="controller"/>
    <mvc:annotation-driven/>

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

   web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--Spring-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:config/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!--Coding filter-->
    <filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>
    
    <!--spring Mvc-->
    <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:config/springmvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
</web-app>

 

    3. Create a table in the database and insert a piece of data

 

 

  4. Use the plug-in to generate the mapper file and dao interface of the test table

Last generated project structure:

 

Generate specific code (this is automatically generated by the plug-in, which is easy):

UserDao interface:

package mapper;

import org.springframework.transaction.annotation.Transactional;
import po.User;

@Transactional
public interface UserDao {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);
}

  UserDao.xml :

<?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="mapper.UserDao">
  <resultMap id="BaseResultMap" type="po.User">
    <id column="user_id" jdbcType="INTEGER" property="id" />
    <result column="user_userName" jdbcType="VARCHAR" property="userName" />
    <result column="user_passWord" jdbcType="VARCHAR" property="passWord" />
    <result column="user_phone" jdbcType="VARCHAR" property="phone" />
    <result column="user_realName" jdbcType="VARCHAR" property="realName" />
    <result column="user_sex" jdbcType="VARCHAR" property="sex" />
    <result column="user_address" jdbcType="VARCHAR" property="address" />
    <result column="user_email" jdbcType="VARCHAR" property="email" />
  </resultMap>
  <sql id="Base_Column_List">
    user.id as user_id, user.userName as user_userName, user.`passWord` as `user_passWord`, 
    user.phone as user_phone, user.realName as user_realName, user.sex as user_sex, user.address as user_address, 
    user.email as user_email
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from user user
    where user.id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from user
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" keyColumn="id" keyProperty="id" parameterType="po.User" useGeneratedKeys="true">
    insert into user (userName, `passWord`, phone, 
      realName, sex, address, 
      email)
    values (#{userName,jdbcType=VARCHAR}, #{passWord,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR}, 
      #{realName,jdbcType=VARCHAR}, #{sex,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR}, 
      #{email,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="po.User" useGeneratedKeys="true">
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="userName != null">
        userName,
      </if>
      <if test="passWord != null">
        `passWord`,
      </if>
      <if test="phone != null">
        phone,
      </if>
      <if test="realName != null">
        realName,
      </if>
      <if test="sex != null">
        sex,
      </if>
      <if test="address != null">
        address,
      </if>
      <if test="email != null">
        email,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="userName != null">
        #{userName,jdbcType=VARCHAR},
      </if>
      <if test="passWord != null">
        #{passWord,jdbcType=VARCHAR},
      </if>
      <if test="phone != null">
        #{phone,jdbcType=VARCHAR},
      </if>
      <if test="realName != null">
        #{realName,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        #{sex,jdbcType=VARCHAR},
      </if>
      <if test="address != null">
        #{address,jdbcType=VARCHAR},
      </if>
      <if test="email != null">
        #{email,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="po.User">
    update user
    <set>
      <if test="userName != null">
        userName = #{userName,jdbcType=VARCHAR},
      </if>
      <if test="passWord != null">
        `passWord` = #{passWord,jdbcType=VARCHAR},
      </if>
      <if test="phone != null">
        phone = #{phone,jdbcType=VARCHAR},
      </if>
      <if test="realName != null">
        realName = #{realName,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        sex = #{sex,jdbcType=VARCHAR},
      </if>
      <if test="address != null">
        address = #{address,jdbcType=VARCHAR},
      </if>
      <if test="email != null">
        email = #{email,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="po.User">
    update user
    set userName = #{userName,jdbcType=VARCHAR},
      `passWord` = #{passWord,jdbcType=VARCHAR},
      phone = #{phone,jdbcType=VARCHAR},
      realName = #{realName,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=VARCHAR},
      address = #{address,jdbcType=VARCHAR},
      email = #{email,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

User class:  

package po;

import java.io.Serializable;


/**
 * user
 * @author 
 */

public class User implements Serializable {
    /**
     * id,Primary key
     */
    private Integer id;

    /**
     * account
     */
    private String userName;

    /**
     * password
     */
    private String passWord;

    /**
     * phone number
     */
    private String phone;

    /**
     * Real name
     */
    private String realName;

    /**
     * Gender
     */
    private String sex;

    /**
     * Address (receiving)
     */
    private String address;

    /**
     * E-mail
     */
    private String email;

    private static final long serialVersionUID = 1L;

    @Override
    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (that == null) {
            return false;
        }
        if (getClass() != that.getClass()) {
            return false;
        }
        User other = (User) that;
        return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
            && (this.getUserName() == null ? other.getUserName() == null : this.getUserName().equals(other.getUserName()))
            && (this.getPassWord() == null ? other.getPassWord() == null : this.getPassWord().equals(other.getPassWord()))
            && (this.getPhone() == null ? other.getPhone() == null : this.getPhone().equals(other.getPhone()))
            && (this.getRealName() == null ? other.getRealName() == null : this.getRealName().equals(other.getRealName()))
            && (this.getSex() == null ? other.getSex() == null : this.getSex().equals(other.getSex()))
            && (this.getAddress() == null ? other.getAddress() == null : this.getAddress().equals(other.getAddress()))
            && (this.getEmail() == null ? other.getEmail() == null : this.getEmail().equals(other.getEmail()));
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getRealName() {
        return realName;
    }

    public void setRealName(String realName) {
        this.realName = realName;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
        result = prime * result + ((getUserName() == null) ? 0 : getUserName().hashCode());
        result = prime * result + ((getPassWord() == null) ? 0 : getPassWord().hashCode());
        result = prime * result + ((getPhone() == null) ? 0 : getPhone().hashCode());
        result = prime * result + ((getRealName() == null) ? 0 : getRealName().hashCode());
        result = prime * result + ((getSex() == null) ? 0 : getSex().hashCode());
        result = prime * result + ((getAddress() == null) ? 0 : getAddress().hashCode());
        result = prime * result + ((getEmail() == null) ? 0 : getEmail().hashCode());
        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", id=").append(id);
        sb.append(", userName=").append(userName);
        sb.append(", passWord=").append(passWord);
        sb.append(", phone=").append(phone);
        sb.append(", realName=").append(realName);
        sb.append(", sex=").append(sex);
        sb.append(", address=").append(address);
        sb.append(", email=").append(email);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

 

  5. Test the basic integration of Spring and Mybatis

1. Create a test class under the test package to test:

 

 

  The contents are as follows:

Test class:

import mapper.UserDao;
import org.springframework.context.ApplicationContext;
import util.SpringUtil;

/**
 * test
 *
 * @author Mr.green
 * @date 2021/11/21 17:27
 */
public class Test {

    @org.junit.jupiter.api.Test
    void test(){
        ApplicationContext applicationContext= SpringUtil.getApplicationContext();
        System.out.println(applicationContext.getBean(UserDao.class).selectByPrimaryKey(1));
    }
}

SpringUtil class:

 1 package util;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 /**
 7  * Spring
 8  *
 9  * @author Mr.green
10  * @date 2021/11/21 17:28
11  */
12 public class SpringUtil {
13     /*Get spring context parser*/
14    static public ApplicationContext getApplicationContext(){
15         return  new ClassPathXmlApplicationContext("config/applicationContext.xml");
16     }
17 
18 
19 }

 

Start the test directly:

 

Nice,Spring and Mybatis are successfully integrated

 

6. Test the integration of spring, mybatis and spring MVC

1. Create a jsp page to display the data of the database

2. Create a controller to respond to the request of the front end

1:   Create a jsp page

  

    a.jsp content:

 

<%--
  Created by IntelliJ IDEA.
  User: Philosohy
  Date: 2021/11/22
  Time: 13:41
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    ${user.id}<br>
    ${user.userName}<br>
    ${user.passWord}<br>
</body>
</html>

 

2. Create a controller:

 

 

    Its contents:

package controller;

import util.SpringUtil;
import mapper.UserDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * test
 *
 * @author Mr.green
 * @date 2021/11/21 18:23
 */
@Controller
public class TestController {

    @RequestMapping("/test")
    public String test(Integer id, Model model){
        ApplicationContext applicationContext= SpringUtil.getApplicationContext();
        model.addAttribute("user",applicationContext.getBean(UserDao.class).selectByPrimaryKey(1));

        return "a";
    }
}

 

  3. Start the test, start the project, and add test after the page that pops up:

 

 

This is not flying!!!!

Posted by thorpe on Mon, 22 Nov 2021 15:22:02 -0800