joh*_*ohn 2 spring spring-boot
我需要将请求URL作为String参数提交给方法
@RequestMapping(value = "/test", method = RequestMethod.POST)
public void testItt(@RequestParam String requestParameter, @RequestURL String requestUrl) {
// Do something with requestUrl
}
Run Code Online (Sandbox Code Playgroud)
如何正确提交请求URL?
我试过了
@RequestMapping(value = "/test", method = RequestMethod.POST)
public void testItt(@RequestParam String requestParameter, @RequestURL String requestUrl) {
// Do something with requestUrl
}
Run Code Online (Sandbox Code Playgroud)
但我觉得必须有更好的方法
永远不要只是从请求中获取URL.这太简单了!编程应该很难,当它不难时,你会很难!:)
但您可以按照上面显示的方式检索网址
因此,让我们从一个表示您想要检索的值的注释开始
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface RequestURL {
}
Run Code Online (Sandbox Code Playgroud)
这将作为注入您已有权访问的值的一种方式.
接下来,我们需要创建一个可以构建URL字符串的类
public class RequestUrlArgumentResolver
implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterAnnotation(RequestURL.class) != null;
}
@Override
public Object resolveArgument(
MethodParameter methodParameter,
ModelAndViewContainer modelAndViewContainer,
NativeWebRequest nativeWebRequest,
WebDataBinderFactory webDataBinderFactory) throws Exception {
HttpServletRequest request
= (HttpServletRequest) nativeWebRequest.getNativeRequest();
//Nice and cozy at home surrounded by safety not obfuscation
return request.getRequestURL().toString();
}
}
Run Code Online (Sandbox Code Playgroud)
接下来我们需要做的是让框架识别这个注释的处理程序.
将以下方法添加到您的配置中(如果您的配置未实现WebMvcConfigurer,您可能需要实现此类或创建一个包含新配置的新配置)
...
@Override
public void addArgumentResolvers(
List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new RequestUrlArgumentResolver());
}
...
Run Code Online (Sandbox Code Playgroud)
然后我们最终回到原始请求映射,它应该按原来的方式工作
@RequestMapping(value = "/test", method = RequestMethod.POST)
public void testItt(@RequestParam String requestParameter,
@RequestURL String requestUrl) {
// Do something with requestUrl
}
Run Code Online (Sandbox Code Playgroud)
积分 - https://www.baeldung.com/spring-mvc-custom-data-binder
| 归档时间: |
|
| 查看次数: |
1249 次 |
| 最近记录: |