由于我正在使用CQRS模式,因此我尝试创建一个单一的控制器方法,该方法在其请求主体中接受每个POST调用并发送它。 我几乎就在那里,但我无法获得路径变量。
我创建了一个自定义HandlerMapping
@Bean
public HandlerMapping requestMappingHandlerMapping() throws NoSuchMethodException {
for (final UrlEnum urlEnumItem : UrlEnum.values()) {
requestMappingHandlerMapping.registerMapping(new RequestMappingInfo(urlEnumItem.getCommandName(),
new PatternsRequestCondition(urlEnumItem.getUrl()),
null,
null,
null,
null,
null,
null),
commandController,
commandController.getClass().getDeclaredMethod("commandHandler", HttpServletRequest.class)
);
}
return requestMappingHandlerMapping;
}
这是我的控制器方法签名
@RequestMapping(method = {RequestMethod.POST, RequestMethod.PUT}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<Object> commandHandler(final HttpServletRequest request) throws Exception {
// controller code here
}
如果网址路径类似于/api/test
,则可以使用/api/test/{idEntity}
,但我不会在请求中提供任何PathVariable。
我尝试过像
这样的一切String originalUrl = (String) request.getAttribute(
HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
返回有价值的网址(即/api/test/1234
),而非模板或添加
@PathVariable Map<String, Object> parameters
作为方法中的参数,为空。
调试请求对象似乎没有什么对识别路径变量有用。
也许我应该询问HandlerMapping,但我无法在控制器方法中访问它。
有没有办法在控制器方法中提取pathVariables?
答案 0 :(得分:0)
It was an error in the configuration. I shouldn't have added the RequestMapping annotation to the controller method because it overrode my configuration.
Now I have
@RestController
public class CommandController extends AbstractController {
private final MappingJackson2JsonView mappingJackson2JsonView = new MappingJackson2JsonView();
@Override
protected ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
// controller code here
return new ModelAndView(mappingJackson2JsonView);
}
}