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

敬请期待

相关文章

相关文章
|
网络协议
【开源视频联动物联网平台】J2mod库对指令码的定义
【开源视频联动物联网平台】J2mod库对指令码的定义
287 1
|
开发工具 图形学 git
Unity 之 加载工程卡在音频处不动(Unity识别不出音频文件)
在Git上克隆同事上传的工程,打开是卡在音频处不动解决方案分享。
883 0
Unity 之 加载工程卡在音频处不动(Unity识别不出音频文件)
|
6月前
|
存储 物联网 数据处理
什么数据中心最好?盘点全球十大数据中心!
在数字时代,数据中心作为关键基础设施,支撑着商业和社会的高效运转。从AWS、谷歌、微软到阿里云、苹果等巨头的数据中心,它们各具特色,涵盖高性能计算、液冷技术、绿色节能和高安全性等领域。这些“超级堡垒”不仅保障了在线交易、远程教育、智慧医疗等服务的稳定运行,还推动了云计算、大数据和物联网的发展,极大提升了社会效率和生活质量。每个数据中心根据自身优势,在不同应用场景中发挥着不可替代的作用,共同构建了数字化世界的基石。
490 1
|
存储 关系型数据库 MySQL
MySQL周内训参照1、ER实体关系图与数据库模型图绘制
MySQL周内训参照1、ER实体关系图与数据库模型图绘制
339 1
|
10月前
|
存储 监控 安全
智慧社区可视化解决方案:科技引领社区服务与管理新篇章
智慧社区通过现代科技整合区域资源,提升治理和服务水平,为居民提供便捷、高效、安全的生活环境。其特点包括科技赋能、资源整合和以人为本,旨在实现社区现代化管理,提高居民满意度。未来将应用更多创新技术,推动社区治理现代化。
361 16
|
10月前
|
人工智能 搜索推荐 安全
人工智能在医疗领域的最新进展与未来趋势
人工智能在医疗领域的最新进展与未来趋势
|
10月前
|
监控 安全 自动驾驶
|
11月前
|
消息中间件 存储 Java
一览纵山小,原来RocketMQ是这样工作的!
本文介绍了阿里巴巴开源的高性能分布式消息队列系统RocketMQ的核心组件及其作用。RocketMQ拥有四个关键组件:NameServer、Broker、Producer和Consumer。NameServer作为注册中心维护路由信息;Broker负责消息的接收、存储和转发;Producer生成消息并通过Topic与Broker关联;Consumer则订阅并处理消息。文章详细解析了各组件的功能及交互逻辑,并展示了RocketMQ在异步通信、日志收集、流处理及事件驱动架构中的典型应用场景。通过整体框架的梳理,有助于读者更好地理解和掌握RocketMQ的工作机制。
158 4
|
弹性计算 前端开发 Java
使用阿里云 mqtt serverless 版本超低成本快速实现 webscoket 长链接服务器
使用阿里云 MQTT Serverless 可轻松实现弹性伸缩的 WebSocket 服务,每日成本低至几元。适用于小程序消息推送的 MQTT P2P 模式。前端需注意安全,避免 AK 泄露,采用一机一密方案。后端通过调用 `RegisterDeviceCredential` API 发送消息。示例代码包括 JavaScript 前端连接和 Java 后端发送。
687 0
|
测试技术 Apache
HTTP 压力测试工具-http_load使用分享
http_load以并行复用的方式运行,用以测试web服务器的吞吐量与负载。 但是它不同于大多数压力测试工具,它可以以一个单一的进程运行,一般不会把客户机搞死。 还可以测试HTTPS类的网站请求。
758 0