
假设我们有一个restful接口,其get请求可能包含任意数量和名称的参数。我们希望将这些参数根据其值的特定规则(例如,值以“1”开头)分别收集到自定义请求对象myweirdrequest的两个map字段中:startwithone和anythingelse。
// 假设的请求示例 // http://localhost:8088/test?first=aaa&second=1bbb&third=1ccc&fourth=2ddd
我们期望MyWeirdRequest对象最终包含以下结构:
startWithOne=[second:1bbb, third:1ccc] anythingElse=[first:aaa, fourth:2ddd]
如果直接在控制器方法中使用Map<String, String>作为参数,虽然可以获取所有参数,但后续的解析和分组逻辑需要在每个使用此Map的控制器方法中重复编写,这显然违背了DRY(Don't Repeat Yourself)原则。尝试使用PropertyEditor配合@RequestParam也存在局限性,因为它通常用于单个参数的类型转换,而非解析整个自定义对象。
首先,我们需要定义一个Java类来承载解析后的请求参数。考虑到HTTP请求参数可能存在同名参数携带多个值的情况(例如?param=val1¶m=val2),Map的值类型应为String[]而不是String。
import java.util.Map;
import java.util.Arrays;
import java.util.HashMap;
public class MyWeirdRequest {
private Map<String, String[]> startWithOne = new HashMap<>();
private Map<String, String[]> anythingElse = new HashMap<>();
public Map<String, String[]> getStartWithOne() {
return startWithOne;
}
public void setStartWithOne(Map<String, String[]> startWithOne) {
this.startWithOne = startWithOne;
}
public Map<String, String[]> getAnythingElse() {
return anythingElse;
}
public void setAnythingElse(Map<String, String[]> anythingElse) {
this.anythingElse = anythingElse;
}
@Override
public String toString() {
return "MyWeirdRequest{" +
"startWithOne=" + mapToString(startWithOne) +
", anythingElse=" + mapToString(anythingElse) +
'}';
}
private String mapToString(Map<String, String[]> map) {
StringBuilder sb = new StringBuilder("{");
map.forEach((key, values) -> {
sb.append(key).append("=").append(Arrays.toString(values)).append(", ");
});
if (sb.length() > 1) { // Remove trailing ", "
sb.setLength(sb.length() - 2);
}
sb.append("}");
return sb.toString();
}
}HandlerMethodArgumentResolver是Spring MVC提供的一个强大接口,它允许我们自定义方法参数的解析逻辑。通过实现这个接口,我们可以完全控制如何从HttpServletRequest中提取数据并将其绑定到控制器方法的特定参数上。
该接口有两个核心方法:
supportsParameter(MethodParameter parameter): 此方法用于判断当前的解析器是否支持处理给定的方法参数。如果返回true,则表示该解析器可以处理此参数;否则,Spring会尝试寻找其他解析器。在这个场景中,我们希望解析器只处理类型为MyWeirdRequest的参数。
resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory): 这是实现参数解析逻辑的核心方法。它接收一个NativeWebRequest对象,通过该对象可以访问到原始的HttpServletRequest,从而获取请求参数、Header等信息。我们在这里实现将请求参数解析并填充到MyWeirdRequest对象中的逻辑。
下面是TestArgumentResolver的实现:
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class TestArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
// 判断是否支持MyWeirdRequest类型的参数
return parameter.getParameterType().equals(MyWeirdRequest.class);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory)
throws Exception {
MyWeirdRequest result = new MyWeirdRequest();
Map<String, String[]> startsWithOne = new HashMap<>();
Map<String, String[]> anythingElse = new HashMap<>();
// 获取所有请求参数,getParameterMap()返回Map<String, String[]>
for (Map.Entry<String, String[]> paramEntry : webRequest.getParameterMap().entrySet()) {
String paramKey = paramEntry.getKey();
String[] paramValues = paramEntry.getValue();
// 过滤出值以"1"开头的参数
List<String> swoValuesList = Arrays.stream(paramValues)
.filter(v -> v != null && v.startsWith("1"))
.collect(Collectors.toList());
if (!swoValuesList.isEmpty()) {
startsWithOne.put(paramKey, swoValuesList.toArray(new String[0]));
}
// 过滤出值不以"1"开头的参数
List<String> aeValuesList = Arrays.stream(paramValues)
.filter(v -> v != null && !v.startsWith("1"))
.collect(Collectors.toList());
if (!aeValuesList.isEmpty()) {
anythingElse.put(paramKey, aeValuesList.toArray(new String[0]));
}
}
result.setStartWithOne(startsWithOne);
result.setAnythingElse(anythingElse);
return result;
}
}在resolveArgument方法中,我们通过webRequest.getParameterMap()获取了所有请求参数的Map<String, String[]>形式。然后,遍历这个Map,根据值的开头是否为“1”进行分组,并分别存入MyWeirdRequest对象的startWithOne和anythingElse字段中。
为了让Spring MVC识别并使用我们自定义的HandlerMethodArgumentResolver,我们需要将其注册到Spring的配置中。这可以通过实现WebMvcConfigurer接口并重写addArgumentResolvers方法来完成。
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@Configuration
public class TestRequestConfiguration implements WebMvcConfigurer {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
// 将自定义的参数解析器添加到列表中
argumentResolvers.add(new TestArgumentResolver());
}
}通过@Configuration注解,Spring会自动扫描并加载这个配置类,从而使TestArgumentResolver生效。
现在,我们的控制器方法可以非常简洁地使用MyWeirdRequest作为参数,而无需关心复杂的参数解析逻辑:
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController("TestEndpoint")
@RequestMapping(path = "/", produces = MediaType.APPLICATION_JSON_VALUE)
public class TestEndpoint {
@RequestMapping(method = RequestMethod.GET, value = "/test")
public String getTest(MyWeirdRequest myRequest) {
// MyWeirdRequest对象已经由TestArgumentResolver填充完毕
return myRequest.toString();
}
}当请求http://localhost:8088/test?first=aaa&second=1bbb&third=1ccc&fourth=2ddd时,TestEndpoint的getTest方法将接收到一个已正确填充的MyWeirdRequest实例,其toString()方法输出将类似于:
MyWeirdRequest{startWithOne={second=[1bbb], third=[1ccc]}, anythingElse={first=[aaa], fourth=[2ddd]}}总而言之,当Spring Boot提供的标准注解无法满足复杂的请求参数映射需求时,HandlerMethodArgumentResolver提供了一个强大而灵活的扩展点。它允许开发者完全掌控参数解析过程,从而构建出更加健壮、可维护和业务驱动的RESTful API。
以上就是Spring Boot REST API自定义复杂请求参数映射的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号