zoukankan      html  css  js  c++  java
  • JAVA_SSM框架入门-尚硅谷SSM框架实战学习笔记(SSM整合配置)

    一、配置 web.xml

    1.1 启动spring容器

    在src/main/webapp/WEB-INF/web.xml文件中配置 启动spring容器

      <!--启动Spring容器-->
      <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>
    

    项目已启动即会加载 类路径下的applicationContext.xml文件

    1.2 创建配置文件applicationContext.xml

    在src/main/resources/ 目录中新建 applicationContext.xml

    1.3 完成web.xml的其他配置项

      <!--Spring MVC 的前端控制器,拦截所有请求-->
      <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
    

    在web.xml同级的目录下新建 dispatcherServlet-servlet.xml 文件夹
    回到web.xml,添加其他配置项

    <!--字符编码过滤器,一定放在所有过滤器之前-->
      <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>forceRequestEncoding</param-name>
          <param-value>true</param-value>
        </init-param>
        <init-param>
          <param-name>forceResponseEncoding</param-name>
          <param-value>true</param-value>
        </init-param>
      </filter>
      <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
      <!--使用Rest风格的URI,将页面普通的POST请求转为指定的delect或者put请求-->
      <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>
    

    注意:字符编码过滤器,一定放在所有过滤器之前

    二、配置 dispatcherServlet-servlet.xml (SpringMVC的配置文件)

    在 src/java/com/wybing/curd包下新建包(图1)

    • bean (模型)
    • controller (控制器)
    • dao (接口,数据持久化操作)
    • service (业务逻辑层)
    • test (测试类)
    • utils (工具类)
      图1
      还有一个mapper层,数据存储对象,相当于DAO层,mapper层直接与数据库打交道(执行SQL语句),接口提供给service层。

    dispatcherServlet-servlet.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 http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <!--SpringMVC的配置文件,包含网站跳转逻辑的控制、配置-->
        <context:component-scan base-package="com.wybing" use-default-filters="false">
            <!--只扫描控制器-->
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        </context:component-scan>
    
        <!--配置视图解析器,方便页面返回-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
    
        <!--两个标准配置-->
        <!--将Spring MVC 不能处理的请求交给Tomcat-->
        <mvc:default-servlet-handler/>
        <!--能支持Spring MVC 更高级的一些功能,比如:JSR303校验、快捷ajax...映射动态请求-->
        <mvc:annotation-driven/>
    
    </beans>
    

    三、配置applicationContext.xml(Spring的配置文件)

    在src/main/resources/ 新建 dbconfig.properties 存放数据库连接信息
    代码:

    jdbc.jdbcUrl = jdbc:mysql://localhost:3305/ssm_crud
    jdbc.driverClass = com.mysql.jdbc.Driver
    jdbc.user = root
    jdbc.password = root
    

    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"
           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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    
         <!-- 扫描 com.wybing 下的所有包 ,除了控制器不要,其他的都要 -->
         <context:component-scan base-package="com.wybing">
             <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
         </context:component-scan>
        <!--Spring的配置文件,这里主要配置和业务逻辑有关的-->
        <!--数据源,事务控制,等等 -->
        <context:property-placeholder location="classpath:dbconfig.properties"/>
        <!--Spring配置文件中通过${key}获取自定义配置文件(dbconfig.properties)中对应的值-->
        <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
            <property name="driverClass" value="${jdbc.driverClass}" ></property>
            <property name="user" value="${jdbc.user}" ></property>
            <property name="password" value="${jdbc.password}" ></property>
        </bean>
    
        <!--配置和Mybatis的整合-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
             <!--指定Mybatis全局配置文件的位置-->
            <property name="configLocation" value="classpath:mybatis-config.xml"></property>
            <property name="dataSource" ref="pooledDataSource"></property>
            <!--指定Mybatis , mapper文件的位置-->
            <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    
        </bean>
    
        <!--配置扫描器,将Mybatis接口的实现加入到ioc容器中-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!--扫描所有dao接口的实现,加入到ioc容器中-->
            <property name="basePackage" value="com.wybing.curd.dao"></property>
        </bean>
    
        <!--配置一个可以执行批量的sqlSession-->
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
            <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
            <constructor-arg name="executorType"  value="BATCH"></constructor-arg>
        </bean>
    
        <!--事务控制的配置-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <!--控制住数据源-->
            <property name="dataSource" ref="pooledDataSource"></property>
        </bean>
    
        <!--开启基于注解的事务,使用XML配置形式的事务(比较重要的都是使用配置式)-->
        <aop:config>
            <!--切入点表达式-->
            <aop:pointcut id="txPoint" expression="execution(* com.wybing.curd.service..*(..))"/>
            <!--配置事务增强-->
            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint" ></aop:advisor>
        </aop:config>
    
        <!--配置事务增强,事务如何切入-->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <!--所有方法都是事务方法-->
                <tx:method name="*" />
                <!--以get开始的所有方法-->
                <tx:method name="get*" read-only="true" />
            </tx:attributes>
        </tx:advice>
    </beans>
    

    四、配置mybatis-config.xml(Mybatis配置文件)

    4.1配置mybatis-config.xml

    在src/main/resources/ 新建 mybatis-config.xml 文件
    Mybatis配置参考:
    https://mybatis.org/mybatis-3/zh/getting-started.html#

    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>
        <settings>
            <!-- 驼峰命名规则 -->
            <setting name="mapUnderscoreToCamelCase" value="true"></setting>
        </settings>
        <typeAliases>
            <package name="com.wybing.crud.bean"></package>
        </typeAliases>
    
        <plugins>
            <!-- com.github.pagehelper为PageHelper类所在包名 -->
            <plugin interceptor="com.github.pagehelper.PageInterceptor">
                <!-- 使用下面的方式配置参数,后面会有所有的参数介绍 -->
                <!--分页参数合理化-->
                <property name="reasonable" value="true"/>
            </plugin>
        </plugins>
    </configuration>
    

    4.2 新建数据库ssm_crud

    两张表:(图表一:tbl_emp、图表二:tbl_dept)
    图表一:tbl_emp
    图表二:tbl_dept
    约束:fk_emp_dept
    约束fk_emp_dept

    4.3 使用 mybatis generator

    参考官网:https://mybatis.org/generator/quickstart.html
    1.引入jar包
    在 pom.xml 文件中添加依赖

        <!--MBG  mybatis.generator 代码生成-->
        <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
        <dependency>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-core</artifactId>
          <version>1.3.5</version>
        </dependency>
    

    2.在 pom.xml 同级目录新建 mbg.xml 文件
    配置参考:https://mybatis.org/generator/configreference/xmlconfig.html

    代码:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE generatorConfiguration
            PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
            "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    
    <generatorConfiguration>
        <!--配置数据库连接信息-->
        <context id="DB2Tables" targetRuntime="MyBatis3">
            <!--让生成的bean,dao等文件没有注释-->
            <commentGenerator>
                <property name="suppressAllComments" value="true" />
            </commentGenerator>
    
            <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                            connectionURL="jdbc:mysql://localhost:3305/ssm_crud?useSSL=false"
                            userId="root"
                            password="root">
            </jdbcConnection>
            <!--Java类型解析-->
            <javaTypeResolver >
                <property name="forceBigDecimals" value="false" />
            </javaTypeResolver>
            <!--Java模型生成 , 指定Java bean生成位置-->
            <javaModelGenerator targetPackage="com.wybing.curd.bean" targetProject=".srcmainjava">
                <property name="enableSubPackages" value="true" />
                <property name="trimStrings" value="true" />
            </javaModelGenerator>
            <!--指定SQL映射文件生成的位置-->
            <sqlMapGenerator targetPackage="mapper"  targetProject=".srcmain
    esources">
                <property name="enableSubPackages" value="true" />
            </sqlMapGenerator>
            <!--指定dao接口生成的位置,mapper接口-->
            <javaClientGenerator type="XMLMAPPER" targetPackage="com.wybing.curd.dao"  targetProject=".srcmainjava">
                <property name="enableSubPackages" value="true" />
            </javaClientGenerator>
            <!--指定每个表的生成策略-->
            <table tableName="tbl_emp" domainObjectName="Employee"></table>
            <table tableName="tbl_dept" domainObjectName="Department"></table>
    
        </context>
    </generatorConfiguration>
    

    3.在src/main/java/com/wybing/curd/test 下新建 MBGTest.java
    代码如下:

    package com.wybing.curd.test;
    
    import org.mybatis.generator.api.MyBatisGenerator;
    import org.mybatis.generator.config.Configuration;
    import org.mybatis.generator.config.xml.ConfigurationParser;
    import org.mybatis.generator.exception.InvalidConfigurationException;
    import org.mybatis.generator.exception.XMLParserException;
    import org.mybatis.generator.internal.DefaultShellCallback;
    
    import java.io.File;
    import java.io.IOException;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * ClassName:    MBGTest
     * Package:    com.wybing.curd.test
     * Description:
     * Datetime:    2021/7/6   10:18
     * Author:   wybing(wybingcom@126.com)
     */
    
    /**
     * 报错:
     * 1.Exception in thread "main" java.sql.SQLException: Unable to load authentication plugin 'caching_sha2_password'.
     *      主要原因8.x版本的验证模块和之前版本不同:
     *      5.x版本是:default_authentication_plugin=mysql_native_password
     *      8.x版本就是:default_authentication_plugin=caching_sha2_password
     * 解决办法:
     *      更新mysql驱动的jar版本,可以修改为8.0.11版本
     */
    
    public class MBGTest {
        public static void main(String[] args) throws InterruptedException, SQLException, IOException, XMLParserException, InvalidConfigurationException {
            List<String> warnings = new ArrayList<String>();
            boolean overwrite = true;
            // 指定配置文件名
            File configFile = new File("mbg.xml");
            ConfigurationParser cp = new ConfigurationParser(warnings);
            Configuration config = cp.parseConfiguration(configFile);
            DefaultShellCallback callback = new DefaultShellCallback(overwrite);
            MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
            myBatisGenerator.generate(null);
    
        }
    }
    
    

    4.运行 MBGTest.java 生成代码
    image
    看到有代码生成就可以了

    后面全是代码了,可参考项目源码:
    https://e.coding.net/qcloud_053214/UsualPracticeCode/ssm_crud.git
    https://github.com/SAIKA952/SSM-CRUD
    博客:

    https://blog.csdn.net/qq_32953185/category_8120255.html
    https://www.cnblogs.com/wybing/p/15026360.html

  • 相关阅读:
    课堂派题库格式转换程序
    操作系统——进程的状态与转换
    android 通用 Intent
    android上使用蓝牙设备进行语音输入
    讯飞语音听写中数字规整问题
    【Android】隐藏底部虚拟按键
    AudioEffect中文API
    为什么要在onNewIntent的时候要显示的去调用setIntent
    android蓝牙耳机下的语音(输入/识别)及按键监听
    Android如何监听蓝牙耳机的按键事件
  • 原文地址:https://www.cnblogs.com/wybing/p/15026596.html
Copyright © 2011-2022 走看看