当前位置:网站首页>Web开发小妙招:巧用ThreadLocal规避层层传值
Web开发小妙招:巧用ThreadLocal规避层层传值
2022-07-06 12:38: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中的方法层层传值,只需要直接通过该局部变量取值即可。
边栏推荐
- Review questions of anatomy and physiology · VIII blood system
- Build your own application based on Google's open source tensorflow object detection API video object recognition system (IV)
- Core principles of video games
- SQL injection 2
- 2022 Guangdong Provincial Safety Officer C certificate third batch (full-time safety production management personnel) simulation examination and Guangdong Provincial Safety Officer C certificate third
- [cloud native and 5g] micro services support 5g core network
- Tencent byte and other big companies interview real questions summary, Netease architects in-depth explanation of Android Development
- Unity makes AB package
- Detailed introduction of distributed pressure measurement system VIII: basic introduction of akka actor model
- C language games - minesweeping
猜你喜欢

How to upgrade high value-added links in the textile and clothing industry? APS to help

OLED屏幕的使用

Continuous test (CT) practical experience sharing

Variable star --- article module (1)

数字三角形模型 AcWing 1018. 最低通行费

Ideas and methods of system and application monitoring

永磁同步电机转子位置估算专题 —— 基波模型与转子位置角

【每周一坑】计算100以内质数之和 +【解答】输出三角形

Tencent byte Alibaba Xiaomi jd.com offer got a soft hand, and the teacher said it was great

知识图谱之实体对齐二
随机推荐
Anaconda安装后Jupyter launch 没反应&网页打开运行没执行
Catch ball game 1
Maximum likelihood estimation and cross entropy loss
数字三角形模型 AcWing 1018. 最低通行费
Comment faire une radio personnalisée
JVM_ Common [interview questions]
C language games - minesweeping
Design your security architecture OKR
22-07-05 upload of qiniu cloud storage pictures and user avatars
Ideas and methods of system and application monitoring
Why do novices often fail to answer questions in the programming community, and even get ridiculed?
Anaconda安裝後Jupyter launch 沒反應&網頁打開運行沒執行
【DSP】【第二篇】了解C6678和创建工程
(工作记录)2020年3月11日至2021年3月15日
Basic knowledge of lists
Application layer of tcp/ip protocol cluster
Use of OLED screen
2022 nurse (primary) examination questions and new nurse (primary) examination questions
8086 instruction code summary (table)
1_ Introduction to go language