4.Spring MVC入门

文章目录

  • [1. HTTP协议](#1. HTTP协议)
  • [2. Spring MVC](#2. Spring MVC)
    • [2.1. 三层架构](#2.1. 三层架构)
    • [2.2. MVC(解决表现层的问题)](#2.2. MVC(解决表现层的问题))
    • [2.3. 核心组件](#2.3. 核心组件)
  • [3. Thymeleaf](#3. Thymeleaf)
    • [3.1. 模板引擎](#3.1. 模板引擎)
    • [3.2. Thymeleaf](#3.2. Thymeleaf)
    • [3.3. 常用语法](#3.3. 常用语法)
  • 代码

1. HTTP协议

网址:https://www.ietf.org/ (官网网址)
https://developer.mozilla.org/zh-CN/ (易于理解)

HyperText Transfer Potocal

用于传输HTML等内容的应用层协议

规定了浏览器和服务器之间如何通信,以及通信时的数据格式


2. Spring MVC

2.1. 三层架构

表现层、业务层、数据访问层

2.2. MVC(解决表现层的问题)

Model: 模型层

View: 视图层

Controller:控制层

2.3. 核心组件

前端控制器:DispatcherServlet

3. Thymeleaf

网址:http://thymeleaf.org/

3.1. 模板引擎

生成动态的HTML

3.2. Thymeleaf

倡导自然模板,即以HTML文件为模板

3.3. 常用语法

标准表达式、判断与循环、模板的布局

代码

java 复制代码
package com.test.community.controller;

import com.test.community.service.AlphaService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * @ClassName AlphaController
 * @Description TODO
 * @Author lcx
 * @Date 2024/2/21 15:22
 * @Version 1.0
 */
@Controller
@RequestMapping("/alpha")
public class AlphaController {

    @Autowired
    private AlphaService alphaService;

    @RequestMapping("/hello")
    @ResponseBody
    public String sayHello() {
        return "Hello Spring Boot!";
    }

    @RequestMapping("/data")
    @ResponseBody
    public String getData() {
        return alphaService.find();
    }

    // SpringMVC获得请求对象和响应对象
    @RequestMapping("/http")
    public void http(HttpServletRequest request, HttpServletResponse response) {
        // 获取请求数据
        System.out.println(request.getMethod());
        System.out.println(request.getServletPath());
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            System.out.println(name + ":" + value);
        }

        // 请求体
        System.out.println(request.getParameter("code"));

        // 返回响应数据
        response.setContentType("text/html; charset=utf-8");
        try(
                PrintWriter writer = response.getWriter();
        ) {
            writer.write("<h1>牛客网</h1>");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    // GET请求
    // 查询所有学生  /students?current=1&limit=20
    @RequestMapping(path = "/students", method = RequestMethod.GET)
    @ResponseBody
    public String getStudents(
            @RequestParam(name = "current", required = false, defaultValue = "1") int current,
            @RequestParam(name = "limit", required = false, defaultValue = "10") int limit) {

        System.out.println(current);
        System.out.println(limit);
        return "some students";
    }

    // /student/123
    @RequestMapping(path = "/student/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getStudent(@PathVariable("id") int id) {
        System.out.println(id);
        return "a student";
    }

    // 浏览器向服务器提交数据
    // POST请求
    @RequestMapping(path = "/student", method = RequestMethod.POST)
    @ResponseBody
    public String saveStudent(String name, int age) {
        System.out.println(name);
        System.out.println(age);
        return "success";
    }

    // 响应HTML数据
    @RequestMapping(path = "/teacher", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView getTeacher() {
        ModelAndView mav = new ModelAndView();
        mav.addObject("name", "张三");
        mav.addObject("age", 12);
        mav.setViewName("/demo/view");
        return mav;
    }

    @RequestMapping(path = "/school", method = RequestMethod.GET)
    public String getSchool(Model model) {
        model.addAttribute("name", "北京大学");
        model.addAttribute("age", 123);
        return "/demo/view";
    }

    // 异步请求中响应JSON数据
    // java对象 -> JSON字符串 -> JS对象
    @RequestMapping(path = "/emp", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getEmp() {
        Map<String, Object> emp = new HashMap<>();
        emp.put("name", "张三");
        emp.put("age", 12);
        emp.put("salary", 8000.00);
        return emp;
    }

    @RequestMapping(path = "/emps", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> getEmps() {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> emp = new HashMap<>();
        emp.put("name", "张三");
        emp.put("age", 12);
        emp.put("salary", 8000.00);
        list.add(emp);
        emp = new HashMap<>();
        emp.put("name", "李四");
        emp.put("age", 22);
        emp.put("salary", 9000.00);
        list.add(emp);
        emp = new HashMap<>();
        emp.put("name", "王五");
        emp.put("age", 32);
        emp.put("salary", 10000.00);
        list.add(emp);
        return list;
    }



}

相关推荐
mygljx3 分钟前
Spring Boot从0到1 -day02
java·spring boot·后端
程序员小郭836 分钟前
Spring Ai 04 解决 ChatClient 初始化冲突问题
java·后端·spring
y = xⁿ8 分钟前
【LeetCodehot100】T114:二叉树展开为链表 T105:从前序与中序遍历构造二叉树
java·算法·链表
SuniaWang9 分钟前
《Spring AI + 大模型全栈实战》学习手册系列 · 专题八:《RAG 系统安全与权限管理:企业级数据保护方案》
java·前端·人工智能·spring boot·后端·spring·架构
xiaohe0735 分钟前
Maven Spring框架依赖包
java·spring·maven
hssfscv1 小时前
软件设计师下午题二 E-R图
java·笔记·学习
十七号程序猿1 小时前
Java图书管理系统 | 无需配置任何环境,双击一键启动,开箱即用
java·spring boot·vue·毕业设计·毕设·源代码管理
宝耶1 小时前
Java面试2:final、finally、finalize 的区别?
java·开发语言·面试
umeelove351 小时前
Spring boot整合quartz方法
java·前端·spring boot
yige451 小时前
SpringBoot 集成 Activiti 7 工作流引擎
java·spring boot·后端