第一章 初始 Spring MVC

2024-06-22 02:44
文章标签 spring mvc 第一章 初始 java

本文主要是介绍第一章 初始 Spring MVC,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 

目录

1.2 SpringMVC处理请求原理简图

第二章 SpringMVC搭建框架

2.1 pom.xml

2.2 web.xml

2.3 springmvc.xml

2.4 HelloController

第三章 @RequestMapping详解

3.1 @RequestMapping注解位置

3.2 @RequestMapping注解属性

3.3 @RequestMapping支持Ant 风格的路径(了解)

常用通配符

第四章 @PathVariable 注解

4.1 @PathVariable注解位置

4.2 @PathVariable注解作用

4.3 @PathVariable注解属性

第五章 REST【RESTful】风格CRUD

5.1 REST的CRUD与传统风格CRUD对比

5.2 REST风格CRUD优势

5.3 实现PUT&DELETE提交方式步骤

5.4 源码解析HiddenHttpMethodFilter

第六章 SpringMVC处理请求数据

6.1 处理请求参数

6.2 处理请头

6.3 处理Cookie信息

6.4 使用原生Servlet-API


 


1.1 SpringMVC概述

  • SpringMVC是Spring子框架

  • SpringMVC是Spring 为【展现层|表示层|表述层|控制层】提供的基于 MVC 设计理念的优秀的 Web 框架,是目前最主流的MVC 框架。

  • SpringMVC是非侵入式:可以使用注解让普通java对象,作为请求处理器【Controller】

  • SpringMVC是用来代替Servlet

    Servlet作用

    1. 处理请求

      1. 跳转页面

1.2 SpringMVC处理请求原理简图
  • 请求

  • DispatcherServlet【前端控制器】

    • 将请求交给Controller|Handler

  • Controller|Handler【请求处理器】

    • 处理请求

    • 返回数据模型

  • ModelAndView

    • Model:数据模型

    • View:视图对象或视图名

  • DispatcherServlet渲染视图

    • 将数据共享到域中

    • 跳转页面【视图】

  • 响应

第二章 SpringMVC搭建框架

2.1 pom.xml
  • 创建工程【web工程】

  • 导入jar包

 <!--spring-webmvc-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.1</version>
    </dependency>

    <!-- 导入thymeleaf与spring5的整合包 -->
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
        <version>3.0.12.RELEASE</version>
    </dependency>

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

2.2 web.xml

注册DispatcherServlet

  • url配置:/

  • init-param:contextConfigLocation,设置springmvc.xml配置文件路径【管理容器对象】

  • <load-on-startup>:设置DispatcherServlet优先级【启动服务器时,创建当前Servlet对象】

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

2.3 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:util="http://www.springframework.org/schema/util"
       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
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
    <context:component-scan base-package="com.haogu"/>
    
</beans>

2.4 HelloController

@Controller
public class HelloController {

    @ResponseBody
    @GetMapping("1.do")
    public String hello(){
        return "hello";
    }
}



第三章 @RequestMapping详解

@RequestMapping注解作用:为指定的类或方法设置相应URL

3.1 @RequestMapping注解位置
  • 书写在类上面

    • 作用:为当前类设置映射URL

    • 注意:不能单独使用,需要与方法上的@RequestMapping配合使用

  • 书写在方法上面

    • 作用:为当前方法设置映射URL

    • 注意:可以单独使用

3.2 @RequestMapping注解属性
  • value属性

    • 类型:String[]

    • 作用:设置URL信息

  • path属性

    • 类型:String[]

    • 作用:与value属性作用一致

  • method属性

    • 类型:RequestMethod[]

public enum RequestMethod {
GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE

    • 作用:为当前URL【类或方法】设置请求方式【POST、DELETE、PUT、GET】

    • 注意:

      • 默认情况:所有请求方式均支持

      • 如请求方式不支持,会报如下错误

        • 405【Request method 'GET' not supported】

  • params

    • 类型:String[]

    • 作用:为当前URL设置请求参数

    • 注意:如设置指定请求参数,但URL中未携带指定参数,会报如下错误

      • 400【Parameter conditions "lastName" not met for actual request parameters:】

  • headers

    • 类型:String[]

    • 作用:为当前URL设置请求头信息

    • 注意:如设置指定请求头,但URL中未携带请求头,会报如下错误

      • 404:请求资源未找到

@RequestMapping(value = {"/saveEmp","/insertEmp"},
                method = RequestMethod.GET,
                params = "lastName=lisi",
                headers = "User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36")
public String saveEmp(){
    System.out.println("添加员工信息!!!!");

    return "hello";
}



 @RequestMapping(method = RequestMethod.POST)
public @interface PostMapping {}
@RequestMapping(method = RequestMethod.GET)
public @interface GetMapping {}
@RequestMapping(method = RequestMethod.PUT)
public @interface PutMapping {}
@RequestMapping(method = RequestMethod.DELETE)
public @interface DeleteMapping {}

3.3 @RequestMapping支持Ant 风格的路径(了解)
  • 常用通配符

    a) ?:匹配一个字符

    b) *:匹配任意字符

    c) **:匹配多层路径

  • 示例代码

@RequestMapping("/testAnt/**")
public String testAnt(){
    System.out.println("==>testAnt!!!");
    return "SUCCESS";
}

第四章 @PathVariable 注解

4.1 @PathVariable注解位置

@Target(ElementType.PARAMETER)

  • 书写在参数前面

4.2 @PathVariable注解作用
  • 获取URL中占位符参数

  • 占位符语法:{}

  • 示例代码

@GetMapping("1.do/{uid}")
    public String hello(@PathVariable String uid){
      System.out.println(uid);
        return "hello";
    } 

4.3 @PathVariable注解属性
  • value属性

    • 类型:String

    • 作用:设置占位符中的参数名

  • name属性

    • 类型:String

    • 作用:与name属性的作用一致

  • required属性

    • 类型:boolean

    • 作用:设置当前参数是否必须入参【默认值:true】

      • true:表示当前参数必须入参,如未入参会报如下错误

        • Missing URI template variable 'empId' for method parameter of type Integer

      • false:表示当前参数不必须入参,如未入参,会装配null值

第五章 REST【RESTful】风格CRUD

5.1 REST的CRUD与传统风格CRUD对比
  • 传统风格CRUD

    • 功能 URL 请求方式 增 /insertEmp POST

    • 删 /deleteEmp?empId=1001 GET

    • 改 /updateEmp POST

    • 查 /selectEmp?empId=1001 GET

  • REST风格CRUD

    • 功能 URL 请求方式 增 /emp POST

    • 删 /emp/1001 DELETE

    • 改 /emp PUT

    • 查 /emp/1001 GET

5.2 REST风格CRUD优势
  • 提高网站排名

    • 排名方式

      • 竞价排名

      • 技术排名

  • 便于第三方平台对接

5.3 实现PUT&DELETE提交方式步骤
  • 注册过滤器HiddenHttpMethodFilter

  • 设置表单的提交方式为POST

  • 设置参数:_method=PUT或_method=DELETE

5.4 源码解析HiddenHttpMethodFilter

public static final String DEFAULT_METHOD_PARAM = "_method";

private String methodParam = DEFAULT_METHOD_PARAM;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {

   HttpServletRequest requestToUse = request;

   if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
      String paramValue = request.getParameter(this.methodParam);
      if (StringUtils.hasLength(paramValue)) {
         String method = paramValue.toUpperCase(Locale.ENGLISH);
         if (ALLOWED_METHODS.contains(method)) {
            requestToUse = new HttpMethodRequestWrapper(request, method);
         }
      }
   }

   filterChain.doFilter(requestToUse, response);
}
/**
     * Simple {@link HttpServletRequest} wrapper that returns the supplied method for
     * {@link HttpServletRequest#getMethod()}.
     */
    private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {

        private final String method;

        public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
            super(request);
            this.method = method;
        }

        @Override
        public String getMethod() {
            return this.method;
        }
    }

第六章 SpringMVC处理请求数据

使用Servlet处理请求数据

  1. 请求参数

    • String param = request.getParameter();

  2. 请求头

    • request.getHeader();

  3. Cookie

    • request.getCookies();

6.1 处理请求参数
  • 默认情况:可以将请求参数名,与入参参数名一致的参数,自动入参【自动类型转换】

  • SpringMVC支持POJO入参

    • 要求:请求参数名与POJO的属性名保持一致

    • 示例代码

<form action="/saveEmp" method="POST">
    id:<input type="text" name="id"><br>
    LastName:<input type="text" name="lastName"><br>
    Email:<input type="text" name="email"><br>
    Salary:<input type="text" name="salary"><br>
    <input type="submit" value="添加员工信息">
</form> 

@RequestParam注解

  • 作用:如请求参数与入参参数名不一致时,可以使用@RequestParam注解设置入参参数名

  • 属性

    • value

      • 类型:String

      • 作用:设置需要入参的参数名

    • name

      • 类型:String

      • 作用:与value属性作用一致

    • required

      • 类型:Boolean

      • 作用:设置当前参数,是否必须入参

        • true【默认值】:表示当前参数必须入参,如未入参会报如下错误

          • 400【Required String parameter 'sName' is not present】

        • false:表示当前参数不必须入参,如未入参,装配null值

    • defaultValue

      • 类型:String

      • 作用:当装配数值为null时,指定当前defaultValue默认值

  • 示例代码

/**
 * 获取请求参数
 * @return
 */
@RequestMapping("/requestParam1")
public String requestParam1(@RequestParam(value = "sName",required = false,
                                        defaultValue = "zhangsan")
                                        String stuName,
                            Integer stuAge){
    System.out.println("stuName = " + stuName);
    System.out.println("stuAge = " + stuAge);
    return SUCCESS;
}

6.2 处理请头
  • 语法:@RequestHeader注解

  • 属性

    • value

      • 类型:String

      • 作用:设置需要获取请求头名称

    • name

      • 类型:String

      • 作用:与value属性作用一致

    • required

      • 类型:boolean

      • 作用:【默认值true】

        • true:设置当前请求头是否为必须入参,如未入参会报如下错误

          • 400【Required String parameter 'sName' is not present】

        • false:表示当前参数不必须入参,如未入参,装配null值

    • defaultValue

      • 类型:String

      • 作用:当装配数值为null时,指定当前defaultValue默认值

  • 示例代码

<a th:href="@{/testGetHeader}">测试获取请求头</a> 

 /**
 * 获取请求头
 * @return
 */
@RequestMapping(value = "/testGetHeader")
public String testGetHeader(@RequestHeader("Accept-Language")String al,
                            @RequestHeader("Referer") String ref){
    System.out.println("al = " + al);
    System.out.println("ref = " + ref);
    return SUCCESS;
}

6.3 处理Cookie信息
  • 语法:@CookieValue获取Cookie数值

  • 属性

    • value

      • 类型:String

      • 作用:设置需要获取Cookie名称

    • name

      • 类型:String

      • 作用:与value属性作用一致

    • required

      • 类型:boolean

      • 作用:【默认值true】

        • true:设置当前Cookie是否为必须入参,如未入参会报如下错误

          • 400【Required String parameter 'sName' is not present】

        • false:表示当前Cookie不必须入参,如未入参,装配null值

    • defaultValue

      • 类型:String

      • 作用:当装配数值为null时,指定当前defaultValue默认值

  • 示例代码

/**
     * 设置Cookie
     * @return
   */
    @RequestMapping("/setCookie")
    public String setCookie(HttpSession session){
//        Cookie cookie = new Cookie();
        System.out.println("session.getId() = " + session.getId());
        return SUCCESS;
    }

    /**
     * 获取Cookie
     * @return
     */
    @RequestMapping("/getCookie")
    public String getCookie(@CookieValue("JSESSIONID")String cookieValue){
        System.out.println("cookieValue = " + cookieValue);
        return SUCCESS;
    }



6.4 使用原生Servlet-API
  • 将原生Servlet相关对象,入参即可

@RequestMapping("/useRequestObject")
public String useRequestObject(HttpServletRequest request){} 

这篇关于第一章 初始 Spring MVC的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1083062

相关文章

Java五子棋之坐标校正

上篇针对了Java项目中的解构思维,在这篇内容中我们不妨从整体项目中拆解拿出一个非常重要的五子棋逻辑实现:坐标校正,我们如何使漫无目的鼠标点击变得有序化和可控化呢? 目录 一、从鼠标监听到获取坐标 1.MouseListener和MouseAdapter 2.mousePressed方法 二、坐标校正的具体实现方法 1.关于fillOval方法 2.坐标获取 3.坐标转换 4.坐

Spring Cloud:构建分布式系统的利器

引言 在当今的云计算和微服务架构时代,构建高效、可靠的分布式系统成为软件开发的重要任务。Spring Cloud 提供了一套完整的解决方案,帮助开发者快速构建分布式系统中的一些常见模式(例如配置管理、服务发现、断路器等)。本文将探讨 Spring Cloud 的定义、核心组件、应用场景以及未来的发展趋势。 什么是 Spring Cloud Spring Cloud 是一个基于 Spring

Javascript高级程序设计(第四版)--学习记录之变量、内存

原始值与引用值 原始值:简单的数据即基础数据类型,按值访问。 引用值:由多个值构成的对象即复杂数据类型,按引用访问。 动态属性 对于引用值而言,可以随时添加、修改和删除其属性和方法。 let person = new Object();person.name = 'Jason';person.age = 42;console.log(person.name,person.age);//'J

java8的新特性之一(Java Lambda表达式)

1:Java8的新特性 Lambda 表达式: 允许以更简洁的方式表示匿名函数(或称为闭包)。可以将Lambda表达式作为参数传递给方法或赋值给函数式接口类型的变量。 Stream API: 提供了一种处理集合数据的流式处理方式,支持函数式编程风格。 允许以声明性方式处理数据集合(如List、Set等)。提供了一系列操作,如map、filter、reduce等,以支持复杂的查询和转

Java面试八股之怎么通过Java程序判断JVM是32位还是64位

怎么通过Java程序判断JVM是32位还是64位 可以通过Java程序内部检查系统属性来判断当前运行的JVM是32位还是64位。以下是一个简单的方法: public class JvmBitCheck {public static void main(String[] args) {String arch = System.getProperty("os.arch");String dataM

详细分析Springmvc中的@ModelAttribute基本知识(附Demo)

目录 前言1. 注解用法1.1 方法参数1.2 方法1.3 类 2. 注解场景2.1 表单参数2.2 AJAX请求2.3 文件上传 3. 实战4. 总结 前言 将请求参数绑定到模型对象上,或者在请求处理之前添加模型属性 可以在方法参数、方法或者类上使用 一般适用这几种场景: 表单处理:通过 @ModelAttribute 将表单数据绑定到模型对象上预处理逻辑:在请求处理之前

eclipse运行springboot项目,找不到主类

解决办法尝试了很多种,下载sts压缩包行不通。最后解决办法如图: help--->Eclipse Marketplace--->Popular--->找到Spring Tools 3---->Installed。

JAVA读取MongoDB中的二进制图片并显示在页面上

1:Jsp页面: <td><img src="${ctx}/mongoImg/show"></td> 2:xml配置: <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001

Java面试题:通过实例说明内连接、左外连接和右外连接的区别

在 SQL 中,连接(JOIN)用于在多个表之间组合行。最常用的连接类型是内连接(INNER JOIN)、左外连接(LEFT OUTER JOIN)和右外连接(RIGHT OUTER JOIN)。它们的主要区别在于它们如何处理表之间的匹配和不匹配行。下面是每种连接的详细说明和示例。 表示例 假设有两个表:Customers 和 Orders。 Customers CustomerIDCus

22.手绘Spring DI运行时序图

1.依赖注入发生的时间 当Spring loC容器完成了 Bean定义资源的定位、载入和解析注册以后,loC容器中已经管理类Bean 定义的相关数据,但是此时loC容器还没有对所管理的Bean进行依赖注入,依赖注入在以下两种情况 发生: 、用户第一次调用getBean()方法时,loC容器触发依赖注入。 、当用户在配置文件中将<bean>元素配置了 lazy-init二false属性,即让