SpringMVC基础

80 阅读4分钟

介绍

  • 针对WEB层
  • 基于MVC设计思想
    • Model -> 模型, Dao层和Service层处理后封装的数据
    • View -> 视图,用于渲染服务器数据的页面
    • Controller -> 控制器,用来接收参数,调用业务,响应数据的组件
  • 开源框架

划分

  • 前端控制器DispatcherServlet ---> SpringMVC提供,负责接收参数和返回页面或数据
  • 处理器 ---> 调用业务层代码

执行流程

springMVC.drawio.png

前端控制器

  • 相当于指挥部
  • 使用适配器调用处理器

代码

package com.itheima.controller;

import com.itheima.domain.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description: //TODO
 * @author: Lor
 * @date: 2024-01-25 10:09
 */
@RequestMapping("/user")
@RestController
public class UserController {

    @ResponseBody
    @RequestMapping("/demo1")
    public User demo1(String name, Integer age){
        return new User(name, age);
    }


   @RequestMapping("/demo2")
    public String demo2(String name, Integer age){
        System.out.println("name = " + name);
        System.out.println("age = " + age);
        return "success";
    }

    @RequestMapping("/demo3")
    public String demo3(User user){
        System.out.println("user = " + user);
        return "success";
    }
}

处理器 ---> 前端控制器中的方法

配置类

SpringMvcConfig

  • 配置 Spring MVC 的一部分,包括组件扫描、开启 WEB 环境等。
package com.itheima.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author Lor
 * @version 1.0.1
 * @date 2024-01-25 09:54:19
 */
@Configuration
@ComponentScan("com.itheima")
@EnableWebMvc    //开启WEB环境
public class SpringMvcConfig implements WebMvcConfigurer {}

WebInitConfig

  • 配置和初始化一个基于 Spring MVC 的 Web 应用程序
package com.itheima.config;

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

import javax.servlet.Filter;

/**
 * @author Lor
 * @version 1.0.1
 * @date 2024-01-25 09:50:11
 */
//@Configuration
public class WebInitConfig extends AbstractDispatcherServletInitializer {
    //创建SpringMVC容器
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext springmvcIoc = new AnnotationConfigWebApplicationContext();
        springmvcIoc.register(SpringMvcConfig.class);
        return springmvcIoc;
    }

    //表示前端控制器拦截的请求路径规则
    @Override
    protected String[] getServletMappings() {
        //  / 表示拦截所有,除JSP之外资源
        return new String[]{"/"};
    }

    //创建Spring容器
    @Override
    protected WebApplicationContext createRootApplicationContext() {
        AnnotationConfigWebApplicationContext springIoc = new AnnotationConfigWebApplicationContext();
        return springIoc;
    }

	// 解决中文字符乱码问题
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        filter.setForceEncoding(true);
        return new Filter[]{filter};
    }
}

注解

@RequestMapping

建立请求URL和处理器之间的映射关系

标记位置

  • 类 -> 抽取公共的url
    • 如果类上标记了 请求URL为 类+ 方法结合
  • 方法 -> 表明当前方法是一个处理器方法,处理请求

常用属性

value/ path: 数组, 请求URL的路径, 可以接收多个
method: 数组,请求方法

@ResponseBody

将方法返回值响应给浏览器,如果返回值是对象,将会转换为JSON格式

标记位置

  • 类 -> 所有的方法都标记了@ResponseBody
  • 方法

注解简化

@Controller + @ResponseBody = @RestController

接收请求参数

简单类型

  • 基本数据类型 + 对应的包装类 + String
  • 请求参数名称 和处理器形参名称一致
//请求:http://localhost:8080/springmvc_01_war/user/demo1?name=cq&age=1
   
   @RequestMapping("/demo2")
    public String demo2(String name, Integer age){
        System.out.println("name = " + name);
        System.out.println("age = " + age);
        return "success";
    }

对象

  • 请求参数名称和实体对象的属性名一致
// 请求:http://localhost:8080/springmvc_01_war/user/demo3?name=cq&age=1

    @RequestMapping("/demo3")
    public String demo3(User user){
        System.out.println("user = " + user);
        return "success";
    }

数组

  • 请求参数名称和处理器数组形参名称一致
// 请求:http://localhost:8080/springmvc_01_war/user/demo4?hobby=blender&hobby=cpp&hobby=python
    @RequestMapping("/demo4")
    public String demo4(String[] hobby){
        if (Objects.nonNull(hobby) && hobby.length >= 1)
            System.out.println(Arrays.asList(hobby));
        return "success";
    }
    // 如果参数类型为String,返回结果为“blender,cpp,python”

集合

  • 请求参数名称和处理器形参名称一致
  • 类型是集合
//请求:http://localhost:8080/springmvc_01_war/user/demo5?hobby=blender&hobby=cpp&hobby=python&num=2
    @RequestMapping("/demo5")
    public String demo5(@RequestParam(name = "hobby") List<String> hobbies, @RequestParam(name = "num" ,required = false, defaultValue = "1") Integer number){
        System.out.println("hobby = " + hobbies);
        System.out.println(number);
        return "success";
    }

日期类型

  • 请求参数与处理器参数一致
  • @DateTimeFormatter(pattern = "时间格式") 指定对应的时间格式
// 请求:http://localhost:8080/springmvc_01_war/user/demo6?time=2024-01-25
    @RequestMapping("/demo6")
    public String demo6(@DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate time){
        System.out.println(time);
        return "success";
    }

JSON

  • 请求参数与处理器参数一致
  • 使用@RequestBody标记
// 请求:http://localhost:8080/springmvc_01_war/user/demo7
    @RequestMapping("/demo7")
    public String demo7(@RequestBody User user){
        System.out.println(user);
        return "success";
    }

路径参数

  • 处理器URL使用 {参数名} 来接收,
  • @PathVariable(name="参数名") 来标记形参
// 请求:http://localhost:8080/springmvc_01_war/user/demo8/23
    @RequestMapping("/demo8/{id}")
    public String demo8(@PathVariable(name = "id") Integer id){
        System.out.println("id = " + id);
        return "success";
    }

@RequestParam 注解

请求参数名称和处理器形参名称不同

  • name/value 指定请求参数的名称
  • required 参数是否必须,默认为true
  • default 默认值