• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

110_SSM框架

开发技术 开发技术 3小时前 1次浏览

目录
  • 需求分析->功能设计->数据库设计
  • 环境要求
    • 环境
    • 要求
  • 数据库环境
  • 基本环境搭建
    • 创建maven项目
    • pom.xml添加依赖,添加资源导出
    • idea连接数据库
  • 提交项目到Git
  • 创建基础包
  • 创建配置文件
    • db.properties
    • mybatis-config.xml
    • applicationContext.xml
  • 创建实体类
  • 创建Mapper接口和Mapper.xml
    • 注册Mapper到mybatis-config.xml
  • 创建Service接口和实现类
  • Spring配置文件
    • 创建配置文件 spring-dao.xml
    • 创建配置文件 spring-service.xml
    • 创建配置文件 spring-mvc.xml
    • applicationContext.xml导入spring-dao.xml spring-service.xml spring-mvc.xml
  • 项目添加web框架支持
    • 配置web.xml
  • 创建Controller
  • 创建首页和书库页
  • Artifacts中WEB-INF下创建lib,并选择jar
  • 配置Tomcat,并测试

需求分析->功能设计->数据库设计

环境要求

环境

  • IDEA
  • MySQL 5.7.19
  • Tomcat 9
  • Maven 3.6

要求

  • 熟练掌握MySQL数据库
  • 熟练掌握Spring,JavaWeb及MyBatis知识
  • 简单的前端知识

数据库环境

CREATE DATABASE `ssm`CHARACTER SET utf8 COLLATE utf8_general_ci; 

USE `ssm`; 
 
CREATE TABLE `ssm`.`books` ( `book_id` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id', `book_name` VARCHAR(100) NOT NULL COMMENT '书名', `book_count` INT(10) NOT NULL COMMENT '数量', `book_detail` VARCHAR(1000) NOT NULL COMMENT '描述', PRIMARY KEY (`book_id`) ) ENGINE=INNODB CHARSET=utf8 COLLATE=utf8_general_ci; 

INSERT INTO `ssm`.`books` (`book_name`, `book_count`, `book_detail`) VALUES ('Java', '1', '从入门到放弃'); 
INSERT INTO `ssm`.`books` (`book_name`, `book_count`, `book_detail`) VALUES ('MySQL', '11', '从删库到跑路'); 
INSERT INTO `ssm`.`books` (`book_name`, `book_count`, `book_detail`) VALUES ('Linux', '5', 'j'); 

SELECT * FROM books LIMIT 0, 1000;

110_SSM框架

基本环境搭建

创建maven项目

110_SSM框架
110_SSM框架

pom.xml添加依赖,添加资源导出

<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>

    <groupId>com.qing</groupId>
    <artifactId>ssm</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.7</version>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

    <!--配置resources,防止资源导出失败问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
</project>

idea连接数据库

110_SSM框架
110_SSM框架

提交项目到Git

git@gitee.com:wl3pbzhyq/ssm.git

创建基础包

110_SSM框架

创建配置文件

110_SSM框架

db.properties

driver=com.mysql.jdbc.Driver
# 如果使用的是MySQL8.0+,增加一个时区的配置:&serverTimezone=Asia/Shanghai
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456

mybatis-config.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>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!--开启驼峰映射-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!--别名-->
    <typeAliases>
        <package name="com.qing.pojo"/>
    </typeAliases>

</configuration>

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



</beans>

创建实体类

package com.qing.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
    private int bookId;
    private String bookName;
    private int bookCount;
    private String bookDetail;
}

创建Mapper接口和Mapper.xml

110_SSM框架

package com.qing.dao;

import com.qing.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BooksMapper {

    /**
     * 新增书
     * @param books
     * @return
     */
    int add(Books books);

    /**
     * 根据Id删除书
     * @param bookId
     * @return
     */
    int deleteById(@Param("bookId") int bookId);

    /**
     * 修改书
     * @param books
     * @return
     */
    int update(Books books);

    /**
     * 根据Id获取书
     * @param bookId
     * @return
     */
    Books getBooksById(@Param("bookId") int bookId);

    /**
     * 获取全部书
     * @return
     */
    List<Books> listBooks();
}

<?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="com.qing.dao.BooksMapper">
    <!--新增书-->
    <insert id="add" parameterType="Books">
        insert into ssm.books(book_name, book_count, book_detail)
        values (#{bookName},#{bookCount},#{bookDetail})
    </insert>
    <!--根据Id删除书-->
    <delete id="deleteById" parameterType="int">
        delete from ssm.books where book_id = #{bookId}
    </delete>
    <!--修改书-->
    <update id="update" parameterType="Books">
        update ssm.books
        set book_name=#{bookName},book_count=#{bookCount},book_detail=#{bookDetail}
        where book_id=#{bookId}
    </update>
    <!--根据Id获取书-->
    <select id="getBooksById" parameterType="int" resultType="Books">
        select * from ssm.books
        where book_id=#{bookId}
    </select>
    <!--获取全部书-->
    <select id="listBooks" resultType="Books">
        select * from ssm.books
    </select>
</mapper>

注册Mapper到mybatis-config.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>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <!--别名-->
    <typeAliases>
        <package name="com.qing.pojo"/>
    </typeAliases>

    <!-- 将包内的映射器接口实现全部注册为映射器 -->
    <mappers>
        <package name="com.qing.dao"/>
    </mappers>

</configuration>

创建Service接口和实现类

110_SSM框架

package com.qing.service;

import com.qing.pojo.Books;

import java.util.List;

public interface BooksService {
    /**
     * 新增书
     * @param books
     * @return
     */
    int add(Books books);

    /**
     * 根据Id删除书
     * @param bookId
     * @return
     */
    int deleteById(int bookId);

    /**
     * 修改书
     * @param books
     * @return
     */
    int update(Books books);

    /**
     * 根据Id获取书
     * @param bookId
     * @return
     */
    Books getBooksById(int bookId);

    /**
     * 获取全部书
     * @return
     */
    List<Books> listBooks();
}

package com.qing.service;

import com.qing.dao.BooksMapper;
import com.qing.pojo.Books;

import java.util.List;

public class BooksServiceImpl implements BooksService {

    // service调dao层,组合Dao
    private BooksMapper booksMapper;

    public void setBooksMapper(BooksMapper booksMapper) {
        this.booksMapper = booksMapper;
    }

    public int add(Books books) {
        return booksMapper.add(books);
    }

    public int deleteById(int bookId) {
        return booksMapper.deleteById(bookId);
    }

    public int update(Books books) {
        return booksMapper.update(books);
    }

    public Books getBooksById(int bookId) {
        return booksMapper.getBooksById(bookId);
    }

    public List<Books> listBooks() {
        return booksMapper.listBooks();
    }
}

Spring配置文件

110_SSM框架

创建配置文件 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
        https://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:db.properties"/>

    <!--连接池
        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>

    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--绑定mybatis的配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!--配置dao接口扫描包,动态的实现Dao接口注入到spring容器中-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--注入sqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--要扫描的dao包-->
        <property name="basePackage" value="com.qing.dao"/>
    </bean>

</beans>

创建配置文件 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"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--扫描service下的包-->
    <context:component-scan base-package="com.qing.service"/>

    <!--将业务类注入到Spring,通过配置,也可以通过注解实现-->
    <bean id="BookServiceImpl" class="com.qing.service.BooksServiceImpl">
        <property name="booksMapper" ref="booksMapper"/>
    </bean>

    <!--声明式事务配置-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--aop事务支持-->
    <!--结合aop实现事务的织入-->
    <!--配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给那些方法配置事务-->
        <!--配置事务的传播特性-->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCout" expression="execution(* com.qing.dao.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCout"/>
    </aop:config>

</beans>

创建配置文件 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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!--注解驱动-->
    <mvc:annotation-driven/>
    <!--静态资源过滤-->
    <mvc:default-servlet-handler/>
    <!--扫描包-->
    <context:component-scan base-package="com.qing.controller"/>
    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

applicationContext.xml导入spring-dao.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
        https://www.springframework.org/schema/beans/spring-beans.xsd">

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

</beans>

项目添加web框架支持

110_SSM框架
110_SSM框架

配置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>spingmvc</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>spingmvc</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>

    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

创建Controller

package com.qing.controller;

import com.qing.pojo.Books;
import com.qing.service.BooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/books")
public class BooksController {

    @Autowired
    @Qualifier("BookServiceImpl")
    private BooksService booksService;

    @RequestMapping("/listBooks")
    public String listBooks(Model model) {
        List<Books> list = booksService.listBooks();
        model.addAttribute("list",list);
        return "listBooks";
    }
}

创建首页和书库页

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
  </head>
  <body>
  <h1><a href="${pageContext.request.contextPath}/books/listBooks">进入书库</a></h1>
  </body>
</html>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>书库</title>
</head>
<body>
<h1>书库</h1>
<div>
    <table class="table table-hover table-striped">
        <thead>
            <tr>
                <th>书籍编号</th>
                <th>书籍名称</th>
                <th>书籍数量</th>
                <th>书籍描述</th>
            </tr>
        </thead>
        <tbody>
            <c:forEach var="book" items="${list}">
                <tr>
                    <td>${book.bookId}</td>
                    <td>${book.bookName}</td>
                    <td>${book.bookCount}</td>
                    <td>${book.bookDetail}</td>
                </tr>
            </c:forEach>
        </tbody>
    </table>
</div>
</body>
</html>

Artifacts中WEB-INF下创建lib,并选择jar

110_SSM框架

配置Tomcat,并测试

110_SSM框架
110_SSM框架
110_SSM框架


程序员灯塔
转载请注明原文链接:110_SSM框架
喜欢 (0)