gpt4 book ai didi

java - Spring MVC Controller 预处理请求体

转载 作者:行者123 更新时间:2023-11-29 07:59:24 30 4
gpt4 key购买 nike

我正在研究 spring REST API。在需求中,有 2 个具有相同 URL 但请求正文不同的 POST 请求。由于 Spring MVC 必须具有跨 Controller 的唯一映射,因此我必须预处理请求主体以映射到特定的 POJO。

根据请求正文中的 session_type,我必须将请求映射到特定的 POJO(JSON -> JAVA POJO)。

例如,如果请求正文中的“session_type”为“typeX”,则请求应映射到 ClassX POJO。如果请求正文中的“session_type”为“typeY”,则请求应映射到 ClassY POJO。

是否有办法使用某种 requestbody 注释来做到这一点?

最佳答案

如果你想绑定(bind)typeXtypeY,那么你肯定需要2个处理程序。但是,为什么我们不使用 @RequestMappingparam 选项:

@RequestMapping(method = RequestMethod.POST, 
value = "/url", params = "session_type=typeX")
public String handleTypeX(@RequestBody @ModelAttribute TypeX typeX){
//TODO implement
}

@RequestMapping(method = RequestMethod.POST,
value = "/url", params = "session_type=typeY")
public String handleTypeY(@RequestBody @ModelAttribute TypeY typeY){
//TODO implement
}

如果您需要一些准备工作(例如规范化参数或手动执行模型绑定(bind)),那么您可以将上述方法与 @InitBinder 结合使用,但请注意,@InitBinder 需要确切的 ULR 规则以及处理程序中的 @ModelAttribute 参数。

编辑:在 Spring MVC 中,不可能为确切的 URL 使用 2 个处理程序,即当方法/URL/参数/消耗类型相同时。 p>

因此我建议使用统一处理程序,您可以在其中检查必要的参数,然后手动转换为相应的类。为了找到必要的类(class),我想最好使用 Strategy pattern :

//class resolver according "session_type" parameter
//note, that you can use Spring autowiring capabilities
private final Map<String, Class> TYPES_CONTEXT = new HashMap<String, Class>(){
{
this.put("x", TypeX.class);
this.put("y", TypeY.class);
//TODO probably other classes
}
}


@RequestMapping(method = RequestMethod.POST,
value = "/url")
public @ResponseBody String handleAnyType(@RequestBody Map<String, String> body){
String sessionType = body.get("session_type");

//TODO handle case if sessionType is NULL

Class convertedClass = TYPES_CONTEXT.get(sessionType);

//TODO handle case if class is not found

Object actualObject = objectMapper.convertValue(body, convertedClass);

//now we use reflection for actual handlers, but you may refactor this in the way you want, f.e. again with Strategy pattern
//note that current approach there should be contract for methods names
Method actualHandler = this.getClass().getMethod("handle" + actualObject.getClass().getSimpleName());

return (String)actualHandler.invoke(this, actualObject);
}

public String handleTypeX(TypeX typeX){
//TODO implement
}

public String handleTypeY(TypeY typeY){
//TODO implement
}

//TODO probably other methods

此方法不处理验证并且省略了一些内容,但我相信这可能会有所帮助。

关于java - Spring MVC Controller 预处理请求体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15396039/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com