当前位置:网站首页>Web开发小妙招:巧用ThreadLocal规避层层传值
Web开发小妙招:巧用ThreadLocal规避层层传值
2022-07-06 12:58:00 【华为云开发者联盟】
摘要:我们可以在处理每次请求的过程中,无需从Controller以及Service中的方法层层传值,只需要直接通过该局部变量取值即可。
本文分享自华为云社区《拦截器中巧用ThreadLocal规避层层传值》,作者:KevinQ。
Web开发中的一点麻烦事
最近,准确地说,是一直都有的一点麻烦事:函数层层传递。什么意思呢?比如说有个很常见的需求描述是:记录用户的某次操作明细。
以在Java的开源框架jfinal中,操作添加一个用户的接口为例,有:
public class XXController() { public void addUser() { // 获取操作人 Integer opUserId = Integer.parseInt(getHeader("opUserId")); // 获取其他参数... service.addUser(...., opUserId); renderAppMsg("添加用户成功"); }}为了记录用户添加的具体操作内容以及信息错误,这个记录用户操作的记录可能需要穿透好层方法。
public class XXService() { public void addUser(String tel, String name, String password, Integer opUserId) { checkTel(tel, opUserId); checkName(name, opUserId); checkPassword(password, opUserId); } public void checkTel(String tel, Integer opUserId) { check(tel, opUserId); } publc void check(..., Integer opUserId) { // ... }}举得这个例子或许不是很恰当,但是相信大家可以理解这个麻烦点在哪里。
函数调用链中的每个方法并不是需要这个参数,而可能仅仅是为了向下个被调用的函数传递这个参数。
那么是否有方法帮助我们来不需要这样逐层传递,从而获取接口请求参数的方法呢。
思考
这有点类似与一个全局变量,但是这个变量对每次请求来说是变化的,那么是否有一种方式能够让我们来保存这样一种:针对每次请求的全局变量呢?
在最近学习Shiro的过程中,以及学习若依开源框架的过程中,我们发现其均使用到了一个强大的Java类:ThreadLocal。
shiro使用ThreadLocal是用来保存当前登录对象,若依框架中,其中所使用的分页插件PageUtil使用ThreadLocal保存请求参数中的pageNum与pageSize等分页参数。因此我们是不是也可以使用ThreadLocal来达到同样的目的。
在拦截器中使用ThreadLocal暂存请求参数
为此,我们来尝试一下,通过ThreadLocal保存请求参数,通过拦截器我们可以拦截每次请求,如下是实现方式:
package com.holdoa.core.interceptor;import com.jfinal.aop.Interceptor;import com.jfinal.aop.Invocation;import javax.servlet.http.HttpServletRequest;public class RequestPool implements Interceptor { public static ThreadLocal<HttpServletRequest> localRequest= new ThreadLocal<>(); @Override public void intercept(Invocation inv) { localRequest.set(inv.getController().getRequest()); inv.invoke(); localRequest.remove(); } public static HttpServletRequest getRequest() { return localRequest.get(); }}我们通过ThreadLocal将整个请求暂存起来,当然,为了节约内存,也可以只保存使用频次高的通用参数,比如当前登录人的信息等等。
使用参数
使用时,只需要我们通过这个线程局部变量取值即可:
String para = RequestPool.localRequest.get().getParameter("username");如此,我们便可以在处理每次请求的过程中,无需从Controller以及Service中的方法层层传值,只需要直接通过该局部变量取值即可。
边栏推荐
- 全网最全的新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀
- The use method of string is startwith () - start with XX, endswith () - end with XX, trim () - delete spaces at both ends
- 愛可可AI前沿推介(7.6)
- Huawei device command
- Data Lake (VIII): Iceberg data storage format
- @Detailed differences among getmapping, @postmapping and @requestmapping, with actual combat code (all)
- Introduction to the use of SAP Fiori application index tool and SAP Fiori tools
- OAI 5g nr+usrp b210 installation and construction
- 嵌入式开发的7大原罪
- JS get array subscript through array content
猜你喜欢

【OpenCV 例程200篇】220.对图像进行马赛克处理

The most comprehensive new database in the whole network, multidimensional table platform inventory note, flowus, airtable, seatable, Vig table Vika, flying Book Multidimensional table, heipayun, Zhix

审稿人dis整个研究方向已经不仅仅是在审我的稿子了怎么办?

PHP saves session data to MySQL database

【力扣刷题】32. 最长有效括号

【论文解读】用于白内障分级/分类的机器学习技术
![[interpretation of the paper] machine learning technology for Cataract Classification / classification](/img/0c/b76e59f092c1b534736132faa76de5.png)
[interpretation of the paper] machine learning technology for Cataract Classification / classification

Reference frame generation based on deep learning

HMS core machine learning service creates a new "sound" state of simultaneous interpreting translation, and AI makes international exchanges smoother

OAI 5g nr+usrp b210 installation and construction
随机推荐
Common English vocabulary that every programmer must master (recommended Collection)
What is the difference between procedural SQL and C language in defining variables
Start the embedded room: system startup with limited resources
js之遍历数组、字符串
OneNote 深度评测:使用资源、插件、模版
20220211 failure - maximum amount of data supported by mongodb
Ravendb starts -- document metadata
Infrared thermometer based on STM32 single chip microcomputer (with face detection)
LLVM之父Chris Lattner:为什么我们要重建AI基础设施软件
Laravel notes - add the function of locking accounts after 5 login failures in user-defined login (improve system security)
请问sql group by 语句问题
Yyds dry goods count re comb this of arrow function
【mysql】游标的基本使用
c#使用oracle存储过程获取结果集实例
嵌入式开发的7大原罪
038. (2.7) less anxiety
Nodejs tutorial let's create your first expressjs application with typescript
None of the strongest kings in the monitoring industry!
【力扣刷题】32. 最长有效括号
Comprehensive evaluation and recommendation of the most comprehensive knowledge base management tools in the whole network: flowus, baklib, jiandaoyun, ones wiki, pingcode, seed, mebox, Yifang cloud,