SSM框架整合

   日期:2020-04-29     浏览:111    评论:0    
核心提示:前言刚学完SSM框架的时候,感觉整合还是很简单的,但是,等过了一段时间之后,再回过头来用SSM框架写javascript

前言

刚学完SSM框架的时候,感觉整合还是很简单的,但是,等过了一段时间之后,再回过头来用SSM框架写项目的时候,感觉既熟悉又陌生,所以,本人就复习一下,并且写这一篇博客记录相关知识。

1.创建数据库

CREATE DATABASE `ssmbuild`;

USE `ssmbuild`;

DROp TABLE IF EXISTS `books`;

CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) 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,'从进门到进牢');

2.创建项目

1)首先创建一个maven项目,添加web支持,在pom.xml中导入依赖

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

2)创建相关包
ewen.dao
ewen.pojo
ewen.service
ewen.controller
在resource目录下,创建mapper、spring文件夹

3.mybatis 相关配置

1)创建mybatis-connfig.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>
  
</configuration>

2)创建jdbc.properties

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

3)创建实体类

 private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;
    //get 、set 方法,构造函数

4)在dao包中创建BookMapper接口

 	public interface BookMapper {
	    public int insert(Book book);
	    public int delete(Book book);
	    public int update(Book book);
	    public Book queryByBookId(int id);
	    public List<Book> queryAll();
	    public Book queryByBookName(String bookName);
}

5)在mapper文件加下创建BookMapper.xml,编写SQL语句

<?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="ewen.dao.BookMapper">
    <!--添加书-->
    <select id="insert" resultType="int" parameterType="Book">
        insert into books
        (bookName,bookCounts,detail)
        values
        (#{bookName},#{bookCounts},#{detail});
    </select>

    <!--删除书-->
    <delete id="delete" parameterType="int">
        delete from books where bookID = #{bookID}
    </delete>

    <!--修改书-->
    <update id="update" parameterType="Book">
        update books set bookName = #{bookName}, bookCounts = #{bookCounts}, detail = #{detail}
        where bookID = #{bookID}
    </update>

    <!--通过id查询书-->
    <select id="queryByBookID" parameterType="int" resultType="Book">
        select * from books where bookID = #{bookID}
    </select>

    <!--查询所有书-->
    <select id="queryAll" resultType="Book">
        select * from books
    </select>
    
    <!--根据书名进行查询-->
    <select id="queryByBookName" resultType="Book" parameterType="String">
        select * from books where bookName = #{bookName}
    </select>
</mapper>

6)编写service层的接口和实现类
BookService接口:

public interface BookService {
    public int insert(Book book);
    public int delete(Book book);
    public int update(Book book);
    public Book queryByBookId(int id);
    public List<Book> queryAll();
}

实现类:

public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;

    public int insert(Book book) {
        return bookMapper.insert(book);
    }

    public int delete(Book book) {
        return bookMapper.delete(book);
    }

    public int update(Book book) {
        return bookMapper.update(book);
    }

    public Book queryByBookId(int id) {
        return bookMapper.queryByBookId(id);
    }

    public List<Book> queryAll() {
        return bookMapper.queryAll();
    }
}

4.spring整合mybatis

在spring文件夹下创建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">

    <!--加载数据库连接的配置文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--配置c3p0连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--配置连接池属性-->
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="jdbcUrl" value="${jdbc.url}" />

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

    <!--配置sqlSessionFactory对象-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入连接池-->
        <property name="dataSource" ref="dataSource"/>

        <!--配置mybatis核心配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>

        <!--开启别名-->
        <property name="typeAliasesPackage" value="ewen.pojo"/>

        <!-- 扫描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!--用扫描包的形式配置mapper,动态实现Dao接口,注入到spring容器中 -->
    <bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--注入sqlSessionFactory对象-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--给出需要扫描的dao接口-->
        <property name="basePackage" value="ewen.dao"/>
    </bean>
</beans>

5.Spring整合service层

在spring文件夹下创建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">

    <!--配置service扫描,扫描service包下所有使用注解的类型-->
    <context:component-scan base-package="ewen.service"/>
</beans>

6.配置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">

    <!--配置核心控制器-->
    <servlet>
        <servlet-name>ssm</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <!--加载总的核心配置文件-->
        <init-param>
            <param-name>ContextConfigLocation</param-name>
            <param-value>classpath:spring/spring-*.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ssm</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> 

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

    <!--配置包扫描器-->
    <context:component-scan base-package="ewen.controller"/>

    <!--配置springmvc的注解驱动-->
    <mvc:annotation-driven/>

    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

到这里框架就整合好了,整个项目的架构如图:

下面写一个简单的增删改查操作
前端页面简单使用bootstrap
1.书籍列表页面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>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 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="row">
            <div class="col-md-4 column" >
                <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toInsert">添加</a>
                <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/list">显示所有书籍</a>
            </div>
            <div class="col-mid-8 column"/>
                <form action="${pageContext.request.contextPath}/book/queryByBookName" class="form-inline">
                    <div class="form-group">
                        <input type="text" class="form-control" name="bookName"  placeholder="请输入书籍名称"/>
                    </div>
                    <button type="submit" class="btn btn-primary">查询</button>
                    <span style="color: red">${error}</span>
                </form>
            </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>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tbody>
                        <c:forEach var="book" items="${list}">
                            <tr>
                                <td>${book.getBookID()}</td>
                                <td>${book.getBookName()}</td>
                                <td>${book.getBookCounts()}</td>
                                <td>${book.getDetail()}</td>
                                <td>
                                    <a class="btn btn-default" href="${pageContext.request.contextPath}/book/toUpdate?id=${book.getBookID()}">更改</a>
                                        &nbsp; | &nbsp;
                                    <a class="btn btn-default" href="${pageContext.request.contextPath}/book/delete/${book.getBookID()}">删除</a>
                                </td>
                            </tr>

                        </c:forEach>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>

2.插入书籍页面

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2020/4/27
  Time: 9:28
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>插入书籍</title>
    <!-- 引入 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="row clearfix">
            <div class="col-md-12 column">
                <form action="${pageContext.request.contextPath}/book/insert">
                    <div class="form-group">
                        <label>书籍名称</label>
                        <input type="text" class="form-control"  name="bookName" required>
                    </div>
                    <div class="form-group">
                        <label>书籍数量</label>
                        <input type="text" class="form-control"   name="bookCounts" required>
                    </div>
                    <div class="form-group">
                        <label>书籍描述</label>
                        <input type="text" class="form-control"  name="detail" required>
                    </div>
                    <button type="submit" class="btn btn-default">添加</button>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

3.更新书籍页面

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>更改书籍</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 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="row clearfix">
            <div class="col-md-12 column">
                <form action="${pageContext.request.contextPath}/book/updateBook">
                    <input type="hidden" name="bookID" value="${book.bookID}">
                    <div class="form-group">
                        <label>书籍名称</label>
                        <input type="text" class="form-control"  name="bookName" value="${book.bookName}" required>
                    </div>
                    <div class="form-group">
                        <label>书籍数量</label>
                        <input type="text" class="form-control"  name="bookCounts" value="${book.bookCounts}" required>
                    </div>
                    <div class="form-group">
                        <label>书籍描述</label>
                        <input type="text" class="form-control"  name="detail" value="${book.detail}" required>
                    </div>
                    <button type="submit" class="btn btn-default">更改</button>
                </form>
            </div>
        </div>
    </div>
</body>

4.BookController

@Controller
@RequestMapping("/book")
public class BookController {
    @Resource
    private BookService bookService;
    //查询所有书籍
    @RequestMapping("/list")
    public String list(Model model){
        List<Book> list = bookService.queryAll();
        model.addAttribute("list",list);
        return "allBook";
    }

    //到添加页面
    @RequestMapping("/toInsert")
    public String toInsert(){
        return "insert";
    }

    //添加书籍
    @RequestMapping("/insert")
    public String insert(Book book){
        bookService.insert(book);
        return "redirect: /book/list";
    }

    //到更新页面
    @RequestMapping("/toUpdate")
    public String toUpdate(Model model, int id){
        Book book = bookService.queryByBookId(id);
        model.addAttribute("book",book);
        return "update";
    }

    @RequestMapping("/updateBook")
    public String updateBook(Book book){
        bookService.update(book);
        return "redirect:/book/list";
    }

    @RequestMapping("/delete/{bookID}")
    public String delete(@PathVariable("bookID") int id){
        Book book = bookService.queryByBookId(id);
        bookService.delete(book);
        return "redirect:/book/list";
    }

    @RequestMapping("/queryByBookName")
    public String queryByBookName(String bookName,Model model){
        Book book = bookService.queryByBookName(bookName);
        System.out.println(book);
        List<Book> list = new ArrayList<Book>();
        list.add(book);
        if(book == null){
            list = bookService.queryAll();
            model.addAttribute("error","数据库无此书");
        }
        model.addAttribute("list", list);
        return "allBook";
    }
}

基于这个,还可以添加更多功能,有时间还会持续更新的。

 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
更多>相关资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服