狂神说SpringMVC
一、概述
什么是MVC
MVC是(Model)模型(dao service), (View)视图(jsp) ,(Controller)控制器(servlet) 的简写 , 是一种软件设计规范.
最典型的MVC就是JSP +servlet +javabean的模式
职责分析
Controller: 控制器
- 取得表单数据
- 调用业务逻辑
- 转向指定页面
Model : 模型
- 业务逻辑
- 保存数据的状态
View : 视图
- 显示页面
二、什么是SpringMVC
2.1 SpringMVC优点
- 轻量级,简单易学
- 高效, 基于请求响应的MVC框架
- 与Spring兼容性好, 无缝结合
- 约定优于配置
- 功能强大 :RESTful , 数据验证 , 格式化 , 本地化 , 主题等
- 简洁灵活
2.2 springmvc运行原理
⑴ 用户发送请求至前端控制器DispatcherServlet
⑵ DispatcherServlet收到请求调用HandlerMapping处理器映射器。
⑶ 处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。
⑷ DispatcherServlet通过HandlerAdapter处理器适配器
⑸ 执行处理器(Controller,也叫后端控制器)。
⑹ Controller执行完成返回ModelAndView
⑺ HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet
⑻ DispatcherServlet将ModelAndView传给ViewReslover视图解析器
⑼ ViewReslover解析后返回具体View
⑽ DispatcherServlet对View进行渲染视图(即将模型数据填充至视图中)。
⑾ DispatcherServlet响应用户。
2.3 简述工作原理:
Spring MVC 工作原理:
简单理解:
客户端发送请求----
前端控制器接受客户端请求DispatcherServlet----
找到处理器映射HandlerMapping----
找到处理器Handler----
处理器返回一个模型视图ModelAndView----
视图解析器进行解析----
返回一个视图对象----
前端控制器的得到视图对象----
显示给用户
1.Tomcat在启动时加载解析web.xml,找到spring mvc的前端总控制器DispatcherServlet,并且通过DispatcherServlet来加载相关的配置文件信息。
2.DispatcherServlet接收到客户端请求,找到对应HandlerMapping,根据映射规则,找到对应的处理器(Handler)。
3.调用相应处理器中的处理方法,处理该请求后,会返回一个ModelAndView。
4.DispatcherServlet根据得到的ModelAndView中的视图对象,找到一个合适的ViewResolver(视图解析器),根据视图解析器的配置,DispatcherServlet将要显示的数据传给对应的视图,最后显示给用户。
2.4 web.xml配置
<!-- 配置DispatcherServlet :这个是SpringMVC的核心;请求分发器,前端控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- DispatcherServlet要绑定Spring的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!-- 启动级别:1 数字越小 , 启动越早-->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 在SpringMVC中 / /*
/ :只匹配所有的请求 , 不会去匹配jsp页面
/* :匹配所有的请求 , 包括jsp页面-->
<servlet-mapping>
<servlet-name>springmvc</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>
2.5 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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--1.注解驱动
2.json格式乱码处理-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--2.静态资源过滤-->
<mvc:default-servlet-handler/>
<!--3.自动扫描包, 让指定包下的注解生效,由IOC容器统一管理-->
<context:component-scan base-package="com.codefuheng.controller"/>
<!--4.视图解析器 : 模板引擎 Thymeleaf Freemarker-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
三、 json
什么是json?
四、整合ssm基本框架
第一步:创建maven项目
第二步:导入pom依赖
- 各种依赖
- build防止资源溢出
Mybatis
第三步:配置数据库
第四步:将mybatis的文件及xml配好
- codefuheng
- dao层: (I)BookMapper BookMapper.xml
- pojo层: Books
- service层: (I) BookService BookServiceImpl
- Resource层
- datebase.properties
- mybatis-config.xml
Spring
- Resource层
- spring-dao.xml
- spring-service.xml
SpringMVC
- web/WEB-INF
- web.xml
- Resource层
- Spring-mvc.xml
- WEB-INF
- 创建jsp文件夹
最后将Spring-dao.xml Spring-service.xml Spring-mvc.xml 导入import到applicationContext.xml中
<import resource="Spring-dao.xml"/>
<import resource="Spring-service.xml"/>
<import resource="Spring-mvc.xml"/>
整合ssm(代码)
第0步: 搭建环境—创建数据库----导入数据
第一步:创建maven项目
第二步:导入pom依赖
- 各种依赖
<!--依赖: junit; mysql数据库驱动;连接池;servlet;jsp;mybatis;mybatis-spring;Spring-->
<dependencies>
<!-- junit测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- lombok 实体类注解依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<!-- mysql数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
<!-- 数据库连接池: c3p0-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- mybatis-spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<!-- Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!-- Spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!-- servlet-api-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- jsp-api-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
<scope>provided</scope>
</dependency>
<!-- jstl-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
- build防止资源溢出
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
Mybatis
第三步:配置连接数据库
第四步:将mybatis的文件及xml配好
-
codefuheng
-
dao层: (I)BookMapper BookMapper.xml
-
BookMapper(接口)
-
public interface BookMapper { /** * 增加一本书 */ int addBook(Books books); /** * 删除一本书 */ int deleteBookById (@Param("bookId") int id); /** * 更新一本书 */ int updateBook(Books books); /** * 查询一本书 */ Books queryBookById(@Param("bookId") int id); /** * 查询全部的书 */ List<Books> queryAllBook(); }
-
BookMapper.xml
-
<?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.codefuheng.dao.BookMapper"> <insert id="addBook" parameterType="Books"> insert into Books(bookName,bookCounts,detail) value(#{bookName},#{bookCounts},#{dateil}) </insert> <delete id="deleteBookById" parameterType="int"> delete * from Books where bookId=#{bookId} </delete> <update id="updateBook" parameterType="Books"> update Books set bookName =#{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookId=#{bookId}; </update> <select id="queryBookById" resultType="Books"> select * from Books where bookId=#{bookId} </select> <select id="queryAllBook" resultType="Books"> select * from Books </select> </mapper>
-
pojo层: Books
-
Books.java
-
@Data @AllArgsConstructor @NoArgsConstructor public class Books { private int bookID; private String bookName; private int bookCounts; private String detail; }
-
service层: (I) BookService BookServiceImpl
-
BookService(接口)
-
public interface BookService { /** * 增加一本书 */ int addBook(Books books); /** * 删除一本书 */ int deleteBookById(int id); /** * 更新一本书 */ int updateBook(Books books); /** * 查询一本书 */ Books queryBookById(int id); /** * 查询全部的书 */ List<Books> queryAllBook(); }
-
BookServiceImpl.java
-
public class BookServiceImpl implements BookService{ 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 updateBook(Books books) { return bookMapper.updateBook(books); } public Books queryBookById(int id) { return bookMapper.queryBookById(id); } public List<Books> queryAllBook() { return bookMapper.queryAllBook(); } }
-
-
Resource层
-
datebase.properties
-
jdbc.driver=com.mysql.cj.jdbc.Driver # 入伙如果使用的是Mysql8.0+ ,增加一个时区的配置; &serverTimezone=Asia/shanghai jdbc.url=jdbc:mysql://localhost:3306/codefuheng?useSSL=false&useUnicode=true;characterEncoding=UTF-8 jdbc.username=root jdbc.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> <typeAliases> <package name="com.codefuheng.pojo"/> </typeAliases> <mappers> <mapper class="com.codefuheng.dao.BookMapper"/> </mappers> </configuration>
-
Spring
-
Resource层
-
spring-dao.xml
-
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!--1.关联数据库配置文件--> <context:property-placeholder location="classpath:datebase.properties"/> <!--2.连接池 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> <!--3.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.codefuheng.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" 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.扫描service下的包--> <context:component-scan base-package="com.codefuheng.service"/> <!--2.将我们的所有业务类,注入到Spring,可以通过配置,或者注解实现--> <bean id="BookServiceImpl" class="com.codefuheng.service.BookServiceImpl"> <property name="bookMapper" ref="bookMapper"/> </bean> <!--3.声明式事务配置--> <bean id="transactionMapper" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--注入数据源--> <property name="dataSource" ref="dataSource"/> </bean> <!--aop事务支持--> </beans>
-
SpringMVC
-
web/WEB-INF
-
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"> <!--配置DispatcherServlet :这个是SpringMVC的核心;请求分发器,前端控制器--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--DispatcherServlet要绑定Spring的配置文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> <!--启动级别:1 数字越小 , 启动越早--> <load-on-startup>1</load-on-startup> </servlet> <!-- 在SpringMVC中 / /* / :只匹配所有的请求 , 不会去匹配jsp页面 /* :匹配所有的请求 , 包括jsp页面--> <servlet-mapping> <servlet-name>springmvc</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> </web-app>
-
-
Resource层
-
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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--1.注解驱动--> <mvc:annotation-driven/> <!--2.静态资源过滤--> <mvc:default-servlet-handler/> <!--3.自动扫描包, 让指定包下的注解生效,由IOC容器统一管理--> <context:component-scan base-package="com.codefuheng.controller"/> <!--4.视图解析器 : 模板引擎 Thymeleaf Freemarker--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--前缀--> <property name="prefix" value="/WEB-INF/jsp/"/> <!--后缀--> <property name="suffix" value=".jsp"/> </bean> </beans>
-
-
WEB-INF
-
创建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> </head> <body> <h3>书籍展示</h3> <div> <table> <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.bookCounts}</td> <td>${book.detail}</td> </tr> </c:forEach> </tbody> </table> </div> </body> </html>
-
最后将Spring-dao.xml Spring-service.xml Spring-mvc.xml 导入import到applicationContext.xml中
- Resource层
- applicationContext.xml
<import resource="Spring-dao.xml"/>
<import resource="Spring-service.xml"/>
<import resource="Spring-mvc.xml"/>