Sobes.tech
Junior — Middle

Is it possible to declare a field in a servlet handler as non-static and immutable after initialization?

sobes.tech AI

Answer from AI

In a servlet, you can declare a field as non-static (i.e., an instance field) and make it immutable after initialization, for example, using the final modifier. Usually, servlet fields are declared as private final and initialized in the init() method or in the constructor (if a non-standard initialization method is used).

It is important to remember that a servlet is created once and used by many threads, so fields should be either immutable (final) or thread-safe. Non-static final fields are suitable for storing configuration or resources that do not change after initialization.

Example:

public class MyServlet extends HttpServlet {
    private final String configValue;

    @Override
    public void init() throws ServletException {
        this.configValue = getServletConfig().getInitParameter("configKey");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.getWriter().write("Config: " + configValue);
    }
}

In this example, the configValue field is non-static and final, and it is initialized once during the servlet's initialization.

Is it possible to declare a field in a servlet… - sobes.tech