SSM框架整合

目录

1、新建Maven项目, 添加web的支持

2、导入相关的pom依赖

3、Maven资源过滤设置

4、建立基本结构和配置框架!

6、Spring层

7、SpringMVC层

8、编写Controller层

9、编写jsp

10、运行排错


1、新建Maven项目, 添加web的支持

2、导入相关的pom依赖

<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-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>
</dependencies>

3、Maven资源过滤设置

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

4、建立基本结构和配置框架!

4.1、tln.pojo

4.2、tln.dao

4.3、tln.service

4.4、tln.controller

4.5、mybatis-config.xml

4.6、applicationContext.xml,也就是Spring的配置文件spring.xml 

4.7、spring-dao.xml,整合dao层和连接数据库

4.8、spring-service.xml,整合service层

4.9、spring-mvc.xml,整合controller层 

5、Mybatis层编写

5.1、编写数据库表

create table `books`(
    `bookID` int(10) NOT NULL  AUTO_INCREMENT COMMENT '书id',
    `bookName` varchar(50) NOT NULL COMMENT '书名',
    `bookCounts` int(11) NOT NULL COMMENT '数量',
    `detail` varchar(200) NOT NULL  COMMENT '描述',
    KEY `bookID` (`bookID`)
)ENGINE = INNODB DEFAULT CHARSET =utf8;

insert into `books`(`bookID`,`bookName`,`bookCounts`,`detail`) values
(1,'java',1,'二分'),(2,'Mysql',10,'从入门到放弃'),(3,'Linux',5,'从删库到跑路');

5.2、IDEA连接数据库

5.3、编写Mybaties核心配置文件

<?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>
    <!--配置数据源jiaogeiSpring去做-->

    <!--  typeAliases降低冗余的全限定类名书写。可以直接在mapper.xml中使用自定义的名字  -->
    <typeAliases>
        <!--可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,包下的类建议使用时首字母小写,这样可以看出是扫描包的情况。-->
        <package name="tln.pojo"/>
    </typeAliases>
    <!-- 使用mapper给每个.xml注册-->
    <mappers>
        <!--  class方式需要接口和配置文件都在一个包下,且只能一个一个配置
        resource可以直接给所有.xml文件注册
        -->
        <mapper resource="tln/dao/BookMapper.xml"/>
        <!--        <mapper resource="dao/*.xml"/>-->
    </mappers>
</configuration>

5.4、编写数据库对应的实体类 tln.pojo.Books

package tln.pojo;

/**
 * @autor
 * @creat 2022-02-23 21:18
 */
public class Books {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;

    @Override
    public String toString() {
        return "Books{" +
                "bookID=" + bookID +
                ", bookName='" + bookName + '\'' +
                ", bookCounts=" + bookCounts +
                ", detail='" + detail + '\'' +
                '}';
    }

    public int getBookID() {
        return bookID;
    }

    public void setBookID(int bookID) {
        this.bookID = bookID;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public int getBookCounts() {
        return bookCounts;
    }

    public void setBookCounts(int bookCounts) {
        this.bookCounts = bookCounts;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

    public Books() {
    }

    public Books(int bookID, String bookName, int bookCounts, String detail) {
        this.bookID = bookID;
        this.bookName = bookName;
        this.bookCounts = bookCounts;
        this.detail = detail;
    }
}

5.5、编写Dao层的 Mapper接口!

public interface BookMapper {
    public void addBook(Book book);
    public int deleteBookById(int id);
    public int updateBook(Book book);
    public Book queryBook(String name);
    public List<Book> queryBooks();
}

 5.6、编写接口对应的 Mapper.xml 文件。需要在MyBatis中注册;

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE mapper
         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <mapper namespace="tln.dao.BookMapper">
     <insert id="addBook" parameterType="Books">
         insert into mybatis.books (bookName,bookCounts,detail)
         values(#{bookName},#{bookCounts},#{detail});
     </insert>
     <delete id="deleteBookById" >
         delete from mybatis.books where bookID=#{bookID};
     </delete>
     <update id="updateBook" parameterType="Books">
         update  mybatis.books
         set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
         where bookID=#{bookID};
     </update>
     <select id="queryBook" resultType="Books">
         select * from mybatis.books where bookName=#{bookName};
     </select>
     <select id="queryBooks" resultType="Books">
         select * from mybatis.books;
     </select>
 </mapper>

5.7、编写service层的接口BookService

public interface BookService {

  //增加一本书
  int add(Book book);
  //根据ID删除一本书
  int delete(int bookID);
  //修改一本书
  int update(Book book);
  //查找一本书根据名字
  Book query(String bookName);
  //显示所有书籍信息
  List<Book> queryAll();

}

5.8、编写service层的实现类

public class BookServiceImpl implements BookService{

  private BookMapper bookMapper;
  //设置一个set接口,可以随意更改底层接口
  public void setBookMapper(BookMapper bookMapper) {
      this.bookMapper = bookMapper;
  }
  @Override
  public int add(Book book) {
      return bookMapper.addBook(book);
  }
  @Override
  public int delete(int bookID) {
      return bookMapper.deleteBookById(bookID);
  }
  @Override
  public int update(Book book) {
      return bookMapper.updateBook(book);
  }
  @Override
  public Book query(String bookName) {
      return bookMapper.queryBook(bookName);
  }
  @Override
  public List<Book> queryAll() {
      return bookMapper.queryBooks();
  }
}

6、编写Controller层

controller主要就是在调用service层

@Controller
@RequestMapping("/book")
public class BookController {
    //bookService注入spring-service
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;
    @RequestMapping("/allBook")
    public String allBook(Model model){
        List<Books> books = bookService.queryAll();
        model.addAttribute("books",books);
        return "allBook";
    }
}

7、SpringMVC层

1、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">
    <!--    DispatchServlet-->
    <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:spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--乱码过滤-->
    <filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

2、配置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
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
    <context:component-scan base-package="tln.controller"/>
    <!-- 让Spring MVC不处理静态资源如:css js html MP4 -->
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>
    <!--
    支持mvc注解驱动
        在spring中一般采用@RequestMapping注解来完成映射关系
        要想使@RequestMapping注解生效
        必须向上下文中注册DefaultAnnotationHandlerMapping
        和一个AnnotationMethodHandlerAdapter实例
        这两个实例分别在类级别和方法级别处理。
        而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>

8、Spring层

1、配置Spring整合MyBatis,这里数据源使用c3p0连接池,导入相关依赖,随后在spring-dao.xml文件中配置;

2、配置spring-dao.xml文件

首先创建数据库配置文件 database.properties,spring-dao中会进行数据库连接

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
<?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">
  <!-- 配置整合mybatis -->
  <!-- 1.关联数据库文件 -->
  <context:property-placeholder location="classpath:database.properties"/>
  <!--   Datasource:使用Spring的数据源替换Mybatis的配置  c3p0    dbcp    druid
      -->
  <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>

  <!--3、配置sqlSessionFactory对象-->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <!--注入数据库连接池-->
      <property name="dataSource" ref="datasource"/>
      <!--绑定mybatis配置文件,自己改动-->
      <property name="configLocation" value="classpath:mybatis-config.xml"/>
  </bean>

  <!-- 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="tln.dao"/>
  </bean>
</beans>

3、spring整合service层

<?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">
    <!--   1、扫描service下的包-->
    <context:component-scan base-package="tln.service"/>
    <!--    2、将我们所有的业务类,注入到spring,可以通过配置或者注解实现-->
    <bean id="BookServiceImpl" class="tln.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>
    <!--    3、声明式事务配置-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--        注入数据源,是spring-dao中定义的那个名字-->
        <property name="dataSource" ref="datasource"/>
    </bean>
    <!--    4、aop事务支持-->

</beans>

4、spring关联spring-dao和spring-service和spring-mvc

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

    <!--关联spring-dao和spring-service和spring-mvc-->
    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-mvc.xml"/>

</beans>

9、编写jsp

<body>
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-head">
                <h1>
                    <small>书籍列表--------显示所有书籍</small>
                </h1>
            </div>
        </div>
    </div>
    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <th>书籍编号</th>
                    <th>书籍名称</th>
                    <th>书籍数量</th>
                    <th>书籍详情</th>
                </tr>
                </thead>
                <%--                从数据库查询出来的,从list中遍历出来--%>
                <tbody>

                <c:forEach var="book" items="${booklist}">
                    <tr>
                        <td>${book.bookID}</td>
                        <td>${book.bookName}</td>
                        <td>${book.bookCounts}</td>
                        <td>${book.detail}</td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>

10、运行排错

当Bean找不到时:

        1、查看这个Bean注入是否成功(spring-service中已经将其注入到spring)

        2、junit单元测试,看代码是否能够查询出结果

public class BookServiceImplTest {
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        BookService bookServiceImpl = (BookService) context.getBean("BookServiceImpl");
        for (Books books : bookServiceImpl.queryAll()) {
            System.out.println(books);
        }
    }
}

        3、问题出现在spring层,springMVC整合的时候没调用到service层的bean
             3.1、spring.xml中注入bean
             3.2、web.xml中,绑定配置文件时DispatchServlet应绑定spring.xml总配置文件路径

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值