SpringMVC-学习笔记

news2025/5/11 3:07:45

文章目录

    • 1.概述
      • 1.1 SpringMVC快速入门
    • 2. 请求
      • 2.1 加载控制
      • 2.2 请求的映射路径
      • 2.3 get和post请求发送
      • 2.4 五种请求参数种类
      • 2.5 传递JSON数据
      • 2.6 日期类型参数传递
    • 3.响应
      • 3.1 响应格式
    • 4.REST风格
      • 4.1 介绍
      • 4.2 RESTful快速入门
      • 4.3 简化操作

1.概述

SpringMVC是一个基于Java的Web应用程序框架,用于构建灵活和可扩展的MVC(Model-View-Controller)架构的Web应用程序。

  • 它是Spring框架的一部分,旨在简化Web应用程序的开发过程。
  • SpringMVC技术与Servlet技术功能等同,属于WEB层开发技术。

SpringMVC优点:

  • 简化WEB层开发;
  • 与Spring、SpringBoot等框架集成;
  • 提供强大的约定大于配置的契约式编程支持;
  • 支持REST风格;

1.1 SpringMVC快速入门

步骤:

  1. 创建maven-web工程
  2. 添加spring-webmvc依赖
  3. 准备controller类(处理浏览器请求的接口)
  4. 创建配置文件
  5. 定义一个用于配置Servlet容器的初始化类,加载spring配置
  6. 启用测试
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.imooc</groupId>
  <artifactId>springmvc-demo</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>

  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.9.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <port>81</port>
          <path></path>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

package it.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


//3.创建控制器(等同于servlet)
@Controller
public class MyController {
    //设置当前操作的请求路径
    @RequestMapping("/save")
    //设置当前操作的返回类型
    @ResponseBody
    public String save(){
        System.out.println("user saving...");
        return "{'info':'springmvc'}";
    }
}


-------------------------------------------------------------------------------------
package it.conf;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

//4.创建springmvc的配置文件,加载controller对应的bean
@Configuration
@ComponentScan("it.controller")
public class SpringMvcConfig {
}

------------------------------------------------------------------------------------------------
package it.conf;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

//
//5.定义一个用于配置Servlet容器的初始化类,加载spring配置
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
    //创建Servlet应用程序上下文,加载springmvc容器配置
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(SpringMvcConfig.class);
        return context;
    }

    //配置DispatcherServlet映射的URL路径,设置哪些请求归属springmvc处理
    //{"/"}表示所有请求
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    //创建根应用程序上下文,加载spring容器配置
    @Override
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }
}




在这里插入图片描述

2. 请求

2.1 加载控制

Spring相关bean

  • 业务bean(Service)
  • 功能bean(DataSource)

SpringMVC相关bean

  • 表现bean

不同的bean都是通过@controller 定义如何避免扫描混乱?
在这里插入图片描述

配置Servlet容器的初始化,并加载Spring和Spring MVC的配置的两种方式:

方法1:继承自AbstractDispatcherServletInitializer

package it.conf;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

//
//定义一个用于配置Servlet容器的初始化类,加载spring配置
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
    //创建Servlet应用程序上下文,加载springmvc容器配置
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(SpringMvcConfig.class);
        return context;
    }

    //配置DispatcherServlet映射的URL路径,设置哪些请求归属springmvc处理
    //{"/"}表示所有请求
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    //创建根应用程序上下文,加载spring容器配置
    @Override
    protected WebApplicationContext createRootApplicationContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(SpringConfig.class);
        return context;
    }
}

方法2:继承自AbstractAnnotationConfigDispatcherServletInitializer类

package it.conf;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

//
//定义一个用于配置Servlet容器的初始化类,加载spring配置
public class ServletContainersInitConfigg extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

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

2.2 请求的映射路径

避免不同控制器中有相同的请求映射,每个控制器类中要加应该请求路径前缀,用于区分不同的请求

@Controller
@RequestMapping("/book")   //请求路径的前缀
public class BookController {
    @RequestMapping("/save")  //请求映射
    @ResponseBody
    public String save(){
        System.out.println("book save");
        return "{'module':'book save'}";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String delete(){
        System.out.println("book delete");
        return "{'module':'book save'}";
    }
}

在这里插入图片描述

2.3 get和post请求发送

get请求

在这里插入图片描述
在这里插入图片描述

post请求

在这里插入图片描述

在这里插入图片描述

解决中文乱码问题

  • 在Springmvc的Servlet容器配置中添加过滤器
@Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("utf-8");
        return new Filter[]{characterEncodingFilter};
    }

在这里插入图片描述

2.4 五种请求参数种类

参数类型:

  1. 普通参数
  2. POJO类型参数
  3. 嵌套POJO
  4. 数组类型
  5. 集合类型

@ResponseBody的作用

  • 设置当前控制器方法响应内容为当前返回值,无需解析。

参数映射规则

  • 客户端传递的参数名称需要和服务器端的参数名称对应,名称不对应无法接受。
    在这里插入图片描述
  • 解决:注解@RequestParam
    在这里插入图片描述

2.实体类参数传递
在这里插入图片描述

在这里插入图片描述
3.嵌套POJO
在这里插入图片描述
4. 数组类型
在这里插入图片描述
5. 集合类型
在这里插入图片描述

2.5 传递JSON数据

添加json坐标

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>

在SpringMvcConfig配置文件中添加@EnableWebMvc开启Json转换功能

package com.it.config;

@Configuration
@ComponentScan("com.it.controller")
@EnableWebMvc
public class SpringMvcConfig{
}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

2.6 日期类型参数传递

日期格式:

  • 2023-08-29
  • 2023/08/29
  • 08/23/2023

在这里插入图片描述
在这里插入图片描述

3.响应

3.1 响应格式

响应:将处理完的结果反馈给客户端(浏览器)

  • 响应页面

  • 响应数据

    • 文本数据
    • json数据

@ResponseBody的作用

  • 设置当前控制器返回值作为响应体
  • 对象->json 、list->json

1.响应页面

package com.it.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class UserRespController {

    //响应页面
    @RequestMapping("/toJumpPage")
    public String toJumpPage(){
        System.out.println("跳转页面中");
        return "page.jsp";
    }
}

在这里插入图片描述

<%--
  Created by IntelliJ IDEA.
  User: 11445
  Date: 2023/8/29
  Time: 18:22
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>跳转页面</title>
</head>
<body>
<h1>跳转页面hh</h1>
</body>
</html>

跳转到其他网站页面

将返回值改为 “redirect:https://www.baidu.com/”

//响应页面2
    @RequestMapping("/tobaidu")
    public String tobaidu(){
        System.out.println("跳转页面中");
        return "redirect:https://www.baidu.com/";
    }

在这里插入图片描述
2.响应文本数据

//响应文本
    @RequestMapping("/toText")
    @ResponseBody
    public String toText(){
        System.out.println("响应文本");
        return "response text";
    }

在这里插入图片描述
3.响应JSON数据

//响应JSON
    @RequestMapping("/toJSON")
    @ResponseBody
    public User toJSON(){
        System.out.println("响应JSON");
        User user = new User();
        user.setId(1);
        user.setAge(56);
        user.setName("nimi");
        return user;
    }

在这里插入图片描述

4.REST风格

4.1 介绍

REST(Representational State Transfer)表现形式转换

  • 是一种软件架构风格,用于设计网络应用程序的分布式系统。
  • 使用统一的接口基于资源的通信方式,通过HTTP协议进行通信。

REST风格的设计原则

  1. 基于资源:将应用程序的功能抽象为资源,每个资源通过唯一的URL进行标识。
  2. 使用HTTP方法:通过HTTP的不同方法(GET、POST、PUT、DELETE等)对资源进行操作。
  3. 无状态:服务器不保存客户端的状态信息,每个请求都包含足够的信息来完成请求。
  4. 统一接口:使用统一的接口定义资源的操作方式,包括资源的标识、操作方法和表示形式等。
  5. 可缓存性:对于不经常变化的资源,可以使用缓存机制提高性能。
  6. 分层系统:不同的组件可以通过中间层进行通信,提高系统的可伸缩性和灵活性。

与传统资源描述形式的区别

传统风格
http://localhost/user/getById?id=1
http://localhost/user/saveUser

REST
http://localhost/user/1
http://localhost/user
---------------------------------------------------------------------------

按照REST风格访问资源使用 -行为动作- 区分对资源进行何种操作

查全部用户 GET:http://localhost/user                 
查指定用户 GET:http://localhost/user/1
添加用户 POST:http://localhost/user
修改用户 PUT :http://localhost/user
删除用户 DELETE:http://localhost/user/1

优点

  • 隐藏了资源的访问行为,无法通过地址得知对资源是何种操作
  • 书写简化

4.2 RESTful快速入门

package com.it.controller;

import com.it.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class UserRestController {

    //1通过id查
    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    @ResponseBody
    public String getById(@PathVariable Integer id){
        System.out.println("通过id查询"+id);
        return "...";
    }

    //查全部
    @RequestMapping(value = "/user",method = RequestMethod.GET)
    @ResponseBody
    public String getAll(){
        System.out.println("查全部");
        return "...";
    }

    //修改
    //@ResponseBody注解表示该方法的返回值将直接作为HTTP响应的body部分返回给客户端。
    // insert方法返回的字符串将作为响应的body返回给客户端。

    //@RequestBody注解表示该方法需要从请求的body部分获取数据,通常用于处理POST、PUT请求中的数据。
    // @RequestBody User user表示将请求的body中的数据转换为User对象,并作为参数传入insert方法中。
    @RequestMapping(value = "/user",method = RequestMethod.PUT)
    @ResponseBody
    public String update(@RequestBody User user){
        System.out.println("修改"+user);
        return "...";
    }

    //新增
    @RequestMapping(value = "/user",method = RequestMethod.POST)
    @ResponseBody
    public String insert(@RequestBody User user){
        System.out.println("新增"+user);
        return "...";
    }

    //删除
    //@PathVariable是Spring MVC中的注解,它的作用是将路径中的变量与方法参数进行绑定。
    // @PathVariable注解用于绑定路径中的{id}变量到方法参数id上,即通过{id}来获取请求路径中的id值。
    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public String delete(@PathVariable Integer id){
        System.out.println("通过id删除"+id);
        return "...";
    }
}

在这里插入图片描述

4.3 简化操作

package com.it.controller;

import com.it.pojo.User;
import org.springframework.web.bind.annotation.*;



@RestController //@Controller和@ResponseBody的合体
@RequestMapping("/user")

public class UserRestEasyController {

    //1通过id查
    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id){
        System.out.println("通过id查询1"+id);
        return "...";
    }

    //查全部
    @GetMapping
    public String getAll(){
        System.out.println("查全部");
        return "...";
    }

    //修改
    @PutMapping
    public String update(@RequestBody User user){
        System.out.println("修改"+user);
        return "...";
    }

    //新增
    @PostMapping
    public String insert(@RequestBody User user){
        System.out.println("新增"+user);
        return "...";
    }

    //删除
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id){
        System.out.println("通过id删除"+id);
        return "...";
    }
}

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

day-04 基于UDP的服务器端/客户端

一.理解UDP &#xff08;一&#xff09;UDP套接字的特点 UDP套接字具有以下特点&#xff1a; 无连接性&#xff1a;UDP是一种无连接的协议&#xff0c;这意味着在发送数据之前&#xff0c;不需要在发送方和接收方之间建立连接。每个UDP数据包都是独立的&#xff0c;它们可以独…

【HSPCIE仿真】输入网表文件(4)常用分析

常用分析 1. 概述2. 直流初始化和工作点分析2.1 电路初始化(.ic)2.2 初始状态语句初始条件语句.IC 和.DCVOLT节点电压设置语句.NODESET 2.2 直流工作点分析(.op)基本语法示例 2.3 直流扫描分析 (.dc)基本语法示例 2.4 其他类型的直流分析 3. 瞬态分析(.TRAN)基本语法示例 4. 其…

CTFhub-文件上传-前端验证

burp 抓包 --> 重发--> 查看源代码 用 GodZilla 生成木马 文件名为 1.php.jsp 上传-->抓包-->改包 (删掉 .jpg) --> 点击 放行 木马文件位置为&#xff1a;http://challenge-f0531d0c27641130.sandbox.ctfhub.com:10800/upload/1.php 用 蚁剑连接 ctfhub{4743b…

【pyqt5界面化工具开发-7】窗口开发-菜单栏窗口QMainWindow

目录 0x00 前言&#xff1a; 一、调用父类的菜单 二、添加菜单内选项 0x00 前言&#xff1a; QWedget 控件和窗口的父类&#xff0c;自由度高(什么都东西都没有)&#xff0c;没有划分菜单、工具栏、状态栏、主窗口 等区域 QMainWindow 是 QWwidget 的子类&#xff0c;包含菜…

【AI】数学基础——高数(函数微分部分)

参考&#xff1a;https://www.bilibili.com/video/BV1mM411r7ko?p1&vd_source260d5bbbf395fd4a9b3e978c7abde437 唐宇迪&#xff1a;机器学习数学基础 文章目录 1.1 函数1.1.1 函数分类1.1.2 常见函数指/对数函数分段函数原函数&反函数sigmod函数Relu函数(非负函数)复…

dvwa文件上传通关及代码分析

文章目录 low等级medium等级high等级Impossible等级 low等级 查看源码&#xff1a; <?phpif( isset( $_POST[ Upload ] ) ) {// Where are we going to be writing to?$target_path DVWA_WEB_PAGE_TO_ROOT . "hackable/uploads/";$target_path . basename( …

uni-search-bar 实现搜索框自动获取焦点

<!-- 基本用法 --> <uni-search-bar confirm"search" input"input" ></uni-search-bar>查看源代码show:true, showSync&#xff1a;true, 都改为true 即可实现

The Cherno——OpenGL

The Cherno——OpenGL 1. 欢迎来到OpenGL OpenGL是一种跨平台的图形接口&#xff08;API&#xff09;&#xff0c;就是一大堆我们能够调用的函数去做一些与图像相关的事情。特殊的是&#xff0c;OpenGL允许我们访问GPU&#xff08;Graphics Processing Unit 图像处理单元&…

CTFHUB_web_密码口令_默认口令

登陆界面如图所示&#xff0c;题目提示默认口令&#xff1a; 查找常用默认口令&#xff1a; 常见web系统默认口令总结 常见网络安全设备弱口令(默认口令) 找到相关内容&#xff1a; 输入用户名密码得到flag

ChatGPT⼊门到精通(4):ChatGPT 为何⽜逼

⼀、通⽤型AI 在我们原始的幻想⾥&#xff0c;AI是基于对海量数据的学习&#xff0c;锻炼出⼀个⽆所不知⽆所不能的模 型&#xff0c;并借助计算机的优势&#xff08;计算速度、并发可能&#xff09;等碾压⼈类。 但我们⽬前的AI&#xff0c;不管是AlphaGo还是图像识别算法&am…

研华I/O板卡 Win10+Qt+Cmake 开发环境搭建

文章目录 一.研华I/O板卡 Win10QtCmake 开发环境搭建 一.研华I/O板卡 Win10QtCmake 开发环境搭建 参考这个链接安装研华I/O板卡驱动程序系统环境变量添加研华板卡dll Qt新建一个c项目 cmakeList.txt中添加研华库文件 cmake_minimum_required(VERSION 3.5)project(advantechDA…

LeetCode(力扣)617. 合并二叉树Python

LeetCode617. 合并二叉树 题目链接代码 题目链接 https://leetcode.cn/problems/merge-two-binary-trees/ 代码 递归 # Definition for a binary tree node. # class TreeNode: # def __init__(self, val0, leftNone, rightNone): # self.val val # …

解决Three.js辉光背景不透明

使用此pass canvas元素的background都能看到 不过相应的辉光颜色和背景颜色不相容的地方看起来颜色会怪一些 如图 不过如果是纯色就没什么问题了 //ts-nocheck /** Author: hongbin* Date: 2023-04-06 11:44:14* LastEditors: hongbin* LastEditTime: 2023-04-06 11:49:23* De…

Node.js crypto模块 加密算法

背景 微信小程序调用飞蛾热敏纸打印机&#xff0c;需要进行参数sig签名校验&#xff0c;使用的是sha1进行加密 // 通过crypto.createHash()函数&#xff0c;创建一个hash实例&#xff0c;但是需要调用md5&#xff0c;sha1&#xff0c;sha256&#xff0c;sha512算法来实现实例的…

python-图片之乐-ASCII 文本图形

ASCII&#xff1a;一个简单的字符编码方案 pillow模块&#xff1a;读取图像&#xff0c;访问底层数据 numpy模块&#xff1a;计算平均值 import sys, random, argparse import numpy as np import math from PIL import Image定义灰度等级和网格 定义两种灰度等级作为全局值…

Git小白入门——了解分布式版本管理和安装

Git是什么&#xff1f; Git是目前世界上最先进的分布式版本控制系统&#xff08;没有之一&#xff09; 什么是版本控制系统&#xff1f; 程序员开发过程中&#xff0c;对于每次开发对各种文件的修改、增加、删除&#xff0c;达到预期阶段的一个快照就叫做一个版本。 如果有一…

EVO大赛是什么

价格是你所付出的东西&#xff0c;而价值是你得到的东西 EVO大赛是什么&#xff1f; “EVO”大赛全称“Evolution Championship Series”&#xff0c;是北美最高规格格斗游戏比赛&#xff0c;大赛正式更名后已经连续举办12年&#xff0c;是全世界最大规模的格斗游戏赛事。常见…

Python Qt学习(四)Radio Button

代码 # -*- coding: utf-8 -*-# Form implementation generated from reading ui file D:\Works\Python\Qt\qt_radiobutton.ui # # Created by: PyQt5 UI code generator 5.15.9 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again.…

2023年高教社杯 国赛数学建模思路 - 案例:异常检测

文章目录 赛题思路一、简介 -- 关于异常检测异常检测监督学习 二、异常检测算法2. 箱线图分析3. 基于距离/密度4. 基于划分思想 建模资料 赛题思路 &#xff08;赛题出来以后第一时间在CSDN分享&#xff09; https://blog.csdn.net/dc_sinor?typeblog 一、简介 – 关于异常…

(笔记四)利用opencv识别标记视频中的目标

预操作&#xff1a; 通过cv2将视频的某一帧图片转为HSV模式&#xff0c;并通过鼠标获取对应区域目标的HSV值&#xff0c;用于后续的目标识别阈值区间的选取 img cv.imread(r"D:\data\123.png") img cv.cvtColor(img, cv.COLOR_BGR2HSV) plt.figure(1), plt.imshow…