【springmvc框架一文搞定】

SpringMVC框架

  • 1. 搭建springmvc测试项目
    • 1.1 创建maven项目
    • 1.2 导入依赖pom.xml
    • 1.3 将springmvc容器加载到tomcat中
    • 1.4 启动tomcat插件
    • 1.5 访问路径:
  • 2. 剖析启动过程
    • 2.1 启动服务器初始化过程
    • 2.2 访问路径执行过程
  • 3.spring-springmvc bean的管理
    • 3.1 因为功能不同,如何避免spring错误的加载到?
    • 3.2 spring加载与spring相关的bean
    • 3.3 springmvc加载springmvc相关的bean
    • 3.4 将springmvc与spring的bean加载到服务tomcat容器中
    • 3.5 启动tomcat插件
    • 3.6 查看打印日志
    • 3.7 当我们自己编写一个容器的时候,并且注册进去
  • 4. 请求与响应
    • 4.1 请求映射路径
    • 4.2 请求参数
    • 4.3 日期类型参数传递
    • 4.4 响应json数据

1. 搭建springmvc测试项目

1.1 创建maven项目

1.2 导入依赖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>com.ypy</groupId>
    <artifactId>springmvc_01_quickstart</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging> <!--修改为war包否者tomcat插件启动后就停止了,没有可以运行的代码-->

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
    </dependencies>
        <!--tomcat插件 启动项目的容器插件-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <port>80</port>
                    <path>/</path>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

1.3 将springmvc容器加载到tomcat中

public class ServletContainerInitConfig extends AbstractDispatcherServletInitializer {
    @Override
    protected WebApplicationContext createServletApplicationContext() {
    	// 项目使用注解配置Web应用上下文
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        // 将配置类注册到上下文
        ctx.register(SpringMvcConfig.class);
        return ctx;
    }

    @Override
    // 配置拦截路径,哪些访问路径需要springmvc管理
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    // 配置其他容器上下文
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }
}

扫描controller进入容器

@ComponentScan("com.ypy.controller")
public class SpringMvcConfig {
}

控制器类

@Controller
public class UserController {

    @RequestMapping("/save")
    @ResponseBody
    public String save(){
        System.out.println("user save ...");
        return "{'info':'Springmvc'}";
    }
}

1.4 启动tomcat插件

edit configurations -> 搜maven -> run: tomcat7:run --> apply. --> run (绿色三角)启动

1.5 访问路径:

http://localhost/save
返回:
在这里插入图片描述

2. 剖析启动过程

2.1 启动服务器初始化过程

  1. 服务器启动,执行ServletContainerInitConfig类,初始化web容器
  2. 执行createServletApplicationContext方法,创建了WebApplicationContext对象
  3. 加载SpringMvcConfig
  4. 执行@ComponentScan加载对应的bean
  5. 加载UserController,每个@RequestMapping的名称对应一个具体的方法
  6. 执行getServletMappings方法,定义所有的请求都通过SpringMVC
    在这里插入图片描述

2.2 访问路径执行过程

  1. 发送请求localhost/save
  2. web容器发现所有请求多经过springmvc,将请求交给springmvc处理
  3. 解析请求路径/save
  4. 有/save匹配执行对应的方法save()
  5. 执行save()
  6. 检测有@RequestBody直接将save()方法的返回值作为响应体返回给请求方。

3.spring-springmvc bean的管理

1.springmvc会加载controller相关的bean
2. spring会加载service、dao、config等包下的bean,那么就会扫描根包下的所有子包,这样就会重复

3.1 因为功能不同,如何避免spring错误的加载到?

SpringMVC的bean–加载Spring控制的bean的时候排除掉springmvc控制的bean

方法:

  1. Spring加载的bean设定扫描范围为com.itheima,排除掉controllert包内的bean
  2. Spring加载的bean设定扫描范围为精准范围,例如service包、dao包等
  3. 不区分Spring与SpringMVC的环境,加载到同一个环境中

3.2 spring加载与spring相关的bean

@Configuration
//@ComponentScan({"com.ypy.service","com.ypy.dao"})
@ComponentScan(value = "com.ypy",
        excludeFilters = @ComponentScan.Filter(
                type = FilterType.ANNOTATION,
                classes = {Controller.class,RestController.class}
        )
)
public class SpringConfig {
}

3.3 springmvc加载springmvc相关的bean

@ComponentScan("com.ypy.controller")
public class SpringMvcConfig {
}

3.4 将springmvc与spring的bean加载到服务tomcat容器中

public class ServletContainerInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        System.out.println("1被调用了);
        return new Class[]{SpringConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
    	System.out.println("2被调用了);
        return new Class[]{SpringMvcConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
       	System.out.println("3被调用了);
        return new String[]{"/"};
    }
}

或者

public class ServletContainerInitConfig extends AbstractDispatcherServletInitializer {
   // 注册springmvc容器bean
   @Override
   protected WebApplicationContext createServletApplicationContext() {
       AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
       ctx.register(SpringMvcConfig.class);
       return ctx;
   }

   @Override
   protected String[] getServletMappings() {
       return new String[]{"/"};
   }

   // 注册spring的容器bean
   @Override
   protected WebApplicationContext createRootApplicationContext() {
       AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
       ctx.register(SpringConfig.class);
       return ctx;
   }
}

3.5 启动tomcat插件

同上,启动方式
edit configurations -> 搜maven -> run: tomcat7:run --> apply. --> run (绿色三角)启动

3.6 查看打印日志

[INFO] Scanning for projects...
[INFO] 
[INFO] ------------------< com.ypy:springmvc_01_quickstart >-------------------
[INFO] Building springmvc_01_quickstart 1.0-SNAPSHOT
[INFO] --------------------------------[ war ]---------------------------------
[INFO] 
[INFO] >>> tomcat7-maven-plugin:2.2:run (default-cli) > process-classes @ springmvc_01_quickstart >>>
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ springmvc_01_quickstart ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ springmvc_01_quickstart ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 5 source files to D:\Application\WorkSpace\self-learn\base-learn\springmvc_01_quickstart\target\classes
[INFO] 
[INFO] <<< tomcat7-maven-plugin:2.2:run (default-cli) < process-classes @ springmvc_01_quickstart <<<
[INFO] 
[INFO] 
[INFO] --- tomcat7-maven-plugin:2.2:run (default-cli) @ springmvc_01_quickstart ---
[INFO] Running war on http://localhost:80/
[INFO] Using existing Tomcat server configuration at D:\Application\WorkSpace\self-learn\base-learn\springmvc_01_quickstart\target\tomcat
[INFO] create webapp with contextPath: 
十一月 13, 2023 9:47:44 下午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["http-bio-80"]
十一月 13, 2023 9:47:44 下午 org.apache.catalina.core.StandardService startInternal
信息: Starting service Tomcat
十一月 13, 2023 9:47:44 下午 org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet Engine: Apache Tomcat/7.0.47
十一月 13, 2023 9:47:45 下午 org.apache.catalina.core.ApplicationContext log
信息: 1 Spring WebApplicationInitializers detected on classpath
1被调用了
2被调用了
3被调用了
十一月 13, 2023 9:47:45 下午 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring root WebApplicationContext
[INFO] Root WebApplicationContext: initialization started
[INFO] Root WebApplicationContext initialized in 261 ms
[INFO] Initializing Servlet 'dispatcher'
十一月 13, 2023 9:47:45 下午 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring DispatcherServlet 'dispatcher'
[INFO] Completed initialization in 119 ms
十一月 13, 2023 9:47:45 下午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["http-bio-80"]
// 发送请求,打印的输出结果
user save ...

3.7 当我们自己编写一个容器的时候,并且注册进去

import com.ypy.config.SpringConfig;
import com.ypy.config.SpringMvcConfig;
import com.ypy.controller.UserController;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App {
    public static void main(String[] args) {
    	// 创建一个internal container
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        // 注册配置类
        ctx.register(SpringConfig.class, SpringMvcConfig.class);
        // 刷新容器
        ctx.refresh();
        //容器获取bean
        UserController bean = ctx.getBean(UserController.class);
        System.out.println(bean);
    }
}

// 输出结果:
com.ypy.controller.UserController@64c87930

4. 请求与响应

4.1 请求映射路径

4.2 请求参数

4.3 日期类型参数传递

4.4 响应json数据

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/145811.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

langchain实战-hello world

一、LangChain简介 github地址&#xff1a; GitHub - langchain-ai/langchain: ⚡ Building applications with LLMs through composability ⚡ LangChain是一个用于开发由语言模型支持的应用程序的框架。它使应用程序能够&#xff1a; 具有上下文感知能力&#xff1a;将语言模…

BES2700H开发不完全手册

BES2700H开发不完全手册 是否需要申请加入数字音频系统研究开发交流答疑群(课题组)&#xff1f;可加我微信hezkz17, 本群提供音频技术答疑服务&#xff0c;群赠送语音信号处理降噪算法&#xff0c;ANC AEC ENC EQ BF BES蓝牙耳机音频资料 1 成功编译 2 代码 3 开放文档

餐饮业数字化革命:抖音小程序团购功能的开发与优化

本文将聚焦于餐饮业数字化的前沿&#xff0c;着眼于抖音小程序团购功能的开发与优化&#xff0c;探讨如何借助这一功能实现餐饮业的蓬勃发展。 一、数字化浪潮下的餐饮业 传统餐饮业面临的挑战在于如何更好地适应快节奏生活和消费者多元化需求。数字化浪潮为餐饮业提供了解决方…

[Linux] ssh远程访问及控制

一、ssh介绍 1.1 SSH简介 SSH&#xff08;Secure Shell&#xff09;是一种安全通道协议&#xff0c;主要用于实现远程登录、远程复制等功能的字符接口。SSH 协议包括用户在登录时输入的用户密码、双方之间的通信。 加密数据传输&#xff0c;SSH 是一种建立在应用层和传输层上…

第06章 面向对象编程(基础)

一 面向对象编程概述 1.1 程序设计的思路 面向对象&#xff0c;是软件开发中的一类编程风格、开发范式。除了面向对象&#xff0c;还有面向过程、指令式编程和函数式编程。在所有的编程范式中&#xff0c;我们接触最多的还是面向过程和面向对象两种。 类比&#xff1a;史书类…

manim更新

manim升级18.0 # 1 更新pip&#xff0c;推荐轮子下载 python -m pip install --upgrade pip 推荐方式下载轮子安装 首先尝试在中断更新pip&#xff0c;通过命令python -m pip install --upgrade pip 可能遇到以下情况 记录最新的pip轮子名 记录下上面pip的名称&#xff0c;去…

得帆信息携手深信服,联合打造高安全PaaS超融合一体化解决方案

上海得帆信息技术有限公司&#xff08;以下简称“得帆”&#xff09;和深信服科技股份有限公司&#xff08;以下简称“深信服”&#xff09;携手推出融合安全性、稳定性、高效性于一体的全新PaaS超融合解决方案。 用户痛点分析 全面推进企业数字化与信息化的趋势下&#xff0c;…

深入探讨Linux中的文本文件查看命令

目录 前言1 cat命令2 less命令3 more命令4 head命令5 tail命令6 总结 前言 在Linux系统中&#xff0c;文本文件是日常工作中不可或缺的一部分&#xff0c;无论是配置文件、日志文件还是代码文件&#xff0c;都需要用到文本文件查看命令。在本文中&#xff0c;我们将深入研究一…

块设备的工作模式

块设备的mknod 还是会创建在 /dev 路径下面&#xff0c;这一点和字符设备一样。/dev 路径下面是 devtmpfs 文件系统。这是块设备遇到的第一个文件系统。我们会为这个块设备文件&#xff0c;分配一个特殊的 inode&#xff0c;这一点和字符设备也是一样的。只不过字符设备走 S_IS…

pcl opencv关于flann的冲突:flann_algorithm_t等

问题如下&#xff1a; 引起问题的点&#xff1a; 解决方法&#xff1a;先include pcl后include opencv; 其他解决方式是在环境变量中将pcl置于opencv前面&#xff0c;但是这里如果是先include opencv&#xff0c;后include pcl问题得不到解决&#xff1b;

java实现冒泡排序

冒泡排序是一种简单的排序算法&#xff0c;以下是Java实现示例代码&#xff1a; public static void bubbleSort(int[] array) {int n array.length;for (int i 0; i < n - 1; i) {for (int j 0; j < n - i - 1; j) {// 如果前面的元素比后面的元素大&#xff0c;就交…

【JVM】Java内存溢出分析(堆溢出、栈溢出、方法区溢出、直接内存溢出)

&#x1f4eb;作者简介&#xff1a;小明java问道之路&#xff0c;2022年度博客之星全国TOP3&#xff0c;专注于后端、中间件、计算机底层、架构设计演进与稳定性建设优化&#xff0c;文章内容兼具广度、深度、大厂技术方案&#xff0c;对待技术喜欢推理加验证&#xff0c;就职于…

ros 使用turtlesim包报错

ros 使用turtlesim包报错 rosrun] Couldn’t find executable named turtlesim_node below /opt/ros/noetic/share/turtlesim 先说一下前提&#xff0c;我的命名空间是demo03-ws&#xff0c;创建了一个功能包叫rename01_node,下面编写了一个launch文件&#xff0c;如下 希望…

2023nacos源码解读第3集——nacos-client核心功能之微服务调用和配置管理测试

文章目录 1、测试项目2、项目注意事项3、 测试核心功能3.1 测试服务调用与负载均衡3.2 测试配置监听 4、参考文档 1、测试项目 项目地址 nacos-service-a nacos-service-b 2、项目注意事项 项目初始化可以使用aliyun spring initializer ,以更方便的使用springcloud alibaba…

CleanMyMac4.14中文免费版mac系统管理软件

许多小伙伴使用Mac后都反馈电脑不如想象中的流畅&#xff0c;甚至有点卡顿的现象&#xff0c;原因可能是因为无用的应用占据了过多的内存&#xff0c;或者是系统盘垃圾过多&#xff0c;导致的电脑卡顿现象。 今天小编教给大家几招&#xff0c;让自己的Mac能够一键重生&#xf…

自律性差怎么办,如何提高自律能力?

自律的力量是强大的&#xff0c;当然一个人不自律也没啥大不了的事&#xff0c;毕竟不自律的人才是大多数&#xff0c;但是当你想要有所成就的时候&#xff0c;那你就必须要学会自律&#xff0c;提高自律。 如果一个人缺乏自律性&#xff0c;那么学生时代肯定成绩不稳定&#…

线性模型拟合非线性数据中,如何找到最优的【分箱】数

具体的数据可以回看上一条博客。我们先来始化三个空列表&#xff0c;用于存储后续计算的预测得分、交叉验证得分的平均值和交叉验证得分的方差。 pred,score,var [], [], [] 2. 再定义一个列表&#xff0c;包含了我们想要尝试的分箱数量。 binsrange [2,5,10,15,20,30] 3…

MySQL学习day02

一、SQL通用语法 1&#xff09;SQL语句可以单行或多行书写&#xff0c;以分号结尾 2&#xff09;SQL语句可以使用空格/缩进来增强语句的可读性 3&#xff09;MySQL数据库的SQL语句不区分大小写&#xff0c;关键字建议使用大写 4&#xff09;注释&#xff1a; a)单行注释&#x…

深度学习+opencv+python实现昆虫识别 -图像识别 昆虫识别 计算机竞赛

文章目录 0 前言1 课题背景2 具体实现3 数据收集和处理3 卷积神经网络2.1卷积层2.2 池化层2.3 激活函数&#xff1a;2.4 全连接层2.5 使用tensorflow中keras模块实现卷积神经网络 4 MobileNetV2网络5 损失函数softmax 交叉熵5.1 softmax函数5.2 交叉熵损失函数 6 优化器SGD7 学…