比如/to_list这个请求并没有发送User user参数,如何给user参数赋值?
@RequestMapping("/to_list")
public String list(Model model,User user) {
model.addAttribute("user", user);
return "goods_list";
}
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
@Autowired
UserArgumentResolver userArgumentResolver;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(userArgumentResolver);
}
}
@Service
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
//首先执行这个方法,如果参数中有User类型参数,执行resolveArgument这个方法
public boolean supportsParameter(MethodParameter parameter) {
Class<?> clazz = parameter.getParameterType();
return clazz==User.class;
}
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
User user=new User();
user.setName("张三");
return user;
}
}