开发者

Storing HttpServletResponse and HttpServletRequest as two fields of a HttpServlet

Is it a g开发者_如何学Pythonood 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);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜