SpringMVC——数据传递的多种方式

本文详细介绍SpringMVC的多种传值方法,像URL路径、参数、表单、Session这些常见方式,以及字符串、JSON、Cookie 和 Header 传递等方法。

本文目录

    • [1. 通过URL路径传值](#1. 通过URL路径传值)
    • [2. 通过URL参数传值](#2. 通过URL参数传值)
    • [3. 通过表单传值](#3. 通过表单传值)
    • [4. 通过Session传值](#4. 通过Session传值)
    • [5. 通过 Cookie 传递](#5. 通过 Cookie 传递)
    • [6. JSON 传递](#6. JSON 传递)

1. 通过URL路径传值

这种方式是将参数直接放在 URL 的路径中,SpringMVC 可以通过 @PathVariable 注解来获取这些参数。

java 复制代码
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class PathVariableController {

    @RequestMapping("/user/{id}")
    @ResponseBody
    public String getUserById(@PathVariable("id") int id) {
        return "UserID: " + id;
    }
}

@PathVariable 注解用于绑定 URL 路径中的变量 id,并将其作为方法的参数传入。当访问 /user/1 时,id 的值就是 1。

2. 通过URL参数传值

这是最常见的传值方式,将参数以 key = value 的形式附加在URL后面,多个参数之间用 & 分隔。SpringMVC 可以通过 @RequestParam 注解来获取这些参数。

java 复制代码
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class RequestParamController {

    @RequestMapping("/search")
    @ResponseBody
    public String search(@RequestParam("keyword") String keyword) {
        return "keyword: " + keyword;
    }
}

@RequestParam 注解用于绑定UR 参数 keyword,并将其作为方法的参数传入。当访问 /search?keyword=java 时,keyword 的值就是 java。

3. 通过表单传值

在 HTML 表单中填写数据,提交表单时,表单数据会被发送到服务器。SpringMVC可以通过 @ModelAttribute 注解将表单数据绑定到一个Java对象上。

java 复制代码
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

class User {
    private String name;
    private int age;

    // Getters and Setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

@Controller
public class ModelAttributeController {

    @RequestMapping("/register")
    @ResponseBody
    public String register(@ModelAttribute User user) {
        return "name: " + user.getName() + ", age: " + user.getAge();
    }
}

@ModelAttribute 注解将表单数据绑定到 User 对象上。表单中的 name 和 age 字段会自动映射到 User 对象的相应属性上。

4. 通过Session传值

通过 HttpSession 对象来实现数据在不同请求之间的传递。

java 复制代码
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class SessionController {

    @RequestMapping("/setSession")
    @ResponseBody
    public String setSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("message", "Hello, Session!");
        return "Session attribute set.";
    }

    @RequestMapping("/getSession")
    @ResponseBody
    public String getSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String message = (String) session.getAttribute("message");
        return "value: " + message;
    }
}

setSession 方法将一个字符串存储到 HttpSession 中,getSession 方法从 HttpSession 中获取该字符串。

可以在请求和响应中使用 Cookie 来传递数据。在 SpringMVC 中,可以使用 @CookieValue 注解获取请求中的 Cookie 值,也可以通过 HttpServletResponse 设置响应的 Cookie。

java 复制代码
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Controller
public class CookieController {

    @RequestMapping("/setCookie")
    @ResponseBody
    public String setCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie("userName", "John");
        cookie.setPath("/");
        response.addCookie(cookie);
        return "Cookie set.";
    }

    @RequestMapping("/getCookie")
    @ResponseBody
    public String getCookie(@CookieValue(value = "userName", defaultValue = "Unknown") String userName) {
        return "value: " + userName;
    }
}

6. JSON 传递

使用@RequestBody 注解,能接收JSON数据并将其转换为Java对象。

java 复制代码
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

class UserInfo {
    private String username;
    private int userAge;

    // Getters and Setters
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getUserAge() {
        return userAge;
    }

    public void setUserAge(int userAge) {
        this.userAge = userAge;
    }
}

@Controller
public class JsonPassingController {
    @RequestMapping(value = "/jsonPass", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String handleJson(@RequestBody UserInfo user) {
        return "user: " + user.getUsername() + ", age: " + user.getUserAge();
    }
}

使用 @RequestBody 注解把接收到的 JSON 数据映射到 UserInfo 对象,发送的 JSON 数据格式如 {"username": "John", "userAge": 25},就能把数据封装到 UserInfo 对象中。

|-----------------------------------------------------------------------------------------------------|--------------------|--------------------------------------------------------------------------------------------------|
| ← 上一篇 Java进阶------常用类及常用方法详解 | 记得点赞、关注、收藏哦! | 下一篇 Java进阶------数组超详细整理 → |

相关推荐
敲上瘾1 小时前
Qt 主窗口QMainWindow:菜单栏、工具栏、状态栏与浮动窗口等
开发语言·c++·qt·ui·qt6.3
这个昵称不容易2 小时前
网上摄影工作室系统设计与实现:96 个 Java 文件、115 个接口,作品发布到点赞评论一条线走完
java·springboot·毕设
金銀銅鐵3 小时前
带您看懂字节码指令(七):对象创建里有什么——new 与 dup
java·jvm·后端
BK贝壳6 小时前
布尔数组也能做按位取反、移位和乘法:bool-hybrid-array 的位运算在本机跑了一遍
开发语言·数据结构·python·性能优化·numpy
吴名氏.7 小时前
全栈跃迁:Java 后端 27 讲【3】Vue3工程化脚手架
java·开发语言·springboot·全栈工程师
codeejun7 小时前
每日一Go·MySQL-24、死锁排查与解决方案
开发语言·mysql·golang
JellyfishMIX8 小时前
AgentScope-Java 核心机制(内循环) ReAct loop 源码分析
java·后端·agent
小此方9 小时前
QT从入门到精通(一)Qt新手保姆级教程:从官网安装到项目实战,四步带你彻底搞懂Qt框架
开发语言·qt
Rain的Java大神之路9 小时前
Spring Boot 4 把自动配置拆成 47 个模块后,我的 `dependency:tree` 翻天了:一份从排查到治理的完整实战手册
java·spring boot·后端
瑶池酒剑仙10 小时前
C++重构与代码质量完全指南:从设计模式、SOLID原则到代码审查与静态分析的工程实践(所赖君子见机)
c语言·开发语言·c++·设计模式·重构·哈希算法·visual studio