Session synchronization and token mechanism used in Java EE development to prevent concurrent duplicate submissions
Usually in normal operations, we do not need to deal with duplicate submissions, and there are many ways to prevent duplicate submissions. For example, in the login process, through the use of redirect, you can allow users to redirect to the background page interface, when the user refresh the interface will not trigger duplicate submission. Or use token, hidden in the form, when submitted for token verification, validation fails to commit. This is all a general practice.
The problem we encountered this time is that repeating commits itself is a mistake, and repeating commits leads to the logic of some related data being no longer correct. These repeated submissions are not made by a normal refresh interface, or by a two-click button. In the ordinary operation, we can use a series of means, so that the corresponding parameters are cleared, so as to prevent incorrect data. However, in one case, these methods are no longer valid, that is, concurrent duplicate commits.
Concurrent repetition commits, that is, at the same time (the interval can be shortened to 0.) Within x seconds), in which case all conventional logic is no longer valid, because multiple requests, while entering the system, are unable to determine whether the requests are invalid, they are judged by regular repetitive logic, and eventually the data is written to the database at the same time, causing data errors.
To give a simple example, sell a commodity in the system, first through the product ID into the system logic judgment, determine whether the product has been sold, if not sold, the data access operation. Whether or not a commodity is sold is a logical judgment and a door to validating the data stored in the database. In conventional judgment, after the previous request passes through the door, the latter request cannot be passed because the validation is false. However, in concurrent requests, two or more requests pass through the gate at the same time, because all are at the same time entered into the judgment, before the judgment to verify that the goods have not been sold, so at the same time into the data storage.
In general Java development, for this case, the critical resource is usually used to lock to ensure that the order of the situation. But the problem with locking is that it is a lock on the global information, that is, the entire product to be sold is locked. For BS applications, we must ensure that another operator's sales request for the same product is passed, that is, restricting only concurrent requests sold by the same operator, without limiting the processing of different requests from multiple operations personnel.
In this case, our locking can not be simply locked in the product, but to be locked in the information related to the operator, this is the session.
A session is a unique identifying information that maintains communication with the server side during the entire operation of a single operator. In multiple requests from the same operator, the session is always guaranteed to be the same object, not multiple objects, because it can be locked. When multiple requests are entered by the same operator, the session limit can only be used one way.
This article is to verify whether the same operator made a concurrent duplicate request by using the session and adding tokens to the session, and when the latter request arrives, the token in the session is used to verify that the token in the request is consistent and, when inconsistent, is considered a duplicate submission and will not be allowed to pass.
The entire process can be described by the following process:
- Client Request Token
- Token is generated on the server side and stored in session, and token is sent to the client
- The client stores tokens and sends token information at the time the request is submitted
- Server-side Unified intercept all requests from the same user, verifying that the current request needs to be verified (not all requests validate duplicate commits)
- Verify the token in the session is consistent with the token in the user's request and release if it is consistent
- Session clears tokens from sessions, preparing for next token generation
- Concurrent duplicate request arrives, authentication token and request token are inconsistent, request denied
By the above process, our entire implementation requires the following several things
- Token generator, responsible for generating tokens
- Customer token request process action, handle customer request, and return token information
- Token interceptor, which is used to intercept the specified request to verify token
- Token request intercept identity, which identifies which requests need to be intercepted
- Client token request processing method for requesting token and storing it in a specific operation and sending it to the request at commit time
Token generator
The token generator is implemented here using a random number that randomly generates a number that implements token generation, as follows:
| 123456789 |
private static final Random random = new Random(System.currentTimeMillis());public static final String TOKENPARAM = "session-token";/** 生成一个token */public static synchronized String generateToken(HttpSession session) { String s = String.valueOf(random.nextLong()); session.setAttribute(TOKENPARAM, s); return s;} |
Token Request Handling Action
Request processing action, that is, receive the corresponding request, and then directly return the corresponding token, the following is a token for the AJAX Request processing action:
| 12345 |
publicString generateTokenAjax() { String token = SessionTokenGenerator.generateToken(ServletActionContext.getRequest().getSession()); AjaxSupport.sendSuccessText(token); returnNONE;} |
token request intercept ID
Intercept the identity, which means which methods need to be intercepted, which can be implemented using annotations, i.e. append annotations like @tokenneed to the method to be intercepted, or use a configuration file to record the list of methods that need to be intercepted in the configuration file, in this article, a configuration file is used to record
token blocker
The token interceptor implements the interception processing that we need and, when confronted with a request for interception, synchronizes token judgment and processing and, based on the results of the processing, determines whether or not it should continue to be released or intercepted:
| 010203040506070809101112131415 |
public String intercept(ActionInvocation invocation) throwsException { String action = invocation.getProxy().getAction().getClass().getName(); String method = invocation.getProxy().getMethod(); final HttpSession session = ServletActionContext.getRequest().getSession(); if(includeMethodSet.contains(action + "." + method)) { synchronized(session) { String paramSessionToken = ServletActionContext.getRequest().getParameter(SessionTokenGenerator.TOKENPARAM); String sessionSessionToken = (String) session.getAttribute(SessionTokenGenerator.TOKENPARAM); if(sessionSessionToken == null || paramSessionToken == null || !paramSessionToken.equals(sessionSessionToken)) return fail(); session.removeAttribute(SessionTokenGenerator.TOKENPARAM); } } return invocation.invoke();} |
If the method above is to determine whether the process is in the interception list, if so, the token in the parameter, and then compared to the token in the session, if not consistent, then directly return to fail, and then remove it from the session.
Client Token implementation
As a client, you only need to request a token before the request is submitted, and when requested, add the token to the request. In this article, there is a jquery Ajax method to handle the token request, which is then added to the Param when the AJAX request is made. The jquery request for token is as follows
| 123456 |
< Code class= "Java plain" >m_ylf.token = function () { &NBSP;&NBSP;&NBSP;&NBSP; Code class= "Java Plain" >m_ylf.invoke ( "/token/generatetoken" ,{}, function (re) { re = re[ "result" &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; window[ "Session-token" < code> &NBSP;&NBSP;&NBSP;&NBSP; |
That is, when processing the received token into the window, to submit the request and then remove it from the window, and then submit, such as the following unified Ajax processing method:
| 123 |
//追加session-tokenif(window["session-token"]) param["session-token"] = window["session-token"]; |
Thus, the entire anti-session token request is complete. If the client impersonates multiple requests, first a request is processed successfully, and the other requests return a similar "cannot commit" error warning (for AJAX requests).
Reprint please indicate source: I Flym
This address: http://www.iflym.com/index.php/code/avoid-conrrent-duplicate-submit-by-use-session-synchronized-and-token.html
Session synchronization and token mechanism used in Java EE development to prevent concurrent duplicate submissions