当前位置:网站首页>Role of handlermethodargumentresolver + use case
Role of handlermethodargumentresolver + use case
2022-06-11 01:22:00 【Da Vinci does not assist】
Preface
I encountered a parameter resolution problem when I was working on the project today HandlerMethodArgumentResolver Doubts about the use of . I want to be a novice here to communicate with you and record . Next, the train starts to leave ......
Text
First, let's get to know the interface ,HandlerMethodArgumentResolver.
public interface HandlerMethodArgumentResolver {
boolean supportsParameter(MethodParameter var1);
Object resolveArgument(MethodParameter var1, ModelAndViewContainer var2, NativeWebRequest var3, WebDataBinderFactory var4) throws Exception;
}
You can see , This interface has two methods ,supportsParameter and resolveArgument.
Method supportsParameter Well understood. , The return value is boolean type , Its function is to judge Controller Parameters in layer , Whether the conditions are met , If the conditions are met, execute resolveArgument Method , If you are not satisfied, skip .
and resolveArgument Methods? , It's only in supportsParameter Method returns true It will be called . Used to handle some business , Assign return value to Controller This parameter in the layer .
So? , We can HandlerMethodArgumentResolver Understood as a parameter parser , We can implement... By writing a class HandlerMethodArgumentResolver Interface to implement Controller Modification of method parameters in layer .
Example of project code
When the parameter parser is not used Controller controller :
@Controller
@RequestMapping("/goods")
public class GoodsController {
private static Logger logger = LoggerFactory.getLogger(GoodsController.class);
@Autowired
UserService userService;
@RequestMapping("/to_list")
public String to_login(Model model,HttpServletResponse response,
@CookieValue(value=UserService.TOKEN,required = false)String cookieToken,
@RequestParam(value = UserService.TOKEN,required = false) String paramToken) {
if(StringUtils.isEmpty(cookieToken)&&StringUtils.isEmpty(paramToken)){
return "login";
}
String token = StringUtils.isEmpty(cookieToken) ? paramToken : cookieToken;
User user=userService.getByToken(response,token);
logger.info(user.toString());
model.addAttribute("user",user);
return "goods_list";
}
}
Please look carefully to_login Method cookieToken and paramToken, Take a closer look at the lower body of Dharma . It's not hard to see. , The two parameters and the statement code in the method body are for , adopt cookie or request Among them token This variable is used to query the user user Information about .
But we didn't find it , This method , Just for this simple little function , Just wrote so much code . Is it a little too bloated ? And if there are other ways to use the user user This information variable ?
well , At this time we can use HandlerMethodArgumentResolver Interface to perform a small optimization .
Use HandlerMethodArgumentResolver After the parser :
Write a class implementation HandlerMethodArgumentResolver Interface
@Service
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
@Autowired
MiaoshaUserService userService;
public boolean supportsParameter(MethodParameter parameter) {
Class<?> clazz = parameter.getParameterType();
return clazz==MiaoshaUser.class;
}
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
String paramToken = request.getParameter(MiaoshaUserService.COOKI_NAME_TOKEN);
String cookieToken = getCookieValue(request, MiaoshaUserService.COOKI_NAME_TOKEN);
if(StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken)) {
return null;
}
String token = StringUtils.isEmpty(paramToken)?cookieToken:paramToken;
return userService.getByToken(response, token);
}
private String getCookieValue(HttpServletRequest request, String cookiName) {
Cookie[] cookies = request.getCookies();
for(Cookie cookie : cookies) {
if(cookie.getName().equals(cookiName)) {
return cookie.getValue();
}
}
return null;
}
}
Put the class we wrote , Register in the configuration file
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
@Autowired
UserArgumentResolver userArgumentResolver;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(userArgumentResolver);
}
}
Last , Our control class can be written like this
@RequestMapping("/to_list")
public String list(Model model,MiaoshaUser user) {
model.addAttribute("user", user);
// Query product list
List<GoodsVo> goodsList = goodsService.listGoodsVo();
model.addAttribute("goodsList", goodsList);
return "goods_list";
}
————————————————
Copyright notice : This paper is about CSDN Blogger 「 Turn over oO」 The original article of , follow CC 4.0 BY-SA Copyright agreement , For reprint, please attach the original source link and this statement .
Link to the original text :https://blog.csdn.net/qq_36408229/article/details/104436508
边栏推荐
- NVIDIA Jetson's PWM Fan custom control
- 用data和proc怎么写出这个,不用sql
- 項目_基於網絡爬蟲的疫情數據可視化分析
- 深圳市南山区专精特新企业申报流程,补贴10-50万
- 中间件_Redis_05_Redis的持久化
- Introduction to the application process of Beijing China Patent Award, with a subsidy of 1million yuan
- 立个flag--重构promise
- dma_buf_export
- The file "setup" does not exist. What should I do?
- Throttling and anti chattering of functions
猜你喜欢

中间件_Redis_05_Redis的持久化
![[introduction to ROS] - 03 basic concepts and instructions of ROS](/img/d4/a9b49dddbe0be8b53acf71219d0959.png)
[introduction to ROS] - 03 basic concepts and instructions of ROS

CentOS actual deployment redis

如何使用自定义注解进行参数校验

Pd虚拟机安装系统提示 “网络初始化失败 操作失败 ”的解决方案

How to write this with data and proc without SQL

多兴趣召回模型实践|得物技术

Le meilleur outil de tambour créatif: Groove agent 5

网络基础(1)-----认识网络
![[introduction to ROS] - 03 ROS workspace and function pack](/img/74/ff9bf9fd4912a02d016f560ac3aebb.png)
[introduction to ROS] - 03 ROS workspace and function pack
随机推荐
ion_mmap
async await
After a/b machine is connected normally, B machine suddenly restarts. Ask a what is the TCP status at this time? How to eliminate this state in the server program?
云呐|省级行政单位固定资产管理系统
Clean up the broken artifacts data (.lastUpdated files) and reload the project. Problem resolution
ion_dma_buf_begin_cpu_access
Sealem finance builds Web3 decentralized financial platform infrastructure
Introduction and creation of Huffman tree
Web3生态去中心化金融平台——Sealem Finance
2022年高考加油 那年我的高考如此兴奋
北京中国专利奖政策支持介绍,补贴100万
焱融看|混合云环境下,如何实现数据湖最优存储解决方案
北京朝阳区专精特新制造业企业支持标准介绍,补贴100万
Solution to prompt "network initialization failed operation failed" in PD virtual machine installation system
ion_ dma_ buf_ begin_ cpu_ access
Pd虚拟机安装系统提示 “网络初始化失败 操作失败 ”的解决方案
百万级访问量—高并发问题的解决历程
对象存储 S3 在分布式文件系统中的应用
Millions of visits - resolution of high concurrency problems
SAS因子分析(proc factor过程和因子旋转以及回归法求因子得分函数)