SpringMVC-ssm案例-2023-04-23

一、准备工作

1.1、搭建普通maven项目,framework的 web项目

1.2、加载maven依赖:junit - mysql-connector-C3P01  

                                 servlet-jsp / JSTL

                                 MyBatis   MyBatis-spring

                                 spring-webmvc / jdbc

                                 lombok

                                 build 资源加载问题

1.3、加载Project Structure --- > lib

1.4、连接数据库

1.5、建包   com.feijian.pojo/service/dao/controller

1.6、配置 mybatis-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 核心配置文件 -->
<configuration>

</configuration>

1.7、配置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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

</beans>

二、编写MyBatis层

2.1  配置:database.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

2.2 Idea连接数据库 ssmbuild

2.3 在mybatis-config.xml文件中 增加配置 :1、别名  2、BookMapper.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>
    <!--别名-->
    <typeAliases>
        <package name="com.feijian.pojo"/>
    </typeAliases>
    <mappers>
        <mapper resource="com/feijian/dao/BookMapper.xml"/>
    </mappers>
</configuration>

2.4 编写pojo 实体例。采用注解  @Data @AllargsConstructor  @ NoargsConstructor

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
}

2.5 写dao接口类

public interface BookMapper {
    //增加一个Book
    int addBook(Books book);
    //根据id删除一个Book
    int deleteBookById(int id);
    //更新Book
    int updateBook(Books books);
    //根据id查询,返回一个Book
    Books queryBookById(int id);
    //查询全部Book,返回list集合
    List<Books> queryAllBook();

 2.6 写dao接口类的 BookMapper.xml (MySql语句,用.xml文件代替接口实现类。增删改查 select / insert / update / delete )

<?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">
<mapper namespace="com.feijian.dao.BookMapper">

    <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books (bookName, bookCounts, detail)
        VALUES (#{bookName},#{bookCounts},#{detail});
    </insert>
    <delete id="deleteBookById" parameterType="int">
        delete from ssmbuild.books where bookID = #{bookId};
    </delete>
    <update id="updateBook" parameterType="books">
        update ssmbuild.books
        set bookName = #{bookName} , bookCounts = #{bookCounts},detail=#{detail}
        where bookID = #{bookID};
    </update>
    <select id="queryBookById" resultType="books">
        select * from ssmbuild.books where bookID = #{bookId};
    </select>
    <select id="queryAllBook" resultType="books">
        select * from ssmbuild.books;
    </select>
</mapper>

 2.7 写Service接口类

public interface BookService {
    //增加一个Book
    int addBook(Books book);
    //根据id删除一个Book
    int deleteBookById(int id);
    //更新Book
    int updateBook(Books books);
    //根据id查询,返回一个Book
    Books queryBookById(int id);
    //查询全部Book,返回list集合
    List<Books> queryAllBook();

2.8 写Service 实现类

public class BookServiceImpl implements BookService {
    //service业务层调dao层 : 组合Dao
    private BookMapper bookMapper;
    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }
    public int addBook(Books books) {
        return bookMapper.addBook(books);
    }
    public int deleteBookById(int id) {return bookMapper.deleteBookById(id);}
    public int updateBook(Books books) {
        return bookMapper.updateBook(books);
    }
    public Books queryBookById(int id) {
        return bookMapper.queryBookById(id);
    }
    public List<Books> queryAllBook() {
        return bookMapper.queryAllBook();
    }

 三、配置   (Spring 整合MyBatis 和 Service )

3.1 Spring 整合 dao层- MyBatis 连接数据库  spring-dao.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"
       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.关联数据库配置文件-->
    <context:property-placeholder location="classpath:database.properties" />

    <!--2.数据库连接池
        dbcp : 半自动化操作,不能自动连接
        c3p0 : 自动化操作(自动化的加载配置文件,而且可以自动设置到对象中!)
        druid ; hikari;
    -->
    <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容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--注入SqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <!-- 需要扫描Dao接口包 -->
        <property name="basePackage" value="com.feijian.dao" />
    </bean>
</beans>

3.2 Spring 整合Service层 spring-service.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"
       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="com.feijian.service" />

    <!--2.将我们的所有业务类,注入到Spring,可以通过配置,或者注解实现-->
    <bean id="BookServiceImpl" class="com.feijian.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper" />
    </bean>
    <!--3.声明式事务配置-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!--4.aop事务支持-->
</beans>

四、SpringMVC层 

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

    <!--DispatcherServlet-->
    <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:applicationContext.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>
    <!--乱码过滤-->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

4.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: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">
    <!--1.注解驱动-->
    <mvc:annotation-driven />
    <!--2.静态资源过滤-->
    <mvc:default-servlet-handler />
    <!--3.扫描包:controller-->
    <context:component-scan base-package="com.feijian.controller" />
    <!--4.视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!--后缀-->
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

 4.3 applicationContext.xml 导入 三个.xml文件   

第一个为:spring-dao.xml    数据库连接 也导入:database.properties   其中:spring-dao.xml中绑定了mybatis-config.xml  

<!--1.关联数据库配置文件-->
<context:property-placeholder location="classpath:database.properties" />
<!--绑定Mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml" />

第二个为:spring-service.xml 

第三个为: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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <import resource="spring-mvc.xml"/>
    <import resource="spring-dao.xml"/>
    <import resource="spring-service.xml"/>

</beans>

 五、Controller层 和视图层编写  在WEB-INF/下新建jsp文件夹 之后的用户自定义页面放这个文件夹之下

5.1 写Controller类

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    @Qualifier("BookServiceImpl")
    BookService bookService;
    //查询全部书籍,并返回一个书籍展示页面
    public String list(Model model){
        List<Books> books = bookService.queryAllBook();
        model.addAttribute("list",books);
        return "allBook";
    }
}

5.2 编写index.jsp 首页页面元素  注意跳转的响应 “/book/allBook”-点击就根据这个响应去controller层去找对应这个响应的方法,找到后执行方法,return的就是要转发的新地址

     通过视图解析器,将return返回的值进行前后缀拼装

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>首页</title>
  <style>
    a{
      text-decoration: none;
      color: black;
      font-size: 18px;
    }
    h3{
      width: 180px;
      height: 38px;
      margin: 100px auto;
      text-align: center;
      line-height: 38px;
      background: deepskyblue;
      border-radius: 5px;
    }
  </style>
</head>
<body>
<h3>
  <a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a>
</h3>
</body>
</html>

5.3 写allBook.jsp页面

 

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>书籍展示页面</title>
    <%--BootStrap美化界面--%>
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>书籍列表 ———— 显示所有书籍</small>
                </h1>
            </div>
        </div>
    </div>
    <div class="col-md-4 column">
        <%--跳转到添加书籍页面--%>
        <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增书籍</a>
        <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/allBook">显示全部书籍</a>
    </div>
    <div class="col-md-4 column"></div>
    <div class="col-md-4 column">
        <%--查询书籍--%>
        <form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float: right">    <%--form-inline:将按键显示在一行--%>
            <span style="color: red;font-weight: bold">${error}</span>
            <input type="text" name="queryBookName" class="form-control" placeholder="请输入要查询的书籍名称">   <%--placeholder:提示信息--%>
            <input type="submit" value="查询" class="btn bt-primary">
        </form>
    </div>
    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped"><%--table-hover:鼠标放上发亮,table-striped:隔行变色--%>
                <thead>
                <tr>
<%--                <th>书籍编号</th>--%>
                    <th>书籍名称</th>
                    <th>书籍数量</th>
                    <th>书籍详情</th>
                </tr>
                </thead>
                <%--书籍从数据库中查询出来,从这个list中遍历出来--%>
                <tbody>
                <c:forEach var="book" items="${list}">
                    <tr>
<%--                    <td>${book.bookID}</td>--%>
                        <td>${book.bookName}</td>
                        <td>${book.bookCounts}</td>
                        <td>${book.detail}</td>
                        <td>
                            <a href="${pageContext.request.contextPath}/book/toUpdateBook/${book.bookID}">修改</a>
                            &nbsp; | &nbsp;
                            <a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除</a>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

 六、Tomcat 调试第一个页面 -查询所有书籍功能实现

 

 

 

 

 

 

 

 

 

 

posted @ 2023-04-23 21:03  Rui2022  阅读(18)  评论(0编辑  收藏  举报