其他分享
首页 > 其他分享> > SSH框架整合--学习狂神笔记

SSH框架整合--学习狂神笔记

作者:互联网

一、我的环境

IDEA 2020.2

MySQL 8

Tomcat 9

Maven3.6

 

数据库环境搭建

在sqlyog里面编写一个数据库表,sql如下

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,'从进门到进牢');

这边不建议一下子全部执行,尽量按顺序执行,避免出现顺序不一,导致种种问题

二、基本环境搭建

第一步

新建一个maven项目,检测idea的maven版本是是否是自己的还是idea本身的,尽量用自己的

然后添加web支持【这样才会有web带蓝点的文件夹】

第二步

导入相关的pom依赖!【junit、mysql驱动、数据库连接池、Servlet、jsp、jstl、Mybatis、Spring】

顺便把maven资源过滤也加上

<?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.Jacob</groupId>
    <artifactId>ssmbuild</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
    <!--Junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</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>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</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.7</version>
        </dependency>
    <!--Spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</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>
</project>

第三步

这边我们把我们的idea和数据库连接【怎么连接如下】

步骤:idea右边侧边栏有一个Database点开---然后左上角有一个加号点开---Data Source展开---点击你的数据库【mysql】---输入user/密码---点开Schemas选择你的数据库表

第四步

数据库配置文件 database.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
jdbc.username=root
jdbc.password=123456

三、Mybatis层编写

第一步

编写MyBatis的核心配置文件

<?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.Jacob.pojo"/>
</typeAliases>
<!-- 注册mapper-->
    <mappers>
        <mapper class="com.Jacob.dao.BookMapper"/>
    </mappers>
</configuration>

第二步

编写实体类Books【属性对应数据库字段,个人建议一模一样】

以下使用了lombok插件!【需要的话自己导包喔】

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

第三步:编写dao层

BookMapper接口

public interface BookMapper {
    //增加一本书
    int addBook(Books books);
    //删除一本书
    int deleteBookById(@Param("bookId") int id);
    //更新一本书
    int updateBooks(Books books);
    //查询一本书 根据id
    Books selectBookById(@Param("bookId") int id);
    //查询全部的书
    List<Books> selectBooks();
    //通过书名查询书籍
    Books queryBookByName(@Param("bookName") String bookName);
}

编写接口对应的BookMapper.xml【这边重点是写sql语句】

<?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对应一个接口-->
<mapper namespace="com.Jacob.dao.BookMapper">
    <insert id="addBook" parameterType="Books">
        insert into books (bookName,bookCounts,detail)
        values (#{bookName},#{bookCounts},#{detail});
    </insert>
    <delete id="deleteBookById" parameterType="int">
        delete from books where bookID=#{bookId};
    </delete>
    <update id="updateBooks" parameterType="Books">
        update books
        set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
        where bookID=#{bookID};
    </update>
    <select id="selectBookById" parameterType="int" resultType="Books">
        select * from books where bookID=#{bookId};
    </select>
    <select id="selectBooks" resultType="Books" >
        select * from books;
    </select>
    <select id="queryBookByName" resultType="Books" parameterType="String">
        select * from books where bookName=#{bookName};
    </select>
</mapper>

这边写完记得里面到mybatis配置文件里面进行注册mapper,我上面已经写好了就是那个注册mapper

第四步:编写service层

接口BookService

public interface BookService {
    //增加一本书
    int addBook(Books books);
    //删除一本书
    int deleteBookById(int id);
    //更新一本书
    int updateBooks(Books books);
    //查询一本书 根据id
    Books selectBookById(int id);
    //查询全部的书
    List<Books> selectBooks();
    //通过书名查询书籍
    Books queryBookByName(String bookName);
}

需要一个实现类BookServiceImpl来实现上面的接口

【这里重点需要掌握的是业务层调用dao层】

public class BookServiceImpl implements BookService{
    //业务层掉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 updateBooks(Books books) {
        return bookMapper.updateBooks(books);
    }

    public Books selectBookById(int id) {
        return bookMapper.selectBookById(id);
    }

    public List<Books> selectBooks() {
        return bookMapper.selectBooks();
    }

    public Books queryBookByName(String bookName) {
        return bookMapper.queryBookByName(bookName);
    }
}

OK,到此,底层需求操作编写完毕!

四、Spring层编写

第一步:首先我们需要配置spring整合MyBatis【这边数据源为:c3p0连接池】

放在第二步来操作

第二步:编写dao层--spring-dao.xml

编写Spring整合Mybatis的相关的配置文件

1.关联数据库文件【就是上面写的database.properties】

2.数据库连接池【你知道有两个就行,代码固定的,具体参数可以自调】

3.配置sqlSessionFactory对象

4.注入数据库连接池【也就是2】

5.配置mybatis的配置文件

6.实现dao注入到spring容器中

7.注入sqlSessionFactory【也就是3】

8.给出需要扫描的dao包

<?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 自动化操作(自动的加载配置文件 并且设置到对象里面)
     -->
    <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全局配置文件:mybatis-config.xml -->
        <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.Jacob.dao"/>
    </bean>

</beans>

 

第三步:编写service层

spring-service.xml

1.扫描service的包

2.将业务类注入到spring容器中

3.配置事务管理器DataSourceTransactionManager 、注入数据库连接池

4.配置事务切入

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 扫描service相关的bean -->
    <context:component-scan base-package="com.Jacob.service"/>
    <!--BookServiceImpl注入到IOC容器中将我们所有的业务类,注入到spring,可以通过配置,可以通过注解-->
    <bean id="BookServiceImpl" class="com.Jacob.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>
    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--给哪些方法配置事务-->
        <!--配置事务的传播特性-->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!--配置事务切入-->
    <aop:config>
        <aop:pointcut id="txPointCut"
                      expression="execution(* com.Jacob.dao.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>

Spring就是一个大杂烩,一个容器!

五、SpringMVC层

第一步:增加一个web支持

右键项目:Add Framework Support..

第二步:编写web.xml

1.DispatcherServlet

2.乱码过滤

3.session过期时间

【这些别怕,固定写法】

<?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>
<!--session过期时间-->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>

第三步:spring-mvc.xml

1.开启SpringMVC注解驱动

2.静态资源默认servlet配置

3.扫描包【cntroller】

4.ViewResolver解析器

<?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.开启SpringMVC注解驱动-->
    <mvc:annotation-driven/>
    <!-- 2.静态资源默认servlet配置-->
    <mvc:default-servlet-handler/>
    <!--扫描包-->
    <context:component-scan base-package="com.Jacob.controller"/>
    <!-- 3.配置jsp 显示ViewResolver视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

配置文件,暂时结束!Controller 和 视图层编写

BookController 类编写

下面就是一些列的对书籍的方法

【重点掌握:Controller层调servcie层】

举个

标签:--,public,int,books,SSH,id,狂神,Books,书籍
来源: https://www.cnblogs.com/com-Jacob/p/16221439.html