SSM simple integration

When I first learned SSM integration, to be honest, I was dizzy. I couldn't remember so many complicated configurations at all.

So what's the best way?

So there will be the following article recording the integration process.

What should be remembered is the core of the three frameworks. According to the workflow, the core configuration is as follows

-In MVC part, only dispatcherServlet and controller package scan view resolution is needed

-In the Spring part, you only need to scan the listener package [exclude the controller below the scan service level]

-Only dataSource/sessionFactory/mapperScanner is needed for MyBatis

Take idea+maven as an example:

1. Create a new Maven web project


2. Import dependency in pom.xml (the core dependency is the jar package required by ssm, and the rest is optional. You can query the corresponding dependency through maven central warehouse)

<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>
    <spring.version>5.0.2.RELEASE</spring.version>
    <slf4j.version>1.6.6</slf4j.version>
    <log4j.version>1.2.12</log4j.version>
    <mysql.version>5.1.6</mysql.version>
    <mybatis.version>3.4.5</mybatis.version>

  </properties>

  <dependencies>
  <!-- spring&SpringMVC -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.8</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</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-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-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
   <!-- junit Optional -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>compile</scope>
    </dependency>
   <!-- Database connection -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
     </dependency>
   <!-- jsp Can be replaced by the rest of the template engine -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- log(Optional) -->
    <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>
    <!-- mybatis -->
    <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>
<!-- c3p0 Can be replaced by another connection pool -->
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
  </dependencies>

It includes the jar package required by the basic functions of spring, spring MVC and mybatis. The database connection pool uses c3p0.

When all imported jar packages appear in external libraries, the import is successful

3. Create corresponding project directory

Since the default template of idea has no corresponding directory, we need to create it manually

Create the corresponding java and resource directories, remember to right-click to select make directory as, select java as sources root, and select resource as resource root (the directory structure needs to be familiar with)

Then integrate Spring

1. First, create the applicationContext.xml file in the resource folder, and import constraints (constraints are usually copied and pasted)

<?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"
       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">
</beans>

2. Enable annotation scanning, the target is our basic package cn.lige2333

<context:component-scan base-package="cn.lige2333">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

Note: the scan of the Controller annotation is removed here because we will turn it on separately in spring MVC.

3. To generate spring containers when the server starts, you need to configure the ContextLoaderListener listener under web.xml and load the spring configuration file applicationContext.xml

<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>

Then the configuration of SpringMVC is carried out

1. Add the front-end controller dispatcher servlet to web.xml

  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   
   <!-- Load springmvc.xml configuration file -->
   <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
 <!-- Load on server startup servlet -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

2. Create the configuration file of springmvc, springmvc.xml, and import constraints

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>

3. Enable spring MVC annotation scanning - only controller annotations are scanned here

<context:component-scan base-package="cn.lige2333">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

4. configure the view parser. Take *.jsp under /WEB-INF/pages/ as an example

<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<! -- the prefix of view resolution is the path before the string returned in the controller -- >
        <property name="prefix" value="/WEB-INF/pages/"/>
<! -- the suffix of view resolution is the extension after the string returned in the controller -- >
        <property name="suffix" value=".jsp"/>
    </bean>

5. Filter static resources (if necessary)

<mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/images/" mapping="/images/**" />
    <mvc:resources location="/js/" mapping="/js/**" />

Take css, images and js as examples here. More can be added below

6. Enable spring MVC annotation support

<mvc:annotation-driven/>

And then mybatis

1. Inject the data source needed to connect to the database in the spring configuration file

<!-- c3p0 Need injection combopooleddatasource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- This is the class name of the connection driver -->
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
<!-- This is the database url -->
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm"/>
<!-- This is the database user name -->
        <property name="user" value="root"/>
<!-- This is the database password -->
        <property name="password" value="123456"/>
    </bean>

2. The purpose of introducing mapping configuration file is to find our dao interface and xml configuration file

<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.lige2333.dao"/>
    </bean>

3. Configure sqlsessionfactory to create dao interface proxy object

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
       <property name="dataSource" ref="dataSource"/>
   </bean>

4. Configure transactions and AOP notifications (if the project needs to use transactions)

<!-- This is the transaction manager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- Need injection DataSource -->
<property name="dataSource" ref="dataSource"/>
    </bean>
<!-- This is a transaction notice -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
<!-- Configure the way we need to add transactions -->
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>
<!-- This is AOP Enhanced for service -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.lige2333.service.Impl.*ServiceImpl.*(..))"/>
    </aop:config>

So far, all configurations are completed. If you want to use logs, you need to import log4j.properties to the resource folder.

Then configure tomcat

After that, let's write some class tests (take jsp as an example)

Database table

domain, three attributes, id, name, money

public class Account implements Serializable {
    private Integer id;
    private String name;
    private Double money;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

controller, two methods, query all information of account and save account

@Controller
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService accountService;
    @RequestMapping("/findAll")
    public String findAll(Model model){
        System.out.println("Presentation level! Query all account information!");
        List<Account> all = accountService.findAll();
        model.addAttribute("list",all);
        return "list";
    }
    @RequestMapping("/save")
    public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
        accountService.saveAccount(account);
        response.sendRedirect(request.getContextPath()+"/account /findAll");
        return;
    }
}

serviceimpl, find all methods

@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;
    @Override
    public List<Account> findAll() {
        System.out.println("1234");
        return accountDao.findAll();
    }

    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }
}

dao interface: a select and an insert

@Repository("accountDao")
public interface AccountDao {
    @Select("select * from account")
    public List<Account> findAll();
    @Insert("insert into account(name,money) values (#{name},#{money})")
    public void saveAccount(Account account);
}

The foreground jsp adds a form that points to the add method

<form action="account/save" method="post">
    //Full name:<input type="text" name="name"><br>
    //Amount of money:<input type="text" name="money"><br>
    <input type="submit" value="Submission"><br>
</form>

The debugging data is as follows:

Result successful! Successfully added and queried data

So far, the simple framework has been integrated and can be used normally

2019.11.20 22:13

Published 2 original articles, won praise 0, visited 4
Private letter follow

Tags: Spring Mybatis xml Maven

Posted on Wed, 12 Feb 2020 00:03:53 -0800 by chadrt