简体   繁体   English

Java Servlet session.getAttribute和setAttribute

[英]Java Servlets session.getAttribute and setAttribute

I was trying to make a counter for the get requests of each session and I finally made it, however, I have a question in order to get to the bottom of the logic how this works. 我试图对每个会话的获取请求进行计数,但最终还是成功了,但是,我有一个问题,目的是要弄清逻辑如何工作。 Here is my code: 这是我的代码:

public class FirstServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       final String COUNTER = "Counter";
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FirstServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            HttpSession session = req.getSession();
            PrintWriter out = resp.getWriter();
            int count = 1;
            Integer i = (Integer) session.getAttribute(COUNTER);
            if(i != null){
                count = i.intValue() +1;
            }
            session.setAttribute(COUNTER, new Integer(count));
             out.println("<html>");
                out.println("<head>");
                out.println("<title>Session Counter</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("Your session ID is <b>" + session.getId());
                out.println("</b> and you have hit this page <b>" + count
                    + "</b> time(s) during this browser session");
        }

Here are the questions: 这里是问题:

Integer i = (Integer) session.getAttribute(COUNTER);
                if(i != null){
                    count = i.intValue() +1;
                }

Since I'm making Integer i and then casting it to integer, does this mean that no matter of the String value it will always have an int value of 0? 由于我要创建Integer i,然后将其转换为整数,这是否意味着无论String值如何,它的int值始终为0? (because COUNTER is of type String) (因为COUNTER是String类型的)

My second question is: why do I have to use session.setAttribute() after I get it in order to print the new value. 我的第二个问题是:为什么要在获取新值后必须使用session.setAttribute()。 My logic is the following. 我的逻辑如下。 As we know each servlet is instantiated only once - I get the attribute (session.getAttribute(COUNTER)), check if i is different than null and then increment it, if I comment the setAttribute I'll not be able to see the new incremented value. 我们知道每个servlet仅实例化一次-我获得属性(session.getAttribute(COUNTER)),检查i是否不同于null,然后对其进行递增,如果我注释了setAttribute,则将看不到新的增值。 Why do I have to set again in order to get the right value? 为什么必须再次设置才能获得正确的值? When I press refresh I'm making a new get request and it takes the old value of COUNTER (for example 2), then we check if it is not null and increment it by 1. I don't get why I have to use session.setAttribute again... 当我按“刷新”时,我正在发出一个新的get请求,它采用了COUNTER的旧值(例如2),然后我们检查它是否不为null并将其递增1。我不明白为什么我必须使用session.setAttribute再次...

Thanks! 谢谢!

First question: No. If the attribute is not in session, i will be null . 第一个问题:否。如果该属性不在会话中, i将为null

Second: This behavior is related to concept of immutability and understanding Java's concept of references . 第二:此行为与不变性的概念有关,并理解Java的引用概念。

Since sessions are storing Objects, your counter will become a reference to Integer object by autoboxing (so there's no need to create the Integer by hand). 由于会话存储对象,因此您的counter将通过自动装箱成为对Integer对象的引用(因此无需手动创建Integer )。 It is one of the immutable classes in JDK, and to change its value, You will need to create a new object reference , that's why it is required to update the object that is stored in session - because session still stores the reference address to old value. 它是JDK中不变的类之一,要更改其值,您将需要创建一个新的对象reference ,这就是为什么需要更新存储在session中的对象的原因-因为session仍然将引用地址存储为旧的值。

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

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