SSM整合

SSM整合

1.ContextLoaderListener

Spring提供了监听器ContextLoaderListener,实现了ServletContextListener接口,可监听ServletContext的状态,在web服务器的启动,读取Spring的配置文件,创建Spring的IOC容器。web应用中必须在web.xml中配置

    <listener>
<!--        在服务启动时加载Soring的配置文件-->
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>

2.准备工作

1)创建Maven Module

2)导入依赖

   <packaging>war</packaging>


    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.3.1</version>
        </dependency>
<!--        springmvc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.1</version>
        </dependency>
<!--        管理界面-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.1</version>
        </dependency>
<!--       mybatis核心 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
<!--        mybatis和spring的整合包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
<!--        连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.31</version>
        </dependency>
<!--       junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
<!--        mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>
<!--        log4j日志-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
<!--        分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>
<!--        日志-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
<!--        ServletAPI-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
<!--        处理json数据的依赖-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.1</version>
        </dependency>
<!--        文件上传的依赖-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
<!--        Spring5和Thymeleaf整合包-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.12.RELEASE</version>
        </dependency>


    </dependencies>

3)创建表

在这里插入图片描述

4)配置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">

<!--    配置编码过滤器-->
    <filter>
        <filter-name>CharacterEncodingFilter</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>

        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


<!--    配置处理请求方式的过滤器-->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

<!--    配置SpringMVC的前端控制器-->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--        设置SpringMVC自定义的位置和名称-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
<!--        将DispatcherServlet的初始化时间提前到服务器启动时-->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

<!--    配置spring的监听器,在服务器启动时加载spring的配置文件-->

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

<!--    配置spring配置文件自定义的位置和名称-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>
</web-app>

5)配置Springmvc.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: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.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">



<!--    //    扫描组件-->
<!--    //    视图控制器-->
<!--    //    默认的servlet-->
<!--    //    mvc驱动-->
<!--    //    视图控制器-->
<!--    //    文件上传解析器-->
<!--    //    拦截器-->
<!--    //    异常解析器-->




    <!--    扫描控制层组件-->
    <context:component-scan base-package="org.example.controller"></context:component-scan>


    <!--    配置Thymeleaf视图解析器-->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <!--                        视图前缀-->
                        <property name="prefix" value="/WEB-INF/templates/"/>

                        <!--                        视图后缀-->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

    <!--    处理静态资源,例如html,js,css,jpg
            若只设置该标签,则只能访问静态资源,其他请求则无法访问
            此时必须设置<mvc:annotation-driven/>解决问题
    -->
<!--    配置默认的servlet处理静态资源-->
    <mvc:default-servlet-handler/>

    <!--    开启mvc注解驱动-->
    <mvc:annotation-driven>


        <mvc:message-converters>
            <!--            处理响应中文内容乱码-->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="defaultCharset" value="UTF-8"/>
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html</value>
                        <value>application/json</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!--    配置视图控制器-->
    <mvc:view-controller path="/" view-name="index"></mvc:view-controller>


    <!--    配置文件上传解析器-->
    <!--    必须通过文件解析器才能将文件转换为MultiparyFile对象-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>



</beans>

其中文件传解析器,拦截器,异常解析器根据功能要求选择是否要配置

6)根据之前学的ssm创建目录和类

在这里插入图片描述

controller.EmployeeController:

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping(value = "/employee",method = RequestMethod.GET)
    public String getAllEmp(Model model){
//        查询所有员工信息
        List<Employee>  list=employeeService.getAllEmployee();
//        将信息在请求域中共享
        model.addAttribute("list",list);
//        跳转employee_list.html
        return "employee_list";
    }
}

mapper.EmployeeMapper:

public interface EmployeeMapper {
    List<Employee> getAllEmployee();
}

pojo.Employee:

根据数据库表的属性创建

public class Employee {
    private Integer empId;
    private String empName;
    private Integer age;
    private String gender;
    private String email;

    public Employee(Integer empId, String empName, Integer age, String gender, String email) {
        this.empId = empId;
        this.empName = empName;
        this.age = age;
        this.gender = gender;
        this.email = email;
    }

    public Integer getEmpId() {
        return empId;
    }

    public void setEmpId(Integer empId) {
        this.empId = empId;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

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

    public Employee() {
    }

    @Override
    public String toString() {
        return "Employee{" +
                "empId=" + empId +
                ", empName='" + empName + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

service.EmployeeServive:

public interface EmployeeService {
    List<Employee> getAllEmployee();
}

service.impl.EmployeeService:

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {


    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public List<Employee> getAllEmployee() {
        return employeeMapper.getAllEmployee();
    }
}

resources.org.example.mapper.EmployeeMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--保证命名空间与mapper接口全类名一致-->
<mapper namespace="org.example.mapper.EmployeeMapper">

<!--        List<Employee> getAllEmployee();-->
    <select id="getAllEmployee" resultType="Employee">
        Select * from t_emp
    </select>
</mapper>

7)配置spring.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:contexr="http://www.springframework.org/schema/context"
       xmlns:context="http://mybatis.org/schema/mybatis-spring" 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://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

<!--扫描组件(除控制层)-->
<contexr:component-scan base-package="org.example">
    <contexr:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</contexr:component-scan>


<!--    引入jdbc.properties-->
    <contexr:property-placeholder location="classpath:jdbc.properties"></contexr:property-placeholder>
<!--    配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>



<!--    配置事务管理器-->
<!--    将使用@Transcational标识的方法或类中的所有方法进行事务管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>


<!--开启事务注解驱动-->
<!--    将使用注解@Transactional标识的方法或者类中所有1的方法进行事务管理-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>




<!--    配置sqlSessionFactoryBean,可以在spring的IOC中直接获取SqlSessionFactory对象-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!--        设置mybatis核心配置文件的路径-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--        设置数据源,若在mybatis的配置文件中设置了,就不用在此设置-->
        <property name="dataSource" ref="dataSource"/>
<!--        设置类型别名-->
        <property name="typeAliasesPackage" value="org.example.pojo"/>
<!--        设置Mapper接口的映射文件的路径-->
        <property name="mapperLocations" value="classpath:org.example.mapper/*.xml"></property>
    </bean>


<!--    配置mapper接口的造梦,可以将指定报下的所有mapper接口,
通过SqlSession创建代理实现类对象,并将这些对象交给IOC管理-->

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="org.example.mapper"></property>
    </bean>

</beans>

其中配置连接池时可以用jdbc.propertis:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
jdbc.username=root
jdbc.password=Zhang153123.

8)配置mybatis的配置文件nybatis-config.xml:

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

    <!-- 引入properties文件,此后就可以在当前文件中使用的方式访问value-->
    <properties resource="jdbc.properties"/>

    <settings>
        <!--        将下划线映射为驼峰-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--        开启延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!--        按需执行-->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>





    <plugins>
        <!--        配置分页插件-->
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>

    <!-- environments:配置连接数据库的环境-->
    <!-- default:设置默认使用的环境id-->
    <environments default="development">
        <environment id="development">

            <!--   transactionManager : 设置事务管理器
       属性:
       type:设置事务管理方式
       type=“JDBC/MANAGED”
       JDBC:表示使用JDBC原生的事务管理方式
       MANAGED:被管理,例如 Spring

-->
            <transactionManager type="JDBC"/>

            <!--   dataSource:设置数据源
       属性:
       type:设置数据源类型
       type=“POOLED/UNPOOLED/JNDI”
       POOLED:表示使用数据库连接池
       UNPOOLED:不使用数据库连接池
       JNDI:使用上下文中的连接池
-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 引入mybatis的映射文件-->

    <mappers>
        <package name="org.example.mapper"/>
    </mappers>
</configuration>

9)log4j.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{dd/MM/yy hh:mm:ss:sss z}] %5p %c{2}: %m%n" />
        </layout>
    </appender>
    <appender name="FILE" class="org.apache.log4j.RollingFileAppender">
        <param name="file" value="${user.home}/foss-framework.log" />
        <param name="append" value="true" />
        <param name="maxFileSize" value="10MB" />
        <param name="maxBackupIndex" value="100" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d [%t] %-5p %C{6} (%F:%L) - %m%n" />
        </layout>
    </appender>


    <!-- 下面是打印mybatis语句的配置-->
    <logger name="com.ibatis" additivity="true">
        <level value="DEBUG" />
    </logger>
    <logger name="java.sql.Connection" additivity="true">
        <level value="DEBUG" />
    </logger>
    <logger name="java.sql.Statement" additivity="true">
        <level value="DEBUG" />
    </logger>
    <logger name="java.sql.PreparedStatement" additivity="true">
        <level value="DEBUG" />
    </logger>
    <logger name="java.sql.ResultSet" additivity="true">
        <level value="DEBUG" />
    </logger>

    <root>
        <level value="INFO" />
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="FILE" />
    </root>
</log4j:configuration>

10)设置页面:

index.xml:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a th:href="@{/employee}">查询所有员工信息</a>
</body>
</html>

employee_list:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>员工列表</title>
</head>
<body>


<table>
  <tr>
    <th colspan="6">员工列表</th>
  </tr>
  <tr>
    <th>流水号</th>
    <th>姓名</th>
    <th>年龄</th>
    <th>性别</th>
    <th>邮箱</th>
    <th>操作</th>
  </tr>

  <tr th:each = "employee,status : ${list}">
    <td th:text="${status.count}"></td>
    <td th:text="${employee.empName}"></td>
    <td th:text="${employee.age}"></td>
    <td th:text="${employee.gender}"></td>
    <td th:text="${employee.email}"></td>
    <td>
      <a href="">删除</a>
      <a href="">修改</a>
    </td>
 </tr>
</table>
</body>
</html>

以上就是基本的ssm整合

```

employee_list:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>员工列表</title>
</head>
<body>


<table>
  <tr>
    <th colspan="6">员工列表</th>
  </tr>
  <tr>
    <th>流水号</th>
    <th>姓名</th>
    <th>年龄</th>
    <th>性别</th>
    <th>邮箱</th>
    <th>操作</th>
  </tr>

  <tr th:each = "employee,status : ${list}">
    <td th:text="${status.count}"></td>
    <td th:text="${employee.empName}"></td>
    <td th:text="${employee.age}"></td>
    <td th:text="${employee.gender}"></td>
    <td th:text="${employee.email}"></td>
    <td>
      <a href="">删除</a>
      <a href="">修改</a>
    </td>
 </tr>
</table>
</body>
</html>

以上就是基本的ssm整合

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值