从零配置起一个可运行的最简单SSM应用,可作为模板今后使用

一、基本环境搭建

1、创建数据库
2、创建meaven工程

(1)在pom.xm里面导入依赖

junit, 数据库驱动,连接池,servlet,JSP,mybatis,mybatis-spring, spring

<dependencies>
        <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!-- 数据库连接池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

        <!--Servlet - JSP -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!--Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

        <!--Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
            <!--lombok偷懒专用-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
        </dependency>
    </dependencies>

(2) 配置静态文件过滤导出问题

让不在Resources文件夹中的xml文件能够被Meaven导出

    <!--设置静态资源过滤-->
    <build>
        <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>
3、连接数据库

idea连接数据库时,出现时区错误,需要在 URL中指定时区

The specified database user/password combination is rejected: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.

jdbc:mysql://localhost:3306?serverTimezone=GMT%2B8
4、建立包名

(1)model,dao,controller,service以及resourse

(2)创建applicationContext.xml以及mybatis-config.xml文件,并加入相应的命令空间

applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

</configuration>

二、搭建Mybatis

1、编写mybatis-config.xml文件

(1)创建数据库连接属性配置文件database.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

(2)给包起别名

    <typeAliases>
        <package name="com.hao.model"/>
    </typeAliases>

(3)声明mapper.xml文件

   <mappers>
       <mapper resource="com/hao/dao/StudentMapper.xml"/>
   </mappers>
2、编写实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    
    
    private int num;
    private String name;
    private String sex;
}
3、编写mapper接口
public interface StudentMapper {
    
    
    //查找学生
    Student findStudentByNum(int num);
}
4、编写mapper.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-->
<mapper namespace="com.hao.dao.StudentMapper">
    <!--根据id查询,返回一个student-->
    <select id="findStudentByNum" resultType="Student">
      select * from students
      where num=#{num}
   </select>


</mapper>
5、编写service层

(1)编写service接口

是为了以后维护起来更方便,更改时只要更改其实现类即可。

public interface StudentService {
    
    
    Student findStudentByNum(int num);
}

(2)编写实现类,并组合Dao层

public class StudentServiceImpl implements StudentService {
    
    
    private StudentMapper studentMapper;
    //因为是私有属性,所以需要一个setter,方便Spring管理
    public void setStudentMapper(StudentMapper studentMapper) {
    
    
        this.studentMapper = studentMapper;
    }

    public Student findStudentByNum(int num) {
    
    
       return studentMapper.findStudentByNum(num);
    }
}

三、搭建spring

1、整合dao层

(1) 创建spring-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
       https://www.springframework.org/schema/context/spring-context.xsd">
</beans>

(2)关联数据库配置文件

<!-- 配置整合mybatis -->
   <!-- 1.关联数据库文件 -->
<context:property-placeholder location="classpath:database.properties"/>

(3)连接池c3p0

   <!-- 2.数据库连接池 -->
   <!--数据库连接池
       dbcp 半自动化操作 不能自动连接
       c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
   -->
   <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
       <!-- 配置连接池属性 -->
       <property name="driverClass" value="${jdbc.driver}"/>
       <property name="jdbcUrl" value="${jdbc.url}"/>
       <property name="user" value="${jdbc.username}"/>
       <property name="password" value="${jdbc.password}"/>

       <!-- c3p0连接池的私有属性 -->
       <property name="maxPoolSize" value="30"/>
       <property name="minPoolSize" value="10"/>
       <!-- 关闭连接后不自动commit -->
       <property name="autoCommitOnClose" value="false"/>
       <!-- 获取连接超时时间 -->
       <property name="checkoutTimeout" value="10000"/>
       <!-- 当获取连接失败重试次数 -->
       <property name="acquireRetryAttempts" value="2"/>
   </bean>

(4)创建sqlSessionFactory Bean

这一步是连接Mybatis和Spring的最重要的一步。把原本读取xml配置文件的操作放在了这里,并且将Spring管理的数据库注入。

String resource = "MybatisConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
sqlSessionFactory.openSession();
   <!-- 3.配置SqlSessionFactory对象 -->
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
       <!-- 注入数据库连接池 -->
       <property name="dataSource" ref="dataSource"/>
       <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
       <property name="configLocation" value="classpath:mybatis-config.xml"/>
   </bean>

(5)扫描dao,注入Spring

将原本手动生成的UserMapper交给Spring自动扫描。

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
System.out.println(userMapper.getUserByUserName("123"));
   <!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
   <!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html-->
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <!-- 注入sqlSessionFactory -->
       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
       <!-- 给出需要扫描Dao接口包 -->
       <property name="basePackage" value="com.hao.dao"/>
   </bean>
2、整合service层

(1)创建spring-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">
    
 </beans>   

(2)扫描service下的Bean

这里(3)中所做的内容是重复的。但(3)的方式可以个性化定制Bean的属性内容。

<!-- 扫描service相关的bean -->
   <context:component-scan base-package="com.hao.service" />

(3)配置所有业务类成Bean

其中,service服务所需要的dao Bean引用,已经在整合dao的时候自动扫描进spring窗口了。

  <!--BookServiceImpl注入到IOC容器中-->
   <bean id="BookServiceImpl" class="com.kuang.service.BookServiceImpl">
       <property name="bookMapper" ref="bookMapper"/>
   </bean>

(4)事务配置

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

四、搭建SpringMVC

1、增加Web支持

右击项目根目录->Add Framework Support->勾选Jave EE下的web application

2、配置web.xml

(1)配置ContextLoaderListener以及定位根上下文配置文件

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

(2)配置DispactchServlet

如果加载spring-mvc.xml,又没有导入根上下文,那么会报错,找不到可满足可依赖的Bean。

如果加载总的配置文件,那么上面的配置根上下文可以不做。

    <!--DispatcherServlet-->
    <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:applicationContext.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>

(3)乱码过滤(非必要)

去掉这层代码,中文正常显示,没找出为什么。

    <!--encodingFilter-->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

(4)配置session存活时间(非必要)

    <!--Session过期时间-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
3、配置spring-mvc.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
   http://www.springframework.org/schema/context/spring-context.xsd
   http://www.springframework.org/schema/mvc
   https://www.springframework.org/schema/mvc/spring-mvc.xsd">
</beans>

(1)配置注解驱动

当配置了mvc:annotation-driven/后,Spring就知道了我们启用注解驱动。然后Spring通过context:component-scan/标签的配置,会自动为我们将扫描到的@Component,@Controller,@Service,@Repository等注解标记的组件注册到工厂中,来处理我们的请求

   <!-- 配置SpringMVC -->
   <!-- 1.开启SpringMVC注解驱动 -->
   <mvc:annotation-driven />

(2)扫描包

<!-- 4.扫描web相关的bean -->
   <context:component-scan base-package="com.hao.controller" />

(3)静态资源过滤

   <!-- 2.静态资源默认servlet配置-->
   <mvc:default-servlet-handler/>

(4)配置视图解析器

   <!-- 3.配置jsp 显示ViewResolver视图解析器 -->
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
       <property name="prefix" value="/WEB-INF/jsp/" />
       <property name="suffix" value=".jsp" />
   </bean>
4、整合applicationContext.xml文件

不整合的话 ,可以在idea中将所有文件都设置为spring上下文文件。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      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">

   <import resource="spring-dao.xml"/>
   <import resource="spring-service.xml"/>
   <import resource="spring-mvc.xml"/>
   
</beans>

五、配置Tomcat环境

注意把要用到的包在Project strucre里面进行导入!!!!!

在这里插入图片描述

参考视频:https://www.bilibili.com/video/BV1aE41167Tu?from=search&seid=7432178993035402623

参考文章:https://mp.weixin.qq.com/s?__biz=Mzg2NTAzMTExNg==&mid=2247484004&idx=1&sn=cef9d881d0a8d7db7e8ddc6a380a9a76&scene=19#wechat_redirect

猜你喜欢

转载自blog.csdn.net/qq_47234534/article/details/109275225