前言
我们在前台访问controller时,想要获取用户信息,就可以用这个办法
效果
我们访问的时候只携带了一个json对象
在controller中可以额外接受到一个dog对象
@GetMapping("/hello")
public String Test2(@RequestBody String people , Dog dog){
System.out.println(dog.getName());
return "hello jsong";
}
实现demo
实现WebArgumentResolver接口,重写resolveArgument方法
package com.jsong.wiki.test.config;
import com.jsong.wiki.test.bean.Dog;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;
public class MyWebArgumentResolver implements WebArgumentResolver {
@Override
public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest nativeWebRequest) throws Exception {
if (methodParameter.getParameterType() != null
&& methodParameter.getParameterType().equals(Dog.class)) {
return new Dog("dog");
}
return null;
}
}
写一个WebMvcConfigurer配置类,重写addArgumentResolvers方法
package com.jsong.wiki.test.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.annotation.ServletWebArgumentResolverAdapter;
import java.util.List;
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers){
resolvers.add(new ServletWebArgumentResolverAdapter(new MyWebArgumentResolver()));
}
}