Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing HttpServletResponse and HttpServletRequest as two fields of a HttpServlet

Is it a good practice/safe to temporarily store the HttpServletRequest and the HttpServletResponse as two fields of a HttpServlet (see below) ? If not, why ?

import java.io.IOException;    
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Test extends HttpServlet
    {
    private HttpServletRequest req;
    private HttpServletResponse resp;
    @Override
    protected void doPost(
            HttpServletRequest req,
            HttpServletResponse resp
            )
            throws ServletException, IOException
        {
        try
            {
            this.req=req;
            this.resp=resp;
            do1();
            do2();
            }
        finally
            {
            this.req=null;
            this.resp=null;
            }
        }

    private void do1() throws ServletException, IOException
        {
        //use req resp
        }
    private void do2() throws ServletException, IOException
        {
        //use req resp
        }
    }

or should I invoke something like:

do1(req,resp);
do2(req,resp);
like image 745
Pierre Avatar asked Apr 12 '26 09:04

Pierre


1 Answers

Is it a good practice/safe to temporarily store the HttpServletRequest and the HttpServletResponse as two fields of a HttpServlet (see below) ?

No!

If not, why ?

Because servlets must be thread-safe. Multiple threads will be going through that servlet object concurrently. If you store the request/response in fields, your thread-safety goes out of the window.

Don't be tempted to take this kind of shortcut just to avoid the visual unpleasantness of parameter passing.

If you really must avoid parameters, then store the request/response in java.lang.ThreadLocal fields. It's still bad practice, but at least now it'll be thread-safe.

like image 154
skaffman Avatar answered Apr 13 '26 21:04

skaffman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!