当前位置:网站首页>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
边栏推荐
- Promise
- [introduction to ROS] - 03 basic concepts and instructions of ROS
- Web3生态去中心化金融平台——Sealem Finance
- How to write this with data and proc without SQL
- hooks的设计哲学
- IRS应用发布之十五:应用安全自测指南
- ADB loop output memory information to folder
- 部分 力扣 LeetCode 中的SQL刷题整理
- Millions of visits - resolution of high concurrency problems
- 快递鸟系统对接
猜你喜欢

CentOS actual deployment 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

Web3生态去中心化金融平台——Sealem Finance

简述自定义注解

Inventory management and strategy mode
![[paper reading] boostmis: boosting medical image semi supervised learning with adaptive pseudolabeling](/img/10/a60cfe830e2238de00121d7bd95ad6.png)
[paper reading] boostmis: boosting medical image semi supervised learning with adaptive pseudolabeling
![[persistent problems of NVIDIA driver] - - /dev/sdax:clean, xxx/xxx files, xxx/xxx blocks - the most complete solution](/img/0e/8c79f7c77f61dfa9a155ab33b77081.png)
[persistent problems of NVIDIA driver] - - /dev/sdax:clean, xxx/xxx files, xxx/xxx blocks - the most complete solution

Le meilleur outil de tambour créatif: Groove agent 5
![[introduction to ROS] - 03 single chip microcomputer, PC host and ROS communication mechanism](/img/ad/d798284ceb370f7c68cbab755a11de.png)
[introduction to ROS] - 03 single chip microcomputer, PC host and ROS communication mechanism
随机推荐
北京中国专利奖政策支持介绍,补贴100万
Introduction to the policy support of Beijing China Patent Award, with a subsidy of 1million yuan
How about compound interest insurance and financial products? Can I buy it?
项目_基于网络爬虫的疫情数据可视化分析
Middleware_ Redis_ 06_ Redis transactions
Current limiting and download interface request number control
[introduction to ROS] - 01 introduction to ROS
北京企业前沿引领技术创新补助资金介绍,补助500万
Time dependent - format, operation, comparison, conversion
[introduction to ROS] - 03 ROS workspace and function pack
中间件_Redis_06_Redis的事务
Direct insert sort and shell sort
中国专利奖申报流程介绍,补贴100万
Summary of pytorch classification problems
IRS应用发布之十五:应用安全自测指南
Traversal (pre order, middle order, post order) and search of binary tree
最好的創意鼓工具:Groove Agent 5
什么是C端 什么是B端 这里告诉你
Norme de soutien à la culture des entreprises de haute technologie du district de Mentougou à Beijing, subvention de 100 000 RMB
2022北京怀柔区新技术新产品(服务)认定要求