Search code examples
javaservletsdtogetter-setter

Store data in a DTO from servlet ...?


Can the below way be implemented to store data in a DTO and access it from any where in the application rather than going for a context ?

Please provide suggestions !!!

public class DummyDTO {
    private String name = null;
    private String age = null;

    // getters and setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

public class MyServletClass extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DummyDTO dummyDTO = new DummyDTO();
        dummyDTO.setName(request.getParameter("name"));
        dummyDTO.setAge(request.getParameter("age"));
        AnotherClass.setValues(dummyDTO);
    }

    public class AnotherClass {
        String name = "";
        String age = "";

        public static void setValues(DummyDTO dummyDTO) {
            name = dummyDTO.getName();
            age = dummyDTO.getAge();
        }
    }
}

Solution

  • No, it can't. Static fields are global to the whole ClassLoader, (to the whole). So if you have several concurrent requests to your servlet, the second one will overwrite the data stored by the first one in the static fields (and in a thread-unsafe way, additionnally).

    If the data is local to a request, you should store it in a request attribute. That's what they're for.

    Side note: your fields are not static, but the only way your code would compile is to make them static.