Sprin6 MVC 第三章 SSM 配置

1. 依赖

xml 复制代码
  <dependencies>
    <!--springmvc-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>6.2.0</version>
    </dependency>
    <!--spring jdbc-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>6.2.0</version>
    </dependency>
    <!--mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.17</version>
    </dependency>
    <!--mybatis spring-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>3.0.4</version>
    </dependency>
    <!--mysql驱动-->
    <dependency>
      <groupId>com.mysql</groupId>
      <artifactId>mysql-connector-j</artifactId>
      <version>8.4.0</version>
    </dependency>
    <!--德鲁伊连接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.2.24</version>
    </dependency>
    <!--jackson-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.18.1</version>
    </dependency>
    <!--servlet api-->
    <dependency>
      <groupId>jakarta.servlet</groupId>
      <artifactId>jakarta.servlet-api</artifactId>
      <version>6.0.0</version>
      <scope>provided</scope>
    </dependency>
    <!--logback-->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.5.12</version>
    </dependency>
    <!--thymeleaf和spring6的整合依赖-->
    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf-spring6</artifactId>
      <version>3.1.2.RELEASE</version>
    </dependency>
  </dependencies>

2. 目录结构

3. Mybatis

1. 数据库源文件

  • jdbc.properties
java 复制代码
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybait?useUnicode=true&serverTimezone\
  =Asia\
  /Shanghai&useSSL=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=1234

2. 配置数据源

java 复制代码
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;
// 读数据源的配置文件
@PropertySource("classpath:jdbc.properties") 
// 数据源的配置文件
public class DataSourceConfig {
  @Value("${jdbc.driver}")
  private String driver;

  @Value("${jdbc.url}")
  private String url;

  @Value("${jdbc.username}")
  private String username;

  @Value("${jdbc.password}")
  private String password;

  @Bean
  public DataSource dataSource(){
    // 使用德鲁伊连接池
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setDriverClassName(driver);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    return dataSource;
  }
   //  事务管理对象
  @Bean
  public PlatformTransactionManager platformTransactionManager(DataSource dataSource){
    DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
    dataSourceTransactionManager.setDataSource(dataSource);
    return dataSourceTransactionManager;
  }
}
  • xml
xml 复制代码
<!--  数据源-->
  <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${jdbc.driver}"/>
    <property name="url" value="${jdbc.url}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
  </bean>

3. Mybatis配置

java 复制代码
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

// 开启事务
@EnableTransactionManagement
public class MyBatisConfig {

  @Bean
  public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    // 数据源,dataSource自动获取上面类中的德鲁伊连接池数据源
    sqlSessionFactoryBean.setDataSource(dataSource);
    //  注册实体类的别名
    sqlSessionFactoryBean.setTypeAliasesPackage("org.example.ssm.bean");
    return sqlSessionFactoryBean;
  }

  @Bean
  public MapperScannerConfigurer mapperScannerConfigurer(){
    MapperScannerConfigurer msc = new MapperScannerConfigurer();
    // mapper
    msc.setBasePackage("org.example.ssm.dao");
    return msc;
  }
}
  • xml
java 复制代码
<!--  配置maybatis相关-->
  <bean class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="typeAliasesPackage" value="com.example.bank.pojo"/>
  </bean>
  <!--Mapper 映射 -->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.example.bank.mapper"/>
  </bean>

4. Spring MVC

java 复制代码
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.thymeleaf.spring6.SpringTemplateEngine;
import org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring6.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;

import java.util.List;

@Configuration
// 扫描controller也就是handle文件夹,纳入spring管理
@ComponentScan("org.example.ssm.handler")
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {

  // 以下三个方法合并起来就是开启视图解析器
  @Bean
  public ThymeleafViewResolver getViewResolver(SpringTemplateEngine springTemplateEngine) {
    ThymeleafViewResolver resolver = new ThymeleafViewResolver();
    resolver.setTemplateEngine(springTemplateEngine);
    resolver.setCharacterEncoding("UTF-8");
    resolver.setOrder(1);
    return resolver;
  }

  @Bean
  public SpringTemplateEngine templateEngine(ITemplateResolver iTemplateResolver) {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(iTemplateResolver);
    return templateEngine;
  }

  @Bean
  public ITemplateResolver templateResolver(ApplicationContext applicationContext) {
    SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
    resolver.setApplicationContext(applicationContext);
    resolver.setPrefix("/WEB-INF/thymeleaf/");
    resolver.setSuffix(".html");
    resolver.setTemplateMode(TemplateMode.HTML);
    resolver.setCharacterEncoding("UTF-8");
    resolver.setCacheable(false);//开发时关闭缓存,改动即可生效
    return resolver;
  }

  // 开启静态资源处理,开启默认的Servlet处理
  @Override
  public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
  }

  // 视图控制器
  @Override
  public void addViewControllers(ViewControllerRegistry registry) {}
  // 配置异常处理器
  @Override
  public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {}

  // 配置拦截器
  @Override
  public void addInterceptors(InterceptorRegistry registry) {}
}
  • xml
xml 复制代码
 <!--  扫描-->
  <context:component-scan base-package="org.example.springmvc"/>
  <!--视图解析器-->
  <bean id="thymeleafViewResolver" class="org.thymeleaf.spring6.view.ThymeleafViewResolver">
    <!--作用于视图渲染的过程中,可以设置视图渲染后输出时采用的编码字符集-->
    <property name="characterEncoding" value="UTF-8"/>
    <!--如果配置多个视图解析器,它来决定优先使用哪个视图解析器,它的值越小优先级越高-->
    <property name="order" value="1"/>
    <!--当 ThymeleafViewResolver 渲染模板时,会使用该模板引擎来解析、编译和渲染模板-->
    <property name="templateEngine">
      <bean class="org.thymeleaf.spring6.SpringTemplateEngine">
        <!--用于指定 Thymeleaf 模板引擎使用的模板解析器。模板解析器负责根据模板位置、模板资源名称、文件编码等信息,加载模板并对其进行解析-->
        <property name="templateResolver">
          <bean class="org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver">
            <!--设置模板文件的位置(前缀)-->
            <property name="prefix" value="/WEB-INF/templates/"/>
            <!--设置模板文件后缀(后缀),Thymeleaf文件扩展名不一定是html,也可以是其他,例如txt,大部分都是html-->
            <property name="suffix" value=".html"/>
            <!--设置模板类型,例如:HTML,TEXT,JAVASCRIPT,CSS等-->
            <property name="templateMode" value="HTML"/>
            <!--用于模板文件在读取和解析过程中采用的编码字符集-->
            <property name="characterEncoding" value="UTF-8"/>
          </bean>
        </property>
      </bean>
    </property>
  </bean>
  <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
      <props>
        <!--用来指定出现异常后,跳转的视图-->
        <prop key="java.lang.Exception">tip</prop>
      </props>
    </property>
    <!--将异常信息存储到request域,value属性用来指定存储时的key。-->
    <property name="exceptionAttribute" value="e"/>
  </bean>
<!--  默认sevlet提供的静态资源管理器 -->
  <mvc:default-servlet-handler/>
<!--  注解驱动器 -->
  <mvc:annotation-driven/>
<!--  视图控制器-->
  <mvc:view-controller path="/" view-name="index"/>
<!--  配置拦截器,可配置多个拦截器,每个拦截器的路径可单独设置 -->
  <mvc:interceptors>
<!--    拦截器的执行顺序就时按照配置的顺序执行 -->
    <mvc:interceptor>
      <!--  拦截路径 -->
      <mvc:mapping path="/"/>
      <!--除 /test 路径之外-->
      <mvc:exclude-mapping path="/test"/>
      <bean class="org.example.springmvc.Interceptors.Interceptor1"/>
    </mvc:interceptor>
    <mvc:interceptor>
      <mvc:mapping path="/"/>
      <!-- 第二种引入方式:使用ref引入需要两个条件
        ①需要拦截器纳入spring管理,在类上加 @Component注解
        ②包扫描范围中
      -->
      <ref bean="interceptor2"/>
    </mvc:interceptor>
    <mvc:interceptor>
      <mvc:mapping path="/"/>
      <bean class="org.example.springmvc.Interceptors.Interceptor3"/>
    </mvc:interceptor>
  </mvc:interceptors>
</beans>

5. web.xml

java 复制代码
import jakarta.servlet.Filter;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;


public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
  /**
   * Spring的配置
   * @return
   */
  @Override
  protected Class<?>[] getRootConfigClasses() {
    return new Class[]{SpringConfig.class};
  }

  /**
   * SpringMVC的配置
   * @return
   */
  @Override
  protected Class<?>[] getServletConfigClasses() {
    return new Class[]{SpringMvcConfig.class};
  }

  /**
   * 用来配置DispatcherServlet的 <url-pattern>
   * @return
   */
  @Override
  protected String[] getServletMappings() {
    return new String[]{"/"};
  }

  /**
   * 配置过滤器
   * @return
   */
  @Override
  protected Filter[] getServletFilters() {
    // 配置字符编码过滤器
    CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
    characterEncodingFilter.setEncoding("UTF-8");
    characterEncodingFilter.setForceResponseEncoding(true);
    characterEncodingFilter.setForceRequestEncoding(true);
    // 配置HiddenHttpMethodFilter
    HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
    return new Filter[]{characterEncodingFilter, hiddenHttpMethodFilter};
  }
}
  • xml
java 复制代码
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

6. Spring

java 复制代码
@Configuration
@ComponentScan({"org.example.ssm.service"}) // 扫描service包,纳入spring管理
@Import({DataSourceConfig.class, MyBatisConfig.class})  // 引入其他配置类
public class SpringConfig {
}
相关推荐
奕の辰17 天前
spring6:4、原理-手写IoC
java·spring·ioc·spring6
奕の辰18 天前
spring6:6、单元测试:JUnit
java·spring·junit·spring6
YUELEI11825 天前
Spring6 MVC 第二章
spring6
YUELEI1181 个月前
Spring6 Transactional 事务
事务·spring6
代码代码快快显灵1 个月前
Spring6
java·spring boot·spring6
zoeil1 年前
spring6-提前编译:AOT
java·服务器·后端·spring·aot·spring6·提前编译
zoeil1 年前
spring6-国际化:i18n | 数据校验:Validation
java·后端·spring·i18n·spring6·validation
阿杰学编程1 年前
1、Spring是什么?
java·后端·spring·spring6