Abstract : We can process every request , No need to Controller as well as Service The method in passes values layer by layer , You only need to take the value directly through the local variable .
This article is shared from Huawei cloud community 《 Skillfully used in interceptors ThreadLocal Avoid passing values layer by layer 》, author :KevinQ.
Web A little trouble in development
lately , To be exact , It's always a little trouble : Function layer by layer transfer . What does that mean ? For example, a common requirement description is : Record the details of a user's operation .
In the Java Open source framework of jfinal in , Add a user's interface as an example , Yes :
public class XXController() {
public void addUser() {
// Get operator
Integer opUserId = Integer.parseInt(getHeader("opUserId"));
// Get other parameters ... service.addUser(...., opUserId);
renderAppMsg(" Add user successfully ");
}
}
In order to record the specific operation content and error information added by the user , This record of user actions may need to penetrate good layer methods .
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) {
// ...
}
}
This example may not be very appropriate , But I believe you can understand where the trouble lies .
This parameter is not required for each method in the function call chain , It may just be to pass this parameter to the next called function .
So is there a way to help us not need to pass layer by layer , So as to obtain the method of interface request parameters .
reflection
This is a bit like a global variable , But this variable changes for each request , So is there a way for us to save such a : The global variables for each request ?
I've been learning recently Shiro In the process of , And the process of learning ruoyi open source framework , We found that they all use a powerful Java class :ThreadLocal.
shiro Use ThreadLocal Is used to save the current login object , If in the frame , The paging plug-in used PageUtil Use ThreadLocal Save... In the request parameters pageNum And pageSize Equal page parameters . So can we also use ThreadLocal To achieve the same purpose .
Use in interceptor ThreadLocal Staging request parameters
So , Let's try , adopt ThreadLocal Save request parameters , Through the interceptor, we can intercept every request , The following is the implementation method :
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();
}
}
We go through ThreadLocal Staging the entire request , Of course , To save memory , You can also save only common parameters that are frequently used , For example, the information of the current login person, etc .
Using parameter
When using , We only need to take the value of the thread local variable :
String para = RequestPool.localRequest.get().getParameter("username");
such , We can process each request , No need to Controller as well as Service The method in passes values layer by layer , You only need to take the value directly through the local variable .
Click to follow , The first time to learn about Huawei's new cloud technology ~
Web Develop little tricks : Skillfully use ThreadLocal Avoid more related articles about layer by layer value transfer
- Angular Develop little tricks 1: Submit form data validation failed , Change the style of the input component
When developing forms , Client data integrity verification is essential , stay jquery There are countless data verification plug-ins in the era, which are also easy to use , Development Angular When applied ,angular Built in some common data validation instructions . Today is not about how these instructions ...
- Move Web Develop tips
Move Web Develop tips Title added to the back of the home screen (IOS) name="apple-mobile-web-app-title" content=" title "> Enable ...
- Angular+ionic2 web End The startup program appears briefly White screen or black screen How to deal with it
stay ionic2 When the project starts, there will be a short white screen or a black screen , Though very short , But the user experience is not so good . I checked the relevant information on the Internet , It's all about packaging APP Solutions for , There is no effect on projects used on the browser side , So I wrote my own style , Cleverly avoid this problem , ...
- 14 individual Linux System security tips , There's always a way !
For the Internet IT For practitioners , More and more work will gradually shift to Linux On the system , This point , Both development . Operation and maintenance . It should be a deep test . There was a technical survey website W3Techs On 2018 year 11 A survey report was released in January , According to the report L ...
- Here you are 40 Tips to improve your programming skills ! also TIOBE 7 Programming language rankings for the month
How to improve programming skills ? I'm afraid many developers have thought about this . lately , Has nearly 15 Software engineer with years of development experience Kesk -*- Wrote a blog post , List 40 Items that will help his career . Maybe , By 40 individual ...
- Web Development tips -- Comprehensive understanding Cookie
One .Cookie Appearance Communication between browser and server is indispensable HTTP agreement , But because HTTP Protocol is stateless , So the server doesn't know what the browser did last time , This is a serious obstacle to interactive Web Implementation of application program . In view of the above ...
- About MySQL Index knowledge and tips — get get get
One . Index Basics 1.1 The advantages of indexing It greatly reduces the amount of data that the server needs to scan , Speed up database retrieval Help server avoid sorting and temporary tables Will be random io Into order io 1.2 The use of indexes Find a match quickly WHERE Line of clause from c ...
- 【CSS】 Little trick , Summary of various problems and treatment methods
1. Realization div Automatic ellipsis interception for text overflow overflow:hidden; /* More than one part is not shown */ text-overflow:ellipsis; /* The excess is represented by dots */ white- ...
- 【 turn 】 A little trick can save you a lot on clothes rmb
friends , You have carefully calculated how much you spend on buying clothes on Taobao every year rmb Do you ?100?1000?10000? Even more ? friends , Do you know where the clothes of most shops on Taobao come from ? friends , You know how to save more mon ...
- web Develop little knowledge
session Sharing mechanism :f5 Refresh is the data request before submitting again Address bar carriage returns belong to different requests Different browsers can't get the previous data The same browser can get synchronized data session Cancellation :session.invalidate() ...
Random recommendation
- C++ Create and traverse binary trees
A simple method to create and traverse binary tree C++ Program , Other operation procedures of binary tree need to be updated . #include <iostream> using namespace std; struct BiTNode{ ch ...
- vmware install mac
1. Laptop installation mac10.6 2. use VMware8, Need to be in mac.vmx Add the following statement to guestOS = "darwin10"ich7m.present="TRUE&q ...
- IronPython call C# DLL Function method
C# DLL Source code using System; using System.Collections.Generic; using System.Text; using System.Security.Cr ...
- jquery easyui tab Several ways to load content
turn :http://my.oschina.net/u/2331760/blog/391937?fromerr=saqeoxxB jQuery Easyui Of tabs Plug ins have two ways to load a tab( TAB ...
- sdut 2847 Monitor ( Thinking questions )
subject The question : Given a, b, x, y; Please make c, d; send c:d = x :y; And c<=a, d<=b, and c, d As big as possible . Find the minimum multiple first , Multiply by the smallest multiple x, y; #inclu ...
- JS Summary of common special effect methods
1. Press Ctrl Submit <body onkeydown="if(event.ctrlKey&&event.keyCode=='13') form1.submit.click ...
- C Language switch/case Cycle complexity optimization reconfiguration
Software refactoring is to improve code readability . Extensibility . Common technical means for maintainability and other purposes . Cycle complexity as a software quality metric , It can reflect these internal quality requirements to a certain extent ( Not all, of course ), So cyclomatic complexity is often used by many projects as the degree of software quality ...
- centos7 install java Running environment
1. Check whether there are relevant historical versions shell:java-version 1.1. There is a correlation OpenJDK And other versions SDK You need to delete , Pictured . View details , Command window input ,shell:rpm -qa | gre ...
- U-boot How to compile and analyze the directory structure
U-boot The overall structure and linux similar , The compilation method is also very similar , General compile commands : make CROSS_COMPILE=arm-linux-gnueabihf- XXX( Target name ) Clear command : ...
- AtCoder Beginner Contest 069 ABCD topic
Topic link :http://abc069.contest.atcoder.jp/assignments A - K-City Time limit : 2sec / Memory limit : 256M ...