前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SSM整合(狂神版)

SSM整合(狂神版)

作者头像
全栈程序员站长
发布2022-08-23 20:22:57
6480
发布2022-08-23 20:22:57
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

SSM整合

我看了一些其他的整合视频感觉都没有狂神的清晰,层次分的分明白,结合狂神的笔记写的

整体项目结构

数据库环境

代码语言:javascript
复制
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,'从进门到进牢');

环境依赖

pom.xml

代码语言:javascript
复制
<?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>org.example</groupId>
    <artifactId>ssmkuang</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <java.version>13</java.version>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>

        <!--添加Servlet和JSP依赖-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</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>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>

        <!--spring AOP的包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.7.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>

        <dependency>

            <groupId>com.alibaba</groupId>

            <artifactId>druid</artifactId>

            <version>1.1.16</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.30</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

        <!--注解依赖 https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3.2</version>
        </dependency>



    </dependencies>

    <!--在build中配置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>

Maven资源过滤设置

代码语言:javascript
复制
  <!--在build中配置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>

建立基本结构

代码语言:javascript
复制
com.blb.entity
com.blb.dao
com.blb.service
com.blb.controller

mybatis-config.xml

代码语言:javascript
复制
<?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>

Mapper.xml

代码语言:javascript
复制
<?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="">

</mapper>

Spring的配置文件

spring-mvc.xml、spring-service.xml、spring-dao.xml,applicationContext.xml

代码语言:javascript
复制
<?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/springbeans.xsd">

</beans>

Mybatis层编写

数据库配置文件 :jdbc.properties

在resources目录下jdbc.properties 这里我还加了Druid连接池的配置

代码语言:javascript
复制
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db3?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
jdbc.init=1
jdbc.minIdle=1
jdbc.maxActive=10

MyBatis的核心配置文件 mybatis-config.xml

代码语言:javascript
复制
<?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>

<!-- 配置数据源,交给spring去做-->
    <typeAliases>
        <package name="com.blb.entity"/>
    </typeAliases>

    <mappers>
        <mapper class="com.blb.dao.BookMapper"></mapper>
    </mappers>
</configuration>

编写数据库对应的实体类

代码语言:javascript
复制
package com.blb.entity;

public class Books { 
   

    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;

     get/set

编写Dao层的 Mapper接口

代码语言:javascript
复制
package com.blb.dao;

import com.blb.entity.Books;

import java.util.List;



public interface BookMapper { 
   

    //增加一个Book
    int addBook(Books book);

    //根据id删除一个Book
    int deleteBookById(@Param("id") int id);

    //更新Book
    int updateBook(Books books);

    //根据id查询,返回一个Book
    Books queryBookById(@Param("id") int id);

    //查询全部Book,返回list集合
    List<Books> queryAllBook();

    //通过书名查书籍返回一个Book
    Books queryBookByName(@Param("bookName") String bookName);

}

}

编写接口对应的 Mapper.xml 文件。需要导入MyBatis的包

代码语言:javascript
复制
<?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.blb.dao.BookMapper">
<!-- 增加一个book-->
    
<insert id="addBook" parameterType="Books">
    insert into books(bookName,bookCounts,detail)
values (#{bookName}, #{bookCounts}, #{detail})

</insert>
    
<!--根据id删除一个book-->
<delete id="deleteBookById" parameterType="int">
delete from books where bookID=#{bookID}
</delete>
    
<!--更新book-->
<update id="updateBook" parameterType="Books">
update books
set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
where bookID = #{bookID}
</update>
    
<!--根据id查询返回一个book-->
<select id="queryBookById" resultType="Books">
select * from books
where bookID = #{bookID}
</select>

<!-- 查询全部书籍-->
<select id="queryAllBook" resultType="Books">
SELECT * from books
</select>

<!-- 通过书名查找书籍-->
<select id="queryBookByName" resultType="Books">
    SELECT * from books where bookName=#{bookName}
</select>
</mapper>

编写Service层的接口和实现类

BookService 接口

代码语言:javascript
复制
package com.blb.service;

import com.blb.entity.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

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();
   通过书名查书籍返回一个Book
    Books queryBookByName(String bookName);

}

BookServiceImpl实现类

代码语言:javascript
复制
package com.blb.service;

import com.blb.dao.BookMapper;
import com.blb.entity.Books;

import java.util.List;

public class BookServiceImpl implements BookService{ 
   

    //sevice 掉用dao层
    private BookMapper bookMapper;

    public BookMapper getBookMapper() { 
   
        return bookMapper;
    }

    public void setBookMapper(BookMapper bookMapper) { 
   
        this.bookMapper = bookMapper;
    }

    @Override
    public int addBook(Books book) { 
   
        return bookMapper.addBook(book);
    }

    @Override
    public int deleteBookById(int id) { 
   
        return bookMapper.deleteBookById(id);
    }

    @Override
    public int updateBook(Books books) { 
   
        return bookMapper.updateBook(books);
    }

    @Override
    public Books queryBookById(int id) { 
   
        return bookMapper.queryBookById(id);
    }

    @Override
    public List<Books> queryAllBook() { 
   
        return bookMapper.queryAllBook();
    }

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

Spring层

Spring整合Mybatis的相关的配置文件 spring-dao.xml

1.加载属性配置文件

代码语言:javascript
复制
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

2.定义数据源

如果需要更换数据源只需要导入依赖,修改class属性值跟property标签。

代码语言:javascript
复制
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driver}"/>
		<property name="url" value="${jdbc.url}"/>
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
</bean>

3.定义SqlSessionFactory

SqlSessionFactory需要注入数据源跟mybatis路径,这样mybatis-config.xml配置的内容才能生效

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

4. 扫描映射器

  • MapperScannerConfigurer会自动扫描指定包下的所有mapper接口,为我们生成mapper接口的实现类并注入到Spring容器中。
  • 注入Spring容器中的的命名策略是使用映射器的非大写的非完全限定类名。可以通过注解@Repository("xx")来修改。
  • MapperScannerConfigurer是需要使用sqlSessionFactory的,但是当只有一个的时候可以省略,如果要显示注入可以使用如下代码注入来注入,注意这里引用上面的sqlSessionFactory,但是是value的属性值,而不是ref<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
  • 这是省略了sqlSession的,如果没有省略sqlSession则sqlSessionFactoryBeanName需要改成sqlSessionTemplateBeanName,并通过value值引入定义的sqlSession。
代码语言:javascript
复制
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.blb.dao"/>
		  
    <!-- 注入sqlSessionFactory,如果只有一个数据源可省略,自动装配, 是value属性,不是ref -->
    <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> -->
	</bean>

配置Spring整合MyBatis,数据源使用Druid或者c3p0连接池

Druid版

代码语言:javascript
复制
<?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">

<!-- 关联数据库配置文件-->
<!-- 读取jdbc.properties 配置文件参数化(参数占位符)-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!-- 连接池 -->
    <!-- 集成Druid连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 基本配置-->
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>

        <!-- 配置初始化大小,最大,最小-->
        <property name="initialSize" value="${jdbc.init}"></property>
        <property name="minIdle" value="${jdbc.minIdle}"></property>
        <property name="maxActive" value="${jdbc.maxActive}"></property>

        <!-- 配置获取连接等待超时时间-->
        <property name="maxWait" value="60000"></property>

        <!-- 配置间隔多久时间才能进行一次检测,检测需要关闭的空闲连接,单位是毫秒-->
        <property name="timeBetweenEvictionRunsMillis" value="60000"></property>

        <!-- 配置一个连接池中最小生存时间,单位是毫秒-->
        <property name="minEvictableIdleTimeMillis" value="300000"></property>
    </bean>


    <!--生产sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池-->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 绑定mybatis配置文件 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        
        <!-- 定义别名也可以在mybatis-config.xml里配置-->
        <property name="typeAliasesPackage" value="com.blb.entity"></property>
    </bean>
<!-- 配置扫描Dao接口包,动态实现Dao接口注入到spring容器中-->
    <bean id="MapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- dao接口所在的包,如果有多个包逗号或分号分隔-->
        <!-- <property name="basePackage" value="com.a.dao,com.b.dao"></property>-->
        <property name="basePackage" value="com.blb.dao"></property>
        <!-- 注入 sqlsessionfactory 如果工厂只有一个sqlsessionfactory的bean此配置可以省略-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>
</beans>

c3p0版

代码语言:javascript
复制
<?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/springcontext.xsd">
<!-- 配置整合mybatis -->
<!-- 1.关联数据库文件 -->
<context:property-placeholder location="classpath:jdbc.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"/>
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<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="com.blb.dao"/>
</bean>
</beans>

spring整合service层

spring-service.xml

1.自动扫描

代码语言:javascript
复制
<context:component-scan base-package="com.blb.service"/>

2.声明式事务

配置声明式事务,注入数据源,需要导入tx的命名空间。

代码语言:javascript
复制
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

3.事务的注解驱动

注入定义的事务管理器

代码语言:javascript
复制
<tx:annotation-driven transaction-manager="transactionManager"/>

完整版

如果不通过bean标签注入可以在类上使用注解注入

代码语言:javascript
复制
<?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">
<!-- 扫描service下的包 也就是扫描相关的bean-->
    <context:component-scan base-package="com.blb.service">

    </context:component-scan>
<!-- 将我们的所有业务类,注入到spring,可以通过配置或者注解实现-->
    <bean id="BookServiceImpl" class="com.blb.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"></property>
    </bean>


    <!-- 引入一个事务管理器,其中依赖DataSource,借以获取连接,进而控制事务逻辑-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- aop事务支持-->
</beans>

SpringMVC层

web.xml

1. 设置DispatcherServlet

代码语言:javascript
复制
<servlet>
        <servlet-name>mvc_my</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>mvc_my</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

2. 字符过滤

代码语言:javascript
复制
 <!--配置springMVC的乱码过滤器-->
    <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>

3.设置监听器启动工厂

代码语言:javascript
复制
<!--启动spring工厂-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

完整版

代码语言:javascript
复制
<?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">

    <!-- springMVC前端控制器-->
    <!-- 1.前端,接收所有的请求-->
    <!-- 2.启动springMVC工厂 mvc.xml-->
    <!-- 3.springMVC流程调度-->
    <servlet>
        <servlet-name>mvc_my</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>mvc_my</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--配置springMVC的乱码过滤器-->
    <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>

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

    <!--启动spring工厂-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
</web-app>

spring-mvc.xml

1.自动扫描

代码语言:javascript
复制
<context:component-scan base-package="com.blb.controller"/>

注解驱动

代码语言:javascript
复制
<mvc:annotation-driven/>

静态资源过滤

代码语言:javascript
复制
<mvc:default-servlet-handler/>

视图解析器

代码语言:javascript
复制
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <!-- 前缀-->
        <property name="prefix" value="/"></property>
        <!-- 后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>

如果想让用户不能直接通过xx.jsp访问可以放到WEB-INF目录下视图解析器可以配置为

代码语言:javascript
复制
<bean id="ResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>
代码语言:javascript
复制
<?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/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd ">


    <!--    注解扫描-->
    <context:component-scan base-package="com.blb.controller" >

    </context:component-scan>
<!--     静态资源默认的servlet配置-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>

    <!--    注解驱动-->
    <mvc:annotation-driven>

        <!--          安装Fastjson转换器-->
        <mvc:message-converters register-defaults="false">

            <bean id="fastJsonHttpMessageConverter"
                  class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <!-- 加入支持的媒体类型:返回contentType -->
                <property name="supportedMediaTypes">
                    <list>
                        <!-- 这里顺序不能反,一定先写text/html,不然ie下会出现下载提示 -->
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>

    </mvc:annotation-driven>

    <!--    视图解析器
          作用 :1.捕获后端控制器的返回值 如果返回的是hello
                2.解析:在返回值前后拼接 "/hello.jsp"
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <!--        前缀-->
        <property name="prefix" value="/"></property>
        <!--        后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>


</beans>

Spring配置整合文件,applicationContext

代码语言:javascript
复制
<?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.xsd">

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

配置日志

logback.xml

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <!-- 添加输出器(追加器) 作用:日志在什么地方进行输出 ch.qos.logback.core.ConsoleAppender:向控制台进行打印输出 -->
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <!-- encoder:编码-->
        <encoder>
            <!-- pattern:规定日志输出的格式 %d{HH:mm:ss.SSS}:开头的时间 [%thread]:输出线程的名称 %-5level:日志的级别 -5表示按5个字符右对齐 %logger{36}:表示那个类进行日志输出 36:这段字符串最多允许36个字符串,超过则会用简写的方式输出 -%msg:具体日志输出的内容 %n:换行 -->
            <pattern>[%thread] %d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- 日志打印的根标签 level:日志输出级别-->
    <root level="debug">
        <!-- 引用appender name="console" 在日志输出的过程中会,只要是等于debug级别或以上都会按照 appender name="console"的格式进行打印-->
        <appender-ref ref="console"/>
    </root>
</configuration>

Controller 和 视图层编写

首页

index.jsp

代码语言:javascript
复制
<%@ 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">

    <style type="text/css">
      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: 4px;
      }
    </style>

  </head>
  <body>
  <h3>
    <a href="${pageContext.request.contextPath}/book/allBook">进入书籍页面</a>
  </h3>
  </body>
</html>

书籍列表页

allbook.jsp

代码语言:javascript
复制
<%@ 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/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">
            <span style="color:red;font-weight: bold">${ 
   error}
            </span>
            <input type="text" name="queryBookName" class="form-control"
                   placeholder="输入查询书名" required>
            <input type="submit" value="查询" class="btn btn-primary">
        </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>
<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?id=${book.getBookID()}">更改</a> |
    <a href="${pageContext.request.contextPath}/book/deleteBook/${book.getBookID()}"> 删除</a>
    </td>
    </tr>
</c:forEach>
                </tbody>
            </table>
        </div>
</div>
</div>
</body>
</html>

添加书籍页面

addBook.jsp

代码语言:javascript
复制
<%@ 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>
    <form action="${pageContext.request.contextPath}/book/addBook"
          method="post">
        书籍名称:<input type="text" name="bookName" required><br>
        书籍数量:<input type="text" name="bookCounts" required>><br>
        书籍详情:<input type="text" name="detail" required>><br>
        <input type="submit" value="添加">
    </form>
</div>

修改书籍页面

updateBook.jsp

代码语言:javascript
复制
<%@ 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>
    <form action="${pageContext.request.contextPath}/book/updateBook"
          method="post">
        <input type="hidden" name="bookID" value="${book.getBookID()}"/>
        书籍名称:<input type="text" name="bookName"
                    value="${book.getBookName()}"/>
        书籍数量:<input type="text" name="bookCounts"
                    value="${book.getBookCounts()}"/>
        书籍详情:<input type="text" name="detail"
                    value="${book.getDetail() }"/>
        <input type="submit" value="提交"/>
    </form>
</div>

Controller代码

代码语言:javascript
复制
package com.blb.controller;

import com.blb.entity.Books;
import com.blb.service.BookService;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController { 
   
    //controller调用service层
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

// 查询全部的书籍,并展示
    @RequestMapping("/allBook")
    public String list(Model model){ 
   
        List<Books> books = bookService.queryAllBook();
        model.addAttribute("list",books);

        return "allBook";
    }
    //跳转到增加书籍页面
    @RequestMapping("/toAddBook")
    public String toAddPaper(){ 
   
        return "addBook";
    }
    //添加书籍的请求
   @RequestMapping("/addBook")
    public String addBook(Books books)
    { 
   
        bookService.addBook(books);
        return "redirect:/book/allBook";
    }

    //跳转到修改页面
    @RequestMapping("/toUpdateBook")
    public String toUpdatePaper(int id,Model model){ 
   
        Books books=bookService.queryBookById(id);
        model.addAttribute("book",books);
        return "updateBook";
    }
    //修改书籍
    @RequestMapping("/updateBook")
    public String updateBook(Books books){ 
   
        bookService.updateBook(books);
        return "redirect:/book/allBook";
    }

    //删除书籍
    @RequestMapping("/deleteBook/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id){ 
   
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }


    //查询书籍
    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName,Model model){ 
   
        Books books = bookService.queryBookByName(queryBookName);
        List<Books> list=new ArrayList<>();
        list.add(books);
        if(books==null){ 
   
            list=(bookService.queryAllBook());
            model.addAttribute("error","未找到该书籍");
        }
        model.addAttribute("list",list);

        return "allBook";
    }
}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/139551.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年5月7,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • SSM整合
  • 整体项目结构
  • 数据库环境
  • 环境依赖
    • pom.xml
      • Maven资源过滤设置
      • 建立基本结构
        • mybatis-config.xml
          • Mapper.xml
            • Spring的配置文件
            • Mybatis层编写
              • 数据库配置文件 :jdbc.properties
                • MyBatis的核心配置文件 mybatis-config.xml
                  • 编写数据库对应的实体类
                    • 编写Dao层的 Mapper接口
                      • 编写接口对应的 Mapper.xml 文件。需要导入MyBatis的包
                        • 编写Service层的接口和实现类
                          • BookService 接口
                        • BookServiceImpl实现类
                        • Spring层
                          • Spring整合Mybatis的相关的配置文件 spring-dao.xml
                            • 1.加载属性配置文件
                            • 2.定义数据源
                            • 3.定义SqlSessionFactory
                            • 4. 扫描映射器
                            • Druid版
                            • c3p0版
                          • spring整合service层
                            • 1.自动扫描
                            • 2.声明式事务
                            • 3.事务的注解驱动
                            • 完整版
                        • SpringMVC层
                          • web.xml
                            • 1. 设置DispatcherServlet
                            • 2. 字符过滤
                            • 3.设置监听器启动工厂
                            • 完整版
                          • spring-mvc.xml
                            • 1.自动扫描
                            • 注解驱动
                            • 静态资源过滤
                            • 视图解析器
                          • Spring配置整合文件,applicationContext
                            • 配置日志
                            • Controller 和 视图层编写
                              • 首页
                                • 书籍列表页
                                  • 添加书籍页面
                                    • 修改书籍页面
                                      • Controller代码
                                      相关产品与服务
                                      数据库
                                      云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
                                      领券
                                      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档