SpringMVC5

简介: SpringMVC5

5、使用ModelMap向request域对象共享数据

@RequestMapping("/testModelMap")
public string testModelMap(ModelMap modelMap){
  modelMap. addAttribute("testscope", "hello,ModelMap");  
  return "success";
}

演示

@RequestMapping ("/testModelMap")
    public String testModelMap(ModelMap modelMap){
        modelMap.addAttribute("testRequestScope", "hello,testModelMap");
        return "success";
    }



6、 Model、 ModelMap、Map的关系

Model、 ModelMap、Map类型的参数其实本质上都是BindingAwareModelMap类型的

public interface Model{}
public class ModelMap extends LinkedHashmap<String, Object> {}  
public class ExtendedModelMap extends ModelMap implements Model{}  
public class BindingAwareModelMap extends ExtendedModelMap {}

获取model、map、modelMap对象

20:50:12.880 [http-nio-8080-exec-69] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.atguigu.mvc.controller.ScopeController#testModel(Model)
{testRequestScope=hello,model}
20:50:14.991 [http-nio-8080-exec-68] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.atguigu.mvc.controller.ScopeController#testMap(Map)
{testRequestScope=hello,Map}
20:50:16.583 [http-nio-8080-exec-66] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.atguigu.mvc.controller.ScopeController#testModelMap(ModelMap)
{testRequestScope=hello,testModelMap}

获取model、map、modelMap对象的类名

20:55:45.625 [http-nio-8080-exec-79] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.atguigu.mvc.controller.ScopeController#testModel(Model)
org.springframework.validation.support.BindingAwareModelMap
20:55:48.532 [http-nio-8080-exec-73] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.atguigu.mvc.controller.ScopeController#testMap(Map)
org.springframework.validation.support.BindingAwareModelMap
20:55:49.933 [http-nio-8080-exec-74] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.atguigu.mvc.controller.ScopeController#testModelMap(ModelMap)
org.springframework.validation.support.BindingAwareModelMap







7、向session域共享数据

@RequestMapping("/testsession")
public String testSession(HttpSession session){
  session.setAttribute("testsessionScope", "hello,session");  
  return "success";
}

演示

@RequestMapping ("/testSession")
    public String testSession(HttpSession session){
        session.setAttribute("testSessionScope","hello,session");
        return "success";
    }
<p th:text="${session.testSessionScope}"></p>



8、向application域共享数据

@RequestMapping("/testApplication")
    public String testApplication(HttpSession session){
        ServletContext application = session.getServletContext();
        application.setAttribute("testApplicationScope", "hello,application");  
        return "success";
    }

演示

ScopeController

@RequestMapping("/testApplication")
    public String testApplication(HttpSession session){
        ServletContext application = session.getServletContext();
        application.setAttribute("testApplicationScope", "hello,application");
        return "success";
    }

success

<a th:href="@{/testApplication}">通过ServletAPI向Application域共享数据</a><br>

index

<p th:text="${application.testApplicationScope}"></p>



六、SpringMVC的视图

SpringMVC中的视图是View接口,视图的作用渲染数据,将模型Model中的数据展示给用户


SpringMVC视图的种类很多,默认有转发视图和重定向视图


当工程引入jstl的依赖,转发视图会自动转换为jstlView


若使用的视图技术为Thymeleaf,在SpringMVC的配置文件中配置了Thymeleaf的视图解析器,由此视图解析器解中析之后所得到的是ThymeleafView

1、 ThymeleafView

当控制器方法中所设置的视图名称没有任何前缀时,此时的视图名称会被SpringMVC配置文件中所配置的视图解析器解析,视图名称拼接视图前缀和视图后缀所得到的最终路径,会通过转发的方式实现跳转。
演示

ViewController

package com.atguigu.mvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ViewController {
    @RequestMapping("/testThymeleafView")
    public String testThymeleafView(){
        return "success";
    }
}

TestController

@RequestMapping("/test_view")
    public String testView(){
        return "test_view";
    }

templates下新建test_view.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a th:href="@{/testThymeleafView}">测试ThymeleafView</a><br>
</body>
</html>

index.html

<a th:href="@{/testApplication}">通过ServletAPI向Application域共享数据</a><br>






2、转发视图

SpringMVC中默认的转发视图是InternalResourceView

SpringMVC中创建转发视图的情况:
当控制器方法中所设置的视图名称以"forward:"为前缀时,创建InternalResourceView视图,此时的视图名称不会被SpringMVC配置文件中所配置的视图解析器解析,而是会将前缀"forward:"去掉,剩余部分作为最终路径通过转发的方式实现跳转


例如"forward:/",“folward:/employee”

演示

ViewController

 @RequestMapping("/testForward")
    public String testForward(){
        return "forward:/testThymeleafView";
    }

注意:只能转发到某一个请求中

test_view.html

<a th:href="@{/testForward}">测试InternalResourceView</a><br>



3、重定向视图

转发浏览器一次请求,地址栏不变,可以得到域对象,可以访问WEB-INF下的资源,不可以跨域

重定向两次请求,地址栏改变,不可以得到域对象,不可以访问WEB-INF下的资源,可以跨域
SpringMVC中默认的重定向视图是RedirectView


当控制器方法中所设置的视图名称以"redirect:"为前缀时,创建RedirectView视图,此时的视图名称不会被SpringMVC配置文件中所配置的视图解析器解析,而是会将前缀"redirect:"去掉,剩余部分作为最终路径通过重定向的方式实现跳转


例如"redirect:/"(重定向到首页),“redirect:/employee”

@RequestMapping("testRedirect")
    public String testRedirect(){
        return "redirect:/testThymeleafView";
    }

地址栏改变到http://localhost:8080/springMVC/testThymeleafView



4、视图控制器view-controller

当控制器方法中,仅仅用来实现页面跳转,即只需要设置视图名称时,可以将处理器方法使用view-controller标签 进行表示

<!--
path:设置处理的请求地址
view-name:设置请求地址所对应的视图名称
-->
<mvc:view-controller path="/testview" view-name="success"></mvc:view-controller>

注:

当SpringMVC中设置任何一个view-controller时,其他控制器中的请求映射将全部失效,此时需要在SpringMVC的核心配置文件中设置开启mvc注解驱动的标签:

<mvc:annotation-driven/>
演示

springMVC.xml

    <mvc:view-controller path="/" view-name="index"></mvc:view-controller>

注:报错不用管

代替

springMVC.xml

<!--    开启mvc的注解驱动-->
    <mvc:annotation-driven/>

使控制器中的请求映射重新实现效果

新建模块 springMVC_jsp


springMVC.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">
    <!--扫描组件    -->
    <context:component-scan base-package="com.atguigu.mvc.controller"></context:component-scan>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="WEB-INF/templates/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <mvc:view-controller path="/" view-name="index"></mvc:view-controller>
<!--    开启mvc的注解驱动-->
    <mvc:annotation-driven/>
</beans>

webapp下 新建index.jsp

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2021/11/19
  Time: 19:26
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>首页</h1>
</body>
</html>


templates/新建success.jsp

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2021/11/19
  Time: 19:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
成功
</body>
</html>

java\com.atguigu.mvc.controller\新建jspController

package com.atguigu.mvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class jspController {
    @RequestMapping("/success")
    public String success(){
        return "success";
    }
}

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2021/11/19
  Time: 19:26
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>首页</h1>
<a href="${pageContext.request.contextPath}/success">success.jsp</a>
</body>
</html>

七、RESTFul

1、RESTFul简介

REST: Representational State Transfer,表现层资源状态转移。

a>资源

资源是一种看待服务器的方式,即,将服务器看作是由很多离散的资源组成。每个资源是服务器上一个可命名的抽象概念。因为资源是一个抽象的概念,所以它不仅仅能代表服务器文件系统中的一个文件、数据库中的一张表等等具体的东西,可以将资源设计的要多抽象有多抽象,只要想象力允许而且客户端应用开发者能够理解。与面向对象设计类似,资源是以名词为核心来组织的,首先关注的是名词。一个资源可以由一个或多个URI来标识。URI既是资源的名称,也是资源在Web上的地址。对某个资源感兴趣的客户端应用,可以通过资源的URI与其进行交互。

b>资源的表述

资源的表述是一段对于资源在某个特定时刻的状态的描述。可以在客户端-服务器端之间转移(交换)。资源的表述可以有多种格式,例如HTML/XML/JSON/纯文本/图片/视频/音频等等。资源的表述格式可以通过协商机制来确定。请求-响应方向的表述通常使用不同的格式。

c>状态转移

状态转移说的是:在客户端和服务器端之间转移(transfer)代表资源状态的表述。通过转移和操作资源的表述, 来间接实现操作资源的目的。

2、RESTFul的实现

它们分别对应四种基本操作:GET用来获取资源,POST用来新建资源,PUT用来更新资源,DELETE用来删除资源。
REST风格提倡URL地址使用统一的风格设计,从前到后各个单词使用斜杠分开,不使用问号键值对方式携带请求参数,而是将要发送给服务器的数据作为URL地址的一部分,以保证整体风格的一致性。



3、

在demo3中

controller新建UserController

package com.atguigu.mvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class UserController {
    /**
     * 使用RESTFul模拟用户资源的增删改查
     * /user        GET     查询所有用户信息
     * /user/1      GET     根据用户id查询用户信息
     * /user        POST    添加用户信息
     * /user/1      DELETE  删除用户信息
     * /user        PUT     更新用户信息
     */
    @RequestMapping(value = "/user",method = RequestMethod.GET )
    public String getAllUsers(){
        System.out.println("查询所有用户信息");
        return "success";
    }
    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET )
    public String getUserById(){
        System.out.println("根据用户id用户信息");
        return "success";
    }
    @RequestMapping(value = "/user",method = RequestMethod.POST )
    public String insertUser(String username,String password){
        System.out.println("添加用户信息:"+username+","+password);
        return "success";
    }
}

test_rest.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a th:href="@{/user}">查询所有用户信息</a>
<a th:href="@{/user/1}">根据id查询用户信息</a>
<form th:action="@{/user}" method="post">
  用户名:<input type="text" name="username"><br>
  密码:<input type="password" name="password"><br>
  <input type="submit" value="添加"><br>
</form>
</body>
</html>

springMVC.xml

    <mvc:view-controller path="/test_rest" view-name="test_rest"></mvc:view-controller>



20:31:37.731 [http-nio-8080-exec-21] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.atguigu.mvc.controller.UserController#getAllUsers()
查询所有用户信息
20:31:37.996 [http-nio-8080-exec-21] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 200 OK
20:31:42.900 [http-nio-8080-exec-16] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/springMVC/user/1", parameters={}
20:31:42.901 [http-nio-8080-exec-16] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.atguigu.mvc.controller.UserController#getUserById()
根据用户id用户信息
20:31:42.903 [http-nio-8080-exec-16] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 200 OK
20:32:20.291 [http-nio-8080-exec-23] DEBUG org.springframework.web.servlet.DispatcherServlet - POST "/springMVC/user", parameters={masked}
20:32:20.291 [http-nio-8080-exec-23] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.atguigu.mvc.controller.UserController#insertUser(String, String)
添加用户信息:admin,1234567
20:32:20.404 [http-nio-8080-exec-23] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 200 OK

敬请期待

相关文章

相关文章
|
18天前
|
缓存 人工智能 前端开发
阿里云Qwen4-Max能力与活动:激活降至71B、单任务11.16元,Token省47.8%,Lite首月19.5元
Qwen4-Max 正式版已经发布‌,千问 AI 平台首发,API 按量计费与 Token Plan 同步开放;预览版标识 qwen4-max-preview 仅走订阅调用,窗口期至 11月25日24:00。架构维持总参数 2.4T、每 Token 激活降至 71B,支持 1M 上下文。Terminal-Bench 4.0 得分 48.5、Token 用量降约 47.8%,Work360 提升 10.4%,单任务平均费用由 26.58 元降至 11.16 元。API 输入 10 元、输出 30 元/百万 Token,缓存命中 0.5 元;Token Plan Lite 首月 19.50 元起。
|
15天前
|
人工智能 数据可视化 API
最新 AI 项目落地实操,阿里云百炼功能拆解,多模型对接方案、成本测算、API 接入教程
阿里云百炼大模型平台,把多厂商大模型统一封装,提供统一API接口、可视化RAG知识库、智能体编排、模型微调全套能力,开发者不用维护GPU算力,就可以快速搭建AI业务。计费模式丰富,新人免费额度、按量付费、节省计划、Token Plan、Coding Plan覆盖测试、正式业务、交互式工具不同场景。
244 0
|
缓存 负载均衡 网络协议
网络协议之:sctp流控制传输协议
要讲网络协议,肯定离不开OSI(Open System Interconnection)的七层模型。 我们一般关注的是网络层之上的几层,比如IPV4 IPV6所在的网络层,TCP UDP所在的传输层,HTTP FTP所在的应用层等。
网络协议之:sctp流控制传输协议
|
1月前
|
人工智能 弹性计算 关系型数据库
阿里云双十一正式开启了,今天第一天,优惠活动,史无前例,折上折了
2026阿里云双十一已开启!云服务器低至38元/年,支持续费同价至2029年;AI大模型4.5折起,Token补贴最高100万元;新用户享万元券、学生300元无门槛券及176款产品免费试用。轻量、ECS、GPU、数据库入口齐全,速抢!
248 0
|
3月前
|
运维 API C++
香港云服务器vs美国云服务器,2026跨境商用选型指南
本文以“用户地域分布”为核心,深度解析香港与美国云服务器选型逻辑:亚太用户首选香港(低延迟、双向稳定、免备案);欧美用户优选美国(本地极速、大带宽、高性价比);混合流量可按占比决策或双节点分流。避开常见误区,兼顾线路、带宽、IP、运维四大商用维度,助跨境业务精准匹配最优节点。
|
10月前
|
存储 弹性计算 网络协议
阿里云服务器ECS购买流程,一张图看懂,2026年最新版指南
2026最新阿里云ECS购买指南:一张图详解自定义购机全流程——涵盖付费类型(包年包月/按量/抢占式)、地域与可用区、实例规格族、操作系统镜像、系统盘/数据盘、公网带宽(固定/流量)、安全组、弹性网卡、IPv6及高级配置等,助您快速下单部署。
908 1
|
6月前
|
人工智能 消息中间件 存储
什么是 OPC—人公司?AI Agent 工作流实践:构建个人任务处理与交付复盘系统
OPC一人公司不是“单打独斗”,而是以1人为中枢,融合AI智能体、知识库、自动化工作流与协作网络,将多人协作的业务流程重构为可复用、可交付、可持续迭代的小型业务系统。(239字)
什么是 OPC—人公司?AI Agent 工作流实践:构建个人任务处理与交付复盘系统
|
7月前
|
人工智能 自然语言处理 安全
阿里云百炼Token Plan(团队版)怎么样?为企业解决了哪些AI订阅痛点?功能、优势与适用场景解析
阿里云百炼Token Plan(团队版)是面向企业团队推出的AI大模型订阅服务,以Credits统一计量,支持Qwen、GLM、Kimi等20+主流模型灵活切换,兼容Qoder、OpenClaw等主流AI编程与智能体工具。提供标准、高级、尊享三档坐席套餐及共享用量包,包月预算可控。内置团队管理后台,支持席位分配、用量分析与权限控制;通过统一接入解决企业多平台分散管理、成本不透明、安全失控等痛点,适合规模化AI开发与跨部门协作场景。
|
7月前
|
JSON 人工智能 文字识别
飞书/钉钉/企微集成型办公Agent:实现一句话触发报销审批
本文介绍如何用AI办公Agent重构报销流程:员工群内一句话发起报销,Agent自动解析、验票、校验预算并推送审批,全程≤15分钟。涵盖多平台接入、大模型结构化提取、发票真伪核验及人工兜底机制,让财务专注高价值工作。(239字)
946 2
|
8月前
|
人工智能 文字识别 JavaScript
小瓶RPA屏幕元素定位选择方法总结
小瓶RPA屏幕元素定位方法总结:离线4种(浏览器选择器🔍、图像识别🖼️、快捷键切换⌨️、OCR文字定位📝),高效稳定;在线1种(多模态AI大模型🤖,需Token)。按优先级排序,总有一款适配你的自动化场景!
579 1