Simple and easy to understand: SSM entry-level project integration example tutorial + attached project source code


Welcome ===Follow===Like===Comment, learn together, and make progress together!

Your likes, attention, and comments are the driving force for my creation!

-------I hope my article is helpful to you-------

Table of contents

I. Introduction

2. Recommended development and operating environment

3. Basic structure of the project

4. Create an ordinary JAVAEE-WEB project

 5. Build a database

 Six, pom.xml introduces dependencies

Seven, create entity class

 8. Create the classes and interfaces of the corresponding modules of the three-tier architecture

9. Integration of Spring and Mybatis

1. Spring configuration file:

2. Integrated configuration of Spring and Mybatis

3. Integration testing

4. Test results

Nine, Spring and SpringMVC integration

1. Spring configuration

2. Configuration of Spring MVC

3. SSM framework integration test

10. Precautions and BUG feedback

1. Console Chinese garbled solution:

 2. Mysql database Chinese garbled solution:

 3. Solution to Chinese garbled characters in the server log:

4. No appropriate protocol exception error occurs

 5. java.lang.NoClassDefFoundError appears: javax/severlet/ error

11. Summary



I. Introduction

  The fastest way to improve your programming level and the understanding and application of a certain direction must be hands-on practice, self-torture in constant Debug, and then give up! ! ! (joke)

  This article is just a tutorial on the integration of the basic SSM framework ( Sping+SpringMVC+Mybatis ), and a simple solution to the problems that may be encountered! Because just starting a project naturally requires a transitional stage, otherwise it will be extremely difficult in the early stage.

  Without further ado, let's get started!

The dry goods are not cumbersome throughout the whole process, and the train starts! !

Final Test Result:

2. Recommended development and operating environment

1. System: Windows 10

2、IDE:Interilj ideal 2021.3

3. Server: Tomacat-8 ( Severlet-4.0 corresponding to a higher version will start an error, pay attention!! )

4. Database: MySQL5.7

5. Browser: FireFox

6、JavaKit:JDK18

3. Basic structure of the project

4. Create an ordinary JAVAEE-WEB project

1. Click File, new, project

 2. Create a JavaEnterpri project, select the corresponding JDK, name it SSM, select JavaEE8, and then Finish

 5. Build a database

1. Create SSM database and tb_book data table

create database SSM;
create table tb_book(
id int(11) primary key,
name varchar(20) not null,
press varchar(20) not null,
author varchar(20) not null);

 2. Insert data

insert into tb_book(id,name,press,author) values(1,"Moving Earth","人民出版社","刘慈欣");

 Six, pom.xml introduces dependencies

The code is as follows: (just copy and paste)

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>SSM</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>SSM</name>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
        <junit.version>5.8.1</junit.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <!--Spring事务管理-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <!--Spring MVC的相关依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <!--MyBatis相关依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--MyBatis与Spring整合相关依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!--数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.20</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
            <version>3.4.5</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
        <!-- 数据库驱动相关依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>SSM</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.3.2</version>
            </plugin>
        </plugins>
        <!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉。 -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>

    </build>


</project>

Seven, create entity class

Create com.iheima.domain package under src/main/java and create Book entity class

1-1Book.java

package com.itheima.domain;
public class Book {
    private Integer id;
    private String name;
    private  String press;
    private  String author;
    public Integer getId()
    {
        return id;
    }
    public void setId(Integer id){
        this.id=id;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getAuthor() {
        return author;
    }
    public void setPress(String press) {
        this.press = press;
    }
    public String getPress() {
        return press;
    }
}

 8. Create the classes and interfaces of the corresponding modules of the three-tier architecture

Create com.iheima.dao package under src/main/java and create BookMapper interface

1-2 BookMapper.java

package com.itheima.dao;
import com.itheima.domain.Book;
public interface BookMapper {
         public Book findBookById(Integer id);
}

Create its mapping file in the same directory

1-3BookMapper.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="com.itheima.dao.BookMapper">
    <!--根据id查询图书信息 -->
    <select id="findBookById" parameterType="int"
            resultType="com.itheima.domain.Book">
  		select * from tb_book where id = #{id}
  	</select>
</mapper>

     Create com.iheima.service package under src/main/java and create BookService interface

        1-4 BookService.java

package com.itheima.service;
import com.itheima.domain.Book;
public interface BookService {
    Book findBookById(Integer id);
}

Create the com.iheima.service.Impl package under src/main/java, and create the implementation class BookServiceImpl

1-5 BookServiceImpl.java

package com.itheima.service.impl;
import com.itheima.dao.BookMapper;
import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;
    public Book findBookById (Integer id)
    {
        return bookMapper.findBookById(id);
    }
}

Create com.iheima.controller package under src/main/java and create BookController processor class

1-5 BookController.java


package com.itheima.controller;
import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class BookController {
    @Autowired
    private BookService bookService;
    @RequestMapping("/book")
    public ModelAndView findBookById(Integer id)
    {
        Book book=bookService.findBookById(id);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("book.jsp");
        modelAndView.addObject("book",book);
        return modelAndView;
    }
}

9. Integration of Spring and Mybatis

1. Spring configuration file:

Create the application-service.xml configuration file in the src/main/resources directory

2-1 application-service.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"
  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
    	">
 <context:component-scan base-package="com.itheima.service"/>
</beans>

2. Integrated configuration of Spring and Mybatis

Create a property source file jdbc.properties in the src/main/resources directory to configure the MySQL database

2-2 jdbc.properties

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true\
  &characterEncoding=utf-8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=123456

Create application-dao.xml configuration information in the src/main/resources directory

2-3 application-dao.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"
       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
 	">
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <bean id="sqlSessionFactory"
          class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.itheima.dao"/>
    </bean>
</beans>

3. Integration testing

Create BookServiceTest class in src/test/java

2-4BookServiceTest.java

import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:application-service.xml","classpath:application-dao.xml"})
public class BookServiceTest {
@Autowired
    private BookService bookService;
@Test
    public void findBookById()
{
    Book book=bookService.findBookById(2);
    System.out.println("id:"+book.getId());
    System.out.println("name:"+book.getName());
    System.out.println("author:"+book.getAuthor());
    System.out.println("press:"+book.getPress());
}
}

4. Test results

Test success:

Nine, Spring and SpringMVC integration

1. Spring configuration

Enter the following code in the web.xml of the project webapp/WEB-INF

3-1 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">
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application-*.xml</param-value>
      </context-param>
      <listener>
        <listener-class>
          org.springframework.web.context.ContextLoaderListener
        </listener-class>
      </listener>
      <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>
          org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
</web-app>

2. Configuration of Spring MVC

Create Spring-mvc.xml configuration information in the src/main/resources directory

 3-2 spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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">
    <context:component-scan base-package="com.itheima.controller"/>
    <mvc:annotation-driven/>
</beans>

3. SSM framework integration test

Create book.jsp file under src/main/webapp

3-4 book.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>图书信息查询</title>
</head>
<body>
<table border="1">
<tr>
    <th>图书id</th>
    <th>图书名称</th>
    <th>出版社</th>
    <th>作者</th>
</tr>
<tr>
    <td>${book.id}</td>
    <td>${book.name}</td>
    <td>${book.press}</td>
    <td>${book.author}</td>
</tr>
</table>
</body>
</html>

Start Tomcat8, enter in the browser

http://localhost:8082/SSM_war_exploded/book?id=1

 Among them, 8082 is the port number, mine is 8082, the default is 8080, just change it according to your own configuration!

 result:

10. Precautions and BUG feedback

1. Console Chinese garbled solution:

Settings->Editor->File Encodings->The three parts can be changed to GBK as shown in the figure

 2. Mysql database Chinese garbled solution:

Modify the database character set:

alter database SSM default convert to character set utf8;

 3. Solution to Chinese garbled characters in the server log:

Find the corresponding Tomcat-8 storage address, find it in conf

logging.properties file, just replace all GBk with UTF-8

 

4. No appropriate protocol exception error occurs

Find the corresponding location jdk, put java.security in

dk.tls.disabledAlgorithms=After SSLv3, TLSv1, TLSv1.1 removed,

As shown in the figure, it is about line 724. After deletion, it is as shown in the figure:

 

 5. java.lang.NoClassDefFoundError appears: javax/severlet/ error

It is because the higher version of Tomcat does not support the 4.0 version of Sevrlet, just replace the lower version of Tomcat

11. Summary

 Generally speaking, when starting a WEB project, there will always be various BUGs due to various reasons, and it takes a lot of time to investigate and debug before the final project can be run step by step, so there are many aspects to consider , it is important to understand the reason why the compiler reports an error, so as to analyze a feasible solution.

 Only by constantly urging yourself to practice and learn, and accumulate debugging ability and experience, can you slowly make progress!

It's not easy to post, I implore the big guys to raise your hands!


Likes: Likes are a kind of virtue, and they are the recognition of my creation by the bosses!


Comments: There is no white contact, it is the beginning of communication between you and me!


Collection: May you pick more, it is the appreciation of the bosses to me!

Guess you like

Origin blog.csdn.net/m0_55278347/article/details/129711245