Spring MVC learning notes (day3 SSM integration [this should be the simplest article on SSM integration] whisper BB)

Posted by toodi4 on Wed, 08 Dec 2021 19:40:20 +0100

SSM integration of spring MVC

The so-called ssm is to use Spring, Spring MVC and Mybatis in the same project. This paper uses a simple example to demonstrate the basic integration process of ssm. The amount of article code is relatively large, you can choose to consult appropriately

1, Modify Maven mirror source

1.1 find maven's configuration file settings.xml

I use the Maven tool provided by idea. If I use my own maven, the way to modify the image configuration is the same.

1.2 modifying Maven source

Use the editor to open the file. I opened it using the underline. Find about line 146, add the following image information, and insert my comments below to solve the problem of slow download of maven

     <mirror>
            <id>alimavenid>
            <name>aliyun mavenname>
            <url>http://maven.aliyun.com/nexus/content/groups/public/url>
            <mirrorOf>centralmirrorOf>
        mirror>
        <mirror>
            <id>ukid>
            <mirrorOf>centralmirrorOf>
            <name>Human Readable Name for this Mirror.name>
            <url>http://uk.maven.org/maven2/url>
        mirror>
        <mirror>
            <id>CNid>
            <name>OSChina Centralname>
            <url>http://maven.oschina.net/content/groups/public/url>
            <mirrorOf>centralmirrorOf>
        mirror>
        <mirror>
            <id>nexusid>
            <name>internal nexus repositoryname>
            
            <url>http://repo.maven.apache.org/maven2url>
            <mirrorOf>centralmirrorOf>
        mirror>

2, Build Maven WebApp project

2.1 construction project

Be sure to choose the second one. If you choose the first one, you have to build a new project

This is the structure of the initialized project

2.2 configuring Maven dependencies

Because we want to build the ssm project, we need to add the dependencies of Spring, Spring MVC, MyBatis, and some other configuration files

  1. Project version locking
  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.8maven.compiler.source>
    <maven.compiler.target>1.8maven.compiler.target>
    <spring.version>5.2.3.RELEASEspring.version>
    <slf4j.version>1.6.6slf4j.version>
    <log4j.version>1.2.12log4j.version>
    <mysql.version>5.1.10mysql.version>
    <mybatis.version>3.4.5mybatis.version>
  properties>
  1. Dependency configuration
  <dependencies>
    <dependency>
      <groupId>org.aspectjgroupId>
      <artifactId>aspectjweaverartifactId>
      <version>1.7.4version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aopartifactId>
      <version>${spring.version}version>
    dependency>



    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>${spring.version}version>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>


    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>${spring.version}version>
    dependency>


    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>${spring.version}version>

    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>${spring.version}version>
    dependency>


    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>compilescope>
    dependency>


    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>${mysql.version}version>
    dependency>


    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>3.1.0version>
      <scope>providedscope>
    dependency>


    <dependency>
      <groupId>javax.servlet.jspgroupId>
      <artifactId>jsp-apiartifactId>
      <version>2.2version>
      <scope>providedscope>
    dependency>


    <dependency>
      <groupId>jstlgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
    dependency>


    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>${log4j.version}version>
    dependency>


    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>${slf4j.version}version>
    dependency>

    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-log4j12artifactId>
      <version>${slf4j.version}version>
    dependency>



    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>${mybatis.version}version>
    dependency>


    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.3version>
    dependency>


    <dependency>
      <groupId>c3p0groupId>
      <artifactId>c3p0artifactId>
      <version>0.9.1.2version>
      <type>jartype>
      <scope>compilescope>
    dependency>
    <dependency>
      <groupId>org.junit.jupitergroupId>
      <artifactId>junit-jupiterartifactId>
      <version>RELEASEversion>
      <scope>compilescope>
    dependency>
  dependencies>

After maven is configured, these contents will be automatically downloaded in the background. We don't care here

3, Configuration file writing

  1. Spring configuration file
  2. Configuration file for spring MVC
  3. We can also write the configuration of MyBatis (but Spring integrates MyBatis objects, so we don't have to write it ourselves)
  4. Configure logging files

3.1 Spring configuration file

Create an applicationContext.xml configuration file in Maven's resources directory and add some Spring configurations and constraints

Some IOC configurations will report errors, which will be solved later

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


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

    

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm?characterEncoding=utf8" />
        <property name="user" value="root"/>
        <property name="password" value="root"/>
    bean>


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


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



    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource">property>
    bean>


    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>

            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT" />
        tx:attributes>
    tx:advice>


    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution( * cn.gorit.service.impl.*ServiceImpl.*(..))">aop:advisor>
    aop:config>
beans>

3.2 log4j configuration file preparation

This is a configuration file for log printing

log4j.rootLogger=INFO,stdout,debug,error

#\u8F93\u51FA\u5230\u63A7\u5236\u53F0
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{yyyy-MM-dd HH:mm:ss,SSS} %p [%t] %C.%M(%L) | %m%n

#\u8F93\u51FADEBUG\u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7\u5230\u6587\u4EF6
log4j.appender.debug=org.apache.log4j.DailyRollingFileAppender
log4j.appender.debug.layout=org.apache.log4j.PatternLayout
log4j.appender.debug.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %p [%t] %C.%M(%L) | %m%n
log4j.appender.debug.File=./logs/debug.txt
log4j.appender.debug.DatePattern=','yyyy-MM-dd
log4j.appender.debug.Threshold=DEBUG
log4j.appender.debug.Append=true
log4j.appender.debug.Encoding=UTF-8

#\u8F93\u51FADEBUG\u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7\u5230\u6587\u4EF6
log4j.appender.error=org.apache.log4j.DailyRollingFileAppender
log4j.appender.error.layout=org.apache.log4j.PatternLayout
log4j.appender.error.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %p [%t] %C.%M(%L) | %m%n
log4j.appender.error.File=./logs/error.txt
log4j.appender.error.DatePattern=','yyyy-MM-dd
log4j.appender.error.Threshold=ERROR
log4j.appender.error.Append=true
log4j.appender.error.Encoding=UTF-8

3.3 spring MVC configuration file

Create springmvc.xml in the resources directory

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.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-3.0.xsd">

    
    <context:component-scan base-package="cn.gorit">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    context:component-scan>
    
	
    
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/">property>
        <property name="suffix" value=".jsp">property>
    bean>


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


    <mvc:annotation-driven/>
beans>

3.4 database creation

Create a database named ssm and create a table named account. The table structure is as follows. Note the database version. I use MySQL version 5.7

//Create database
create database ssm;

// Use database
use ssm;

// Create data table
create table account(
	id int(11) primary key auto_increment,
	name varchar(30),
	money double 
};

3.5 writing web.xml

Configure front-end controller spring listener Encoding listener

<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">
  
  <display-name>Archetype Created Web Applicationdisplay-name>
  

<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>

  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
  context-param>


  <servlet>
    <servlet-name>dispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>

    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc.xmlparam-value>
    init-param>

    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServletservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>


  <filter>
    <filter-name>characterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>UTF-8param-value>
    init-param>
  filter>
  <filter-mapping>
    <filter-name>characterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>
  
web-app>

4, Writing java classes

4.1 create the following package structure

4.2 write entity Account

From the above, we should create an entity class named account, which also contains three fields

package cn.gorit.entity;

import java.io.Serializable;

public class Account implements Serializable {

    private Integer id;
    private String name;
    private double money;
	
	// Using the construction method with parameters, when we use IOC container injection, the data passed from the form will be automatically encapsulated into an Account object
    public Account(Integer id, String name, double money) {
        this.id = id;
        this.name = name;
        this.money = money;
    }
	
	// getter and setter are omitted because they are not used

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

4.3 method of writing dao layer

We can use MyBatis annotations to directly complete the operation of the database

package cn.gorit.dao;

import cn.gorit.entity.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Account interface
 * */
@Repository
public interface AccountDao {

    // Query all account information
    @Select("select * from account")
    public List<Account> findAll();

    // Save account information
    @Insert("insert into account(name,money) values(#{name},#{money})")
    public int saveAccount(Account account);
}

4.4 preparation method

  1. Written by AccountService Write two basic account operation interfaces
package cn.gorit.service;

import cn.gorit.entity.Account;
import java.util.List;

public interface AccountService {
    // Query all account information
    public List<Account> findAll();

    // Save account information
    public void saveAccount(Account account);
}
  1. AccountServiceImpl implements the AccountService interface Previously, we completed the database operation in mybatis. Here, we can directly call the corresponding method of dao layer
package cn.gorit.service.impl;

import cn.gorit.dao.AccountDao;
import cn.gorit.entity.Account;
import cn.gorit.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Override
    public List<Account> findAll() {
        System.out.println("Business layer, query all accounts...");
        return accountDao.findAll();
    }

    @Override
    public void saveAccount(Account account) {
        System.out.println("Business layer, deposit account...");
        accountDao.saveAccount(account);
    }
}

4.5 writing controller

Using the Controller, we can see the data we want on the page

package cn.gorit.controller;

import cn.gorit.entity.Account;
import cn.gorit.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

// Account web
@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("/test")
    @ResponseBody
    public String test() {
        // Use RequestBody to identify this method, so that a string will be returned, otherwise spring MVC will look for the jsp file with the same name
        return "Hello World";
    }

    @RequestMapping("/findAll")
    public String findAll(Model model) {
        System.out.println("Performance layer, query all accounts...");
//        Call the service method
        List<Account> list = accountService.findAll();
        model.addAttribute("list",list);
        return "list";
    }

    // Save data
    @RequestMapping("/save")
    public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("Presentation layer, save account...");
        System.out.println(account);
//        Call the service method
        accountService.saveAccount(account);
        response.sendRedirect(request.getContextPath()+"/account/findAll");
        return;
    }
}

But do you think it's over? No, we haven't written the front page yet

5, Write front page

5.1 index.jsp preparation

Because we need to call the method in the controller here

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>test title>
head>
<body>

    <h3>SpringMVC h3>
    <a href="account/findAll">findAlla>

    <h3>Test save h3>
    <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="preservation">
    form>
body>
html>

5.2 successful preparation jump interface

Create the pages file in the WEB-INF directory, and then create list.jsp and success.jsp (corresponding to the page jumped in the controller)

Why is this?

  1. Because we have configured such a view parser in springmvc.xml
  1. Because we use the controller to receive all network requests, this request will first pass through the front-end controller configured in web.xml
  1. After passing through the front-end controller, we will pass through the view parser, and then jump to the specified page, that is, list.js, according to the returned content
<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<html>
<head>
    <title>listtitle>
head>
<body>
    <h3>All account information was queried h3>
    ${list.get(0)} ${list.get(0)}
body>
html>

6, Operation effect

6.1 return string

6.2 query all

I only print the first data of the displayed content, so there is only the first data here

6.3 form encapsulation