简体   繁体   English

将数据存储在servlet的DTO中......?

[英]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 ? 是否可以实现以下方式将数据存储在DTO中并从应用程序中的任何位置访问它而不是去上下文?

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();
        }
    }
}

No, it can't. 不,它不能。 Static fields are global to the whole ClassLoader, (to the whole). 静态字段对整个ClassLoader是全局的(对整体而言)。 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). 因此,如果您有几个并发请求到您的servlet,第二个将覆盖静态字段中的第一个存储的数据(并且以一种线程不安全的方式,另外)。

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. 旁注:您的字段不是静态的,但代码编译的唯一方法是使它们保持静态。

You can use like this.... 你可以像这样使用....

Put values in a map which has key the user's sessionId. 将值放在具有用户sessionId键的映射中。

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, request.getSession().getSessionId());
}

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

    private static HashMap<String, DummyDTO> map; 
    public static HashMap<String, DummyDTO> setValues(DummyDTO dummyDTO, String key) {
      return map.put(key, dummyDTO);
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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