1.Helloword

大家好,我是路人,前段时间把spring系列写完之后,就直接写springboot系列了,但是发现了一个问题,有不少粉丝问我springmvc系列哪里看?这些粉丝中可能有些朋友根本没有接触过springmvc,然后直接被我带入了springboot,会突然感觉很懵逼。

目前大多数公司都会使用Springboot来开发微服务,为其他端提供接口,而这些功能都是依靠springmvc实现的,所以为了大家看我的文章能够顺畅一些,还是决定先把springmvc系列补上,不管大家是否学过springmvc,都希望你们和我一起再过一遍springmvc,因为每个人对springmvc的理解也是不一样的,我会采用大量案例来进行讲解,也会介绍原理及源码,希望对你有所帮助。

1、为什么需要学springmvc?

工作需要

目前用到java的企业,99.99%都会用到springmvc,即使没有直接使用springmvc,也会使用springboot,而springboot中基本上都会用到springmvc

面试需要

企业都在使用springmvc,所以面试的时候基本都会问到相关的问题。

更好的学习springboot、springcloud

如果想学好 springboot 和 springcloud,那么必须先掌握spring、springmvc这2个技术。

2、预备知识

学习springmvc之前,需要先掌握2个系列的课程:maven和spring,还未学的朋友,先去补补。

3、软件版本

  • idea 2020.3.3
  • jdk1.8
  • ≥maven3.6.1
  • spring5.3.6
  • apache-tomcat-9.0.46

4、本文目标

通过springmvc实现一个helloword,将项目发布到tomcat中,然后在首页中发起一个请求,请求交给springmvc处理,由springmvc向客户端输出一个helloword,通过这个案例让大家熟悉下springmvc的使用步骤。

5、Helloword案例

开发步骤

 
  1. 1、创建一个maven项目
  2. 2、在项目中创建一个maven web模块
  3. 3、maven中添加springmvc相关依赖
  4. 4、web.xml中配置springmvc
  5. 5、添加springmvc配置文件
  6. 6、写一个HelloWordController
  7. 7、将项目部署到tomcat中
  8. 8、浏览器中验证效果

下面跟着我一步步来操作。

step1:创建一个maven项目

使用idea创建父子项目,打开idea->File->New->Project

按照下图输入对应的信息

点击Finish,项目创建成功,如下图

按照下图中的说明,将红框的部分删除

将pom.xml文件内容替换为下面的内容

 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.javacode2018</groupId>
  7. <artifactId>springmvc-series</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <packaging>pom</packaging>
  10. <properties>
  11. <maven.compiler.source>8</maven.compiler.source>
  12. <maven.compiler.target>8</maven.compiler.target>
  13. </properties>
  14. </project>

此时项目结构如下图

如下图,File->Settings中指定项目maven的版本

step2、项目中创建一个maven模块

选中项目->点击鼠标右键->New->Module,创建一个maven模块

如下图,通过maven的插件来创建web模块,这个地方的maven插件需要注意下,不要选错了

点击上图中的Next,进入下面页面,输入模块的信息,然后点击Next

如下图,继续点击Finish,完成模块的创建

项目结构如下图

chat01-helloword模块中需要添加几个文件夹,操作如下图:

step3、maven中添加springmvc相关依赖

将下面内容替换到chat01-helloword/pom.xml中,主要添加了springmvc和servlet的依赖配置信息。

 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.javacode2018</groupId>
  6. <artifactId>chat01-helloword</artifactId>
  7. <version>1.0-SNAPSHOT</version>
  8. <packaging>war</packaging>
  9. <name>chat01-helloword Maven Webapp</name>
  10. <url>http://www.itsoku.com</url>
  11. <properties>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. </properties>
  14. <dependencies>
  15. <!-- 添加springmvc依赖 -->
  16. <dependency>
  17. <groupId>org.springframework</groupId>
  18. <artifactId>spring-webmvc</artifactId>
  19. <version>5.3.6</version>
  20. </dependency>
  21. <!-- 添加servlet 依赖 -->
  22. <dependency>
  23. <groupId>jakarta.servlet</groupId>
  24. <artifactId>jakarta.servlet-api</artifactId>
  25. <version>5.0.0-M1</version>
  26. <scope>provided</scope>
  27. </dependency>
  28. </dependencies>
  29. <build>
  30. <finalName>chat01-helloword</finalName>
  31. </build>
  32. </project>

step4、web.xml中配置springmvc

web.xml版本太低了,我们先升级下他的版本

点击File->Project Structure->Module,进入到下面界面

点击上图中的-按钮,如下图,然后确定删除

然后按照下面操作,添加新版本的web.xml文件

web.xml版本升级成功

在web.xml中添加springmvc的配置,可以直接将下面替换到web.xml中,主要就是配置了一个DispatcherServlet这个servlet,这个springmvc的核心配置

 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  5. version="4.0">
  6. <!--
  7. 声明springmvc核心配置对象:DispatcherServlet,这是一个servlet
  8. 这个servlet的url-parttern配置的是:*.do
  9. 表示以.do结尾的请求都发送给DispatcherServlet这个servlet去处理
  10. -->
  11. <servlet>
  12. <servlet-name>springmvc</servlet-name>
  13. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  14. <init-param>
  15. <!-- contextConfigLocation 用来指定springmvc配置文件的位置,文件名称不一定要交springmvc,大家可以随意起名 -->
  16. <param-name>contextConfigLocation</param-name>
  17. <param-value>classpath:springmvc.xml</param-value>
  18. </init-param>
  19. <!-- load-on-startup:表示web容器启动的时,当前对象创建的顺序,值越小初始化越早,大于等于0 -->
  20. <load-on-startup>0</load-on-startup>
  21. </servlet>
  22. <servlet-mapping>
  23. <servlet-name>springmvc</servlet-name>
  24. <url-pattern>*.do</url-pattern>
  25. </servlet-mapping>
  26. </web-app>

step5、添加springmvc配置文件

chat01-helloword->resource->鼠标右键->New->XXML Configuration File->Spring Config

输入文件名称:springmvc.xml

文件添加成功

替换下这个文件的内容

 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. 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">
  6. <!-- springmvc容器(也就是一个spring容器)会扫描指定包中的组件,将其注册到springmvc容器中 -->
  7. <context:component-scan base-package="com.javacode2018.springmvcseries.chat01"/>
  8. </beans>

step6、写一个HelloWordController

这个类中创建了一个hello方法,方法上面添加了一个@RequestMapping 注解,是Springmvc中的一个注解,value属性用来指定一个url列表,springmvc会将这些指定的url请求转发给当前方法处理。

我们希望访问/hello.do的时候,跳转到/WEB-INF/view/hello.jsp这个页面,这个页面中输出一段内容

 
  1. package com.javacode2018.springmvcseries.chat01;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.servlet.ModelAndView;
  5. @Controller
  6. public class HelloController {
  7. /**
  8. * @RequestMapping:用来表示url和方法的映射
  9. * value属性用来指定一个url列表,springmvc会将这些指定的url请求转发给当前方法处理
  10. * @return
  11. */
  12. @RequestMapping("/hello.do")
  13. public ModelAndView hello() {
  14. ModelAndView modelAndView = new ModelAndView();
  15. modelAndView.setViewName("/WEB-INF/view/hello.jsp");
  16. //稍后将这个信息显示在hello.jsp中,modelAndView.addObject相当于request.setAttribute(name,value)
  17. modelAndView.addObject("msg","这是第一个springboot程序!");
  18. return modelAndView;
  19. }
  20. }

/WEB-INF/view/中添加hello.jsp内容如下

 
  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4. <title>spingmvc系列</title>
  5. </head>
  6. <body>
  7. <h1>hello SpringMVC</h1>
  8. </body>
  9. </html>

修改index.jsp的内容,如下,主要添加一个超链接,当点击这个超链接的时候,请求会发给springmvc,然后springmvc会将请求转发给HelloController的hello方法,然后通过这个方法最后将hello.jsp内容输出

 
  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4. <title>spingmvc系列</title>
  5. </head>
  6. <body>
  7. <div style="text-align: center">
  8. <h1>hello SpringMVC</h1>
  9. <h1>msg:${msg}</h1>
  10. </div>
  11. </body>
  12. </html>

step7、将项目部署到tomcat中

这里我们将项目部署到tomcat10中,过程如下:

如下图,启动tomcat

step8、验证效果

访问:http://localhost:8080/chat01/

点击页面中的连接,会跳转到http://localhost:8080/chat01/hello.do,输出

6、SpringMVC处理器请的过程

6.1、详细的过程

1、tomcat启动的时候,会初始化DispatcherServlet,DispatcherServlet中会创建一个springmvc容器,其实就是我们熟悉的spring容器(ApplicationContext),只不过这个容器的类型是(WebApplicationContext),此容器会加载web.xml中contextConfigLocation指定的springmvc配置文件

2、由于springmvc.xml中指定了扫描包的规则,而HelloController符合这个扫描规则,所以会被注册到springmvc容器中

3、当发起*.do请求的时候,请求会到达DispatcherServlet中央处理器,中央处理器会根据请求路径,去springmvc容器中找到能够处理这个请求的方法,具体由哪个方法来处理这个请求呢?

这里就是通过@RequestMapping来匹配的,这个注解可以将请求和方法进行映射,匹配的请求会被@RequestMapping标注的方法处理,所以在这个步骤中springmvc容器会发现HelloController这个bean的hello方法方法可以处理/hello.do请求

4、DispatcherServlet中通过反射来调用helloController这个bean的hello方法

5、DispatcherServlet接收到了hello方法的返回值

6、DispatcherServlet根据hello方法的返回值,做跳转操作,相当于

 
  1. request.getRequestDispatcher("/WEB-INF/view/hello.jsp").forward(request,response);

6.2、简化过程

客户端发送请求 —-> 到达tomcat —-> tomcat发现是请求是*.do的请求 —-> tomcat 将请求转发给中央调度器DispatcherServlet —-> 中央调度器根据url将转发给我们自定义的controller —-> DispacherServlet根据controller的返回结果做跳转操作 —-> 将结果输出到客户端

7、总结

本文主要通过一个案例详细介绍了springmvc开发项目的一个过程,大家把案例敲一遍,有问题,欢迎留言交流。

8、软件及代码位置

软件地址:

 
  1. 链接:https://pan.baidu.com/s/1_Ol-UZkN_6woMBtjcFygvQ
  2. 提取码:e66j

代码位于码云上

 
  1. https://gitee.com/javacode2018/springmvc-series
D:\javaJDK17\bin\java.exe "-javaagent:D:\编程软件\idea2022\IntelliJ IDEA 2022.1.3\lib\idea_rt.jar=4912:D:\编程软件\idea2022\IntelliJ IDEA 2022.1.3\bin" -Dfile.encoding=UTF-8 -classpath "D:\IDEA java\javaWeb\Maven\maven-project01\target\classes;D:\Maven\apache-maven-3.9.3-bin\apache-maven-3.9.3\mvn_store\org\mybatis\mybatis\3.5.5\mybatis-3.5.5.jar;D:\Maven\apache-maven-3.9.3-bin\apache-maven-3.9.3\mvn_store\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.jar;D:\Maven\apache-maven-3.9.3-bin\apache-maven-3.9.3\mvn_store\org\slf4j\slf4j-api\1.7.32\slf4j-api-1.7.32.jar;D:\Maven\apache-maven-3.9.3-bin\apache-maven-3.9.3\mvn_store\ch\qos\logback\logback-core\1.2.6\logback-core-1.2.6.jar;D:\Maven\apache-maven-3.9.3-bin\apache-maven-3.9.3\mvn_store\ch\qos\logback\logback-classic\1.2.6\logback-classic-1.2.6.jar" Demo1.HelloWord Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: java.sql.SQLException: Error setting driver on UnpooledDataSource. Cause: java.lang.ClassNotFoundException: Cannot find class: ${com.mysql.jdbc.Driver} ### The error may exist in UserMapper.xml ### The error may involve test.selectAll ### The error occurred while executing a query ### Cause: java.sql.SQLException: Error setting driver on UnpooledDataSource. Cause: java.lang.ClassNotFoundException: Cannot find class: ${com.mysql.jdbc.Driver} at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:149) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:140) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:135) at Demo1.HelloWord.main(HelloWord.java:23) Caused by: java.sql.SQLException: Error setting driver on UnpooledDataSource. Cause: java.lang.ClassNotFoundException: Cannot find class: ${com.mysql.jdbc.Driver} at org.apache.ibatis.datasource.unpooled.UnpooledDataSource.initializeDriver(UnpooledDataSource.java:244) at org.apache.ibatis.datasource.unpooled.UnpooledDataSource.doGetConnection(UnpooledDataSource.java:223) at org.apache.ibatis.datasource.unpooled.UnpooledDataSource.doGetConnection(UnpooledDataSource.java:219) at org.apache.ibatis.datasource.unpooled.UnpooledDataSource.getConnection(UnpooledDataSource.java:95) at org.apache.ibatis.datasource.pooled.PooledDataSource.popConnection(PooledDataSource.java:432) at org.apache.ibatis.datasource.pooled.PooledDataSource.getConnection(PooledDataSource.java:89) at org.apache.ibatis.transaction.jdbc.JdbcTransaction.openConnection(JdbcTransaction.java:139) at org.apache.ibatis.transaction.jdbc.JdbcTransaction.getConnection(JdbcTransaction.java:61) at org.apache.ibatis.executor.BaseExecutor.getConnection(BaseExecutor.java:337) at org.apache.ibatis.executor.SimpleExecutor.prepareStatement(SimpleExecutor.java:86) at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:62) at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:325) at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:89) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:147) ... 3 more
07-22
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值