You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何开发支持多URI的REST Web服务方法并返回指定格式?

嘿,这两个问题其实在Spring MVC/Spring Boot里都有很直接的解决方案,我来给你梳理一下:

1. 让单个Web服务方法支持多个URI

你之前觉得“每个方法需对应唯一URI”,其实Spring的@RequestMapping注解完全支持映射多个URI——只需要给注解的value属性传入一个字符串数组,把所有需要匹配的URI都放进去就好。

举个修改后的代码例子:

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController // 后面会解释这个注解的作用
public class MyController {

    // 同时匹配 /add、/append、/insert 这三个URI
    @RequestMapping(value = {"/add", "/append", "/insert"})
    public Response add(@RequestParam List elements) {
        // 你的业务逻辑代码
        return new Response();
    }
}

如果需要更严谨,还可以加上method属性指定请求方法(比如method = RequestMethod.POST),避免不同请求方式的冲突。

2. 让方法返回指定格式(如JSON)

要让方法返回JSON格式,核心是让Spring把返回的Java对象自动序列化为JSON字符串,主要有两种常用且简洁的方式:

方式一:使用@ResponseBody注解

在方法上添加@ResponseBody,Spring会自动将返回的对象转换为JSON(前提是项目中引入了JSON处理依赖,比如Spring Boot的spring-boot-starter-web已经默认包含了Jackson库):

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.Controller;
import java.util.List;

@Controller
public class MyController {

    @RequestMapping(value = {"/add", "/append"})
    @ResponseBody
    public Response add(@RequestParam List elements) {
        Response response = new Response();
        // 设置response的具体内容
        return response;
    }
}

方式二:使用@RestController注解(更省心)

如果你的控制器类里所有方法都需要返回JSON这类响应体,直接用@RestController代替@Controller就行——它相当于@Controller + @ResponseBody的组合,每个方法默认都会返回序列化后的响应体:

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
public class MyController {

    // 可以通过produces属性明确指定返回格式为JSON,同时限制只有Accept头为application/json的请求才会匹配
    @RequestMapping(value = {"/add", "/append"}, produces = "application/json")
    public Response add(@RequestParam List elements) {
        Response response = new Response();
        // 设置response的具体内容
        return response;
    }
}

另外,produces属性(比如produces = MediaType.APPLICATION_JSON_VALUE)可以明确告诉客户端返回的内容类型,也能过滤掉不符合Accept请求头的请求,让接口更规范。

内容的提问来源于stack exchange,提问作者J123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:23:38