简体   繁体   中英

Java Servlet returns response to client before committing the database transaction

I use a 3rd party framework to process my requests by passing HttpServletRequest and HttpServletResponse into the framework. The database transaction handling is done separately from the framework like this:

public class MyServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {

        startTransaction();
        framework.process(req, resp);
        commitTransaction();

    }
}

As it turns out, the framework writes the full response back to the client before the call to commitTransaction() returns. This creates possible race-conditions: The client might issue a follow-up request that runs in a second new database transaction that can't access the data added or updated in the first transaction, because it is not committed yet.

What are best practices to work around those kind of issues? I can't modify the behavior of the framework I'm using.

I suggest to use a ServletFilter for such concerns. It would look like this:

public void doFilter(
        ServletRequest request,
        ServletResponse response, 
        FilterChain chain) throws IOException, ServletException {
    startTransaction();
    chain.doFilter(request, wrapper);
    commitTransaction();
 }

However, you should add exception handling to the filter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM