SSM整合(狂神版)

SSM整合(狂神版)SSM整合数据库环境环境依赖pom.xml建立基本结构mybatis-config.xmlapplicationContext.xml数据库环境CREATEDATABASE`ssmbuild`;USE`ssmbuild`;DROPTABLEIFEXISTS`books`;CREATETABLE`books`(`bookID`INT(10)NOTNULLAUTO_INCREMENTCOMMENT’书id’,`bookName`VARCHAR(100)NO

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

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

整体项目结构

在这里插入图片描述

数据库环境

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

<?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资源过滤设置

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

建立基本结构

com.blb.entity
com.blb.dao
com.blb.service
com.blb.controller

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>

</configuration>

Mapper.xml

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

<?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连接池的配置

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

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

编写数据库对应的实体类

package com.blb.entity;

public class Books { 
   

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

     get/set

编写Dao层的 Mapper接口

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

<?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 接口

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实现类

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.加载属性配置文件

<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

2.定义数据源

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

<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配置的内容才能生效

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

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

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

<?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.自动扫描

<context:component-scan base-package="com.blb.service"/>

2.声明式事务

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

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

3.事务的注解驱动

注入定义的事务管理器

<tx:annotation-driven transaction-manager="transactionManager"/>

完整版

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

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

<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. 字符过滤

 <!--配置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.设置监听器启动工厂

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

完整版

<?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.自动扫描

<context:component-scan base-package="com.blb.controller"/>

注解驱动

<mvc:annotation-driven/>

静态资源过滤

<mvc:default-servlet-handler/>

视图解析器

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

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

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

<bean id="ResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>
<?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

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

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


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

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

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

<%@ 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代码

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";
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • Feign原理 (图解)_feign原理

    Feign原理 (图解)_feign原理1.1简介:Feign远程调用的Feign远程调用,核心就是通过一系列的封装和处理,将以JAVA注解的方式定义的远程调用API接口,最终转换成HTTP的请求形式,然后将HTTP的请求的响应结果,解码成JAVABean,放回给调用者。Feign远程调用的基本流程,大致如下图所示。从上图可以看到,Feign通过处理注解,将请求模板化,当实际调用的时候,传入参数,根据参数再应用到请求上,进而转化成真正的Request请求。通过Feign以及JAVA的动态代理机制,使得Java…

  • Java高级工程师常见面试题(答案)[通俗易懂]

    Java高级工程师常见面试题(答案)[通俗易懂]Java高级工程师常见面试题2017年02月17日12:46:00阅读数:17280一、Java基础1.String类为什么是final的。   1.线程安全2.支持字符串常量池数据共享,节省资源,提高效率(因为如果已经存在这个常量便不会再创建,直接拿来用)  2.HashMap的源码,实现…

  • linux服务器负载均衡配置_分布式系统如何负载均衡

    linux服务器负载均衡配置_分布式系统如何负载均衡因项目需要最近研究了下Linux红帽6.5下实现Apache负载均衡的问题。从干净的环境说起。   1、安装JDK环境       首先下载linux版本的JDK,我使用的是jdk-6u24-linux-x64-rpm.bin,并将该文件上传至服务器的指定目录。       chmod777jdk-6u24-linux-x64-rpm.bin修改文件的操作权限;   

  • java 和 C 代码运行效率的比较(整理)「建议收藏」

    java 和 C 代码运行效率的比较(整理)「建议收藏」最近和朋友无意间讨论起了有关java和C的效率问题,(我是java推介者,他是c语言推介者,他做的是嵌入式)故,想通过网络查询一下,总结一下,两者到底效率如何,其有何差异,原因

  • DataOps: 大数据新战线

    DataOps: 大数据新战线

    2021年11月22日
  • 视频要不要开hdr_hdr在什么情况下使用

    视频要不要开hdr_hdr在什么情况下使用最近两年HDR这个概念可谓是铺天盖地而来,手机也好PC也好电视也好,都拼命往自己头上扣HDR的帽子。而在某些发烧友眼中,如果看片子不带HDR,堪比步兵变骑兵,一下子变得索然无味。然而,新事物往往也伴随着众多新坑,特别是在软硬件环境复杂的PC平台,稍有不慎就会摔得脸青鼻肿,播HDR的效果甚至不如播普通的片子。PC播HDR的大坑有几何?PC并不是专门为视频播放设计的机器,和专业的蓝光机等播放器相比…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号