SSM整合笔记(超详细)

SSM+

  • 环境
  1. MySQL7
  2. Maven3
  3. IDEA
  4. Tomcat
  • 基本架构

SSM整合笔记(超详细)_第1张图片

1 Spring环境搭建

1.1 创建好项目后导入Spring和Junit包

<dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.2.0.RELEASEversion>
        dependency>
    
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.1version>
            <scope>testscope>
        dependency>
dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.1version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                configuration>
            plugin>
        plugins>
    build>

1.2 Spring核心配置文件applicationContext.xml

  • 创建实体类
// 此处使用lombok懒人工具,建议老老实实alt+ins生成get、set,构造器等
@Data
public class Hello {
     
    private String name;
    private int age ;
}
  • 核心配置文件(applicationContext.xml)

<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">
    <bean id="hello" class="priv.zwh.mall.pojo.Hello">
        
        <property name="name" value="Spring"/>
    bean>
beans>
  • 测试
public class TestHello {
     
    @Test
    public void test() {
     
        // 获取上下文对象
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        // 从上下文对象中获取对象
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.getName());
    }
}

2 Mybatis环境搭建

2.1 数据库搭建

CREATE DATABASE `mybatis`;
USE `mybatis`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(20) NOT NULL,
`name` varchar(30) DEFAULT NULL,
`pwd` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert  into `user`(`id`,`name`,`pwd`) values (1,'狂神','123456'),(2,'张三','abcdef'),(3,'李四','987654');

2.2 导入Mybatis相关jar

<dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>3.5.2</version>
</dependency>
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.47</version>
</dependency>
 <!--静态资源过滤问题(放入build标签中)-->
<resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties
                    **/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties
                    **/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
</resources>

2.3 编写Mybatis核心配置文件



<configuration>
    
    <settings>
        
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    settings>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                
                <property name="url"
                          value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8"/>
                
                <property name="username" value="root"/>
                
                <property name="password" value="123456"/>
            dataSource>
        environment>
    environments>
    
    <mappers>
        <package name="priv.zwh.mall.dao.test"/>
    mappers>
configuration>

2.4 编写Mybatis工具类

public class MybatisUtils {
     
   private static SqlSessionFactory sqlSessionFactory;
   static {
     
       try {
     
           String resource = "mybatis-config.xml";
           // 注意导入的是org.apache.ibatis.io下的Resource
           InputStream inputStream =Resources.getResourceAsStream(resource);
           sqlSessionFactory = newSqlSessionFactoryBuilder().build(inputStream);
      } catch (IOException e) {
     
           e.printStackTrace();
      }
  }
   //获取SqlSession连接
   public static SqlSession getSession(){
     
       return sqlSessionFactory.openSession();
  }
}

2.5 编写Mapper接口类

public interface UserMapper {
     
   List<User> selectUser();
}

2.6 编写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">
    // 注意namespace全限定类名
<mapper namespace="priv.zwh.mall.dao.test.UserMapper">
    <select id="selectUser" resultType="priv.zwh.mall.pojo.User">
        select id,name,pwd from user
    </select>
</mapper>

2.7 Junit测试

public class TestUser {
     
   @Test
   public void selectUser() {
     
       SqlSession session = MybatisUtils.getSession();
       //方法一:
       // System.out.println(session.selectList("priv.zwh.mall.dao.test.UserMapper.selectUser"));
       //方法二:
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> users = mapper.selectUser();
        for (User user : users) {
     
            System.out.println(user);
        }
        // 一定要记得关闭
       session.close();
    }
}

3 SpringMVC环境搭建

3.1 导入SpringMVC相关jar

<dependencies>
   <dependency>
       <groupId>junitgroupId>
       <artifactId>junitartifactId>
       <version>4.12version>
   dependency>
   <dependency>
       <groupId>org.springframeworkgroupId>
       <artifactId>spring-webmvcartifactId>
       <version>5.1.9.RELEASEversion>
   dependency>
   <dependency>
       <groupId>javax.servletgroupId>
       <artifactId>servlet-apiartifactId>
       <version>2.5version>
   dependency>
   <dependency>
       <groupId>javax.servlet.jspgroupId>
       <artifactId>jsp-apiartifactId>
       <version>2.2version>
   dependency>
   <dependency>
       <groupId>javax.servletgroupId>
       <artifactId>jstlartifactId>
       <version>1.2version>
   dependency>
dependencies>

3.2 配置web.xml(如果是maven工程还需添加骨架支持)


<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">
    <servlet>
        <servlet-name>servletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        
        <init-param>
            
            <param-name>contextConfigLocationparam-name>
            
            <param-value>classpath:springmvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>servletservlet-name>
        <url-pattern>*.dourl-pattern>
    servlet-mapping>
web-app>

3.3 编写SpringMVC配置文件

  • 方式一

<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">
        
        <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">bean>
        
        <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter">bean>
        
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
            
            <property name="prefix" value="/WEB-INF/jsp/">property>
            
            <property name="suffix" value=".jsp">property>
        bean>
        
         <bean id="/hello" class="com.srz.controller.HelloController">bean>
beans>
  • 方式二(常用)

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

    
    <context:component-scan base-package="priv.zwh.mall.controller"/>
    
    <mvc:default-servlet-handler/>
    
    <mvc:annotation-driven/>
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/jsp/"/>
        
        <property name="suffix" value=".jsp"/>
    bean>
beans>

3.4 Controller编写

@Controller
public class HelloController {
     
    @RequestMapping("/first")
    public String hello(Model model) {
     
        //封装数据
        model.addAttribute("msg", "Hello Spring");
        return "hello"; //会被视图解析器处理
    }
}

3.5 启动Tomcat进行测试

  • 404问题

SSM整合笔记(超详细)_第2张图片

  • 解决方法

SSM整合笔记(超详细)_第3张图片

  • 查看效果

SSM整合笔记(超详细)_第4张图片

4 通用项目构建模板

SSM整合笔记(超详细)_第5张图片

4.1 pom.xml


<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>org.examplegroupId>
    <artifactId>mallartifactId>
    <version>1.0-SNAPSHOTversion>
    
    <dependencies>
        
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.2.0.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.1version>
            <scope>testscope>
        dependency>
        
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.2version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.47version>
        dependency>
        
        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>2.5version>
        dependency>
        
        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>jsp-apiartifactId>
            <version>2.2version>
        dependency>
        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>
        
        <dependency>
            <groupId>com.mchangegroupId>
            <artifactId>c3p0artifactId>
            <version>0.9.5.2version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.1.9.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.4version>
        dependency>
    dependencies>
    
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.1version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                configuration>
            plugin>
        plugins>
        
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
        resources>
    build>
project>

4.2 Mybatis层编写

  • log4j配置文件参数(放在resources中)
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file

#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/zwh.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
  • 数据库配置文件编写,database.properties(放在resources中)
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
  • Mybatis核心配置文件,mybatis-config.xml


<configuration>
    
    <settings>
        <setting name="logImpl" value="log4j"/>
    settings>
    
    <typeAliases>
        <package name="priv.zwh.mall.pojo"/>
    typeAliases>
    
    <mappers>
        <mapper class="priv.zwh.mall.dao.BookMapper"/>
    mappers>
configuration>
  • Mapper.xml编写


<mapper namespace="com.kuang.dao.XXX">
  
mapper>

4.3 Spring层编写

  • Spring整合Mybatis,spring-dao.xml

<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">
    
    
    <context:property-placeholder location="classpath:database.properties"/>
    
    
    <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}"/>
        
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        
        <property name="autoCommitOnClose" value="false"/>
        
        <property name="checkoutTimeout" value="10000"/>
        
        <property name="acquireRetryAttempts" value="2"/>
    bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource"/>
        
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    bean>
    
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        
        <property name="basePackage" value="priv.zwh.mall.(dao)"/>
    bean>
beans>
  • Spring整合service层,spring-service

<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">

    
    <context:component-scan base-package="priv.zwh.mall.(service)"/>
    
    <bean id="bookServiceImpl" class="priv.zwh.mall.service.impl.(BookServiceImpl)">
        <property name="bookMapper" ref="bookMapper"/>
    bean>
    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        
        <property name="dataSource" ref="dataSource"/>
    bean>
beans>

4.4 SpringMVC层编写

  • web.xml

<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">
   
   <servlet>
       <servlet-name>DispatcherServletservlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
       <init-param>
           <param-name>contextConfigLocationparam-name>
             
           <param-value>classpath:applicationContext.xmlparam-value>
       init-param>
       <load-on-startup>1load-on-startup>
   servlet>
   <servlet-mapping>
       <servlet-name>DispatcherServletservlet-name>
       <url-pattern>/url-pattern>
   servlet-mapping>
   
   <filter>
       <filter-name>encodingFilterfilter-name>
       <filter-class>
          org.springframework.web.filter.CharacterEncodingFilter
       filter-class>
       <init-param>
           <param-name>encodingparam-name>
           <param-value>utf-8param-value>
       init-param>
   filter>
   <filter-mapping>
       <filter-name>encodingFilterfilter-name>
       <url-pattern>/*url-pattern>
   filter-mapping>
   
   <session-config>
       <session-timeout>15session-timeout>
   session-config>
web-app>
  • spring-mvc.xml

<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">
    
    <mvc:annotation-driven/>
    
    <mvc:default-servlet-handler/>
    
    <context:component-scan base-package="priv.zwh.mall.controller"/>
    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/jsp/"/>
        
        <property name="suffix" value=".jsp"/>
    bean>
beans>
  • Spring配置整合文件,applicationContext.xml

<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="springmvc-config.xml"/>
beans>

你可能感兴趣的:(SSM整合笔记(超详细))