简体   繁体   中英

Why method in Java servlet class return null when called from another java servlet or java class?

I have two Java Servlets Organization1 and Organization2. I have saved the response value of Organization1 to one global variable called org1. Then I created a method getOrg1Name() in Organization1 which returns the value which is saved in that global variable org1. Please check code below:

   public class Organization1 extends HttpServlet {

    private String org1;

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter pw = response.getWriter();
        response.setContentType("text/html");

        this.org1 = request.getParameter("org1_name");

}
    public String getOrg1Name()
    {
        return this.org1;
    }

} Then after I created a 2nd servlet Organization2. Inside the doPost() method of Organization2, I created a instance of Organization1 so that I can call that method getOrg1Name() which returns the value saved in global variable org1. Please check code below:

    public class Organization2 extends HttpServlet {

        private String org2;

        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            PrintWriter pw = response.getWriter();
            response.setContentType("text/html");

            this.org2 = request.getParameter("org2_name");

            Organization1 organization1 = new Organization1();
            String org1 = organization1.getOrg1Name();

            // org1 is always null. Why??   
    }
    }

But each time method getOrg1Name() returns null. Can someone help me with this issue?

Field org1 in Organization1 is not a global variable in your case - it's a private field of class Organization1. That means when you create new instance of Organization1 field org1 is set to its default value. Default value of String is null.

If you want everything to work the way I see you want, you have to declare field org1 as static.

private static String org1;

In that case all instances of class Organization1 will have a link to one org1 instance.

However, this approach has a problem. Value of a field org1 will be rewritten with every request on servlet Organization1. So it is a good task to understand how static fields work, but code smell in real programming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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