how to store request object in session scope in jsp

前端 未结 3 1938
南方客
南方客 2021-01-28 03:00

I was just doing random trick & testing in my jsp pages. I wanted to store request scope object in session scope object using At

3条回答
  •  不知归路
    2021-01-28 03:51

    Request object shouldn't be stored in the session. As JB Nizet wrote it shouldn't be used out side of current request. Container may decide for example to reuse that object later on, while handling different request, resetting all its attributes.

    You can get parameters and attributes from current request using methods request.getParameter() and request.getAttribute() and if you need them for later you can store them in session. You can also store your arbitrary objects in session. For example like this (fragment):

    String paramForLater = request.getParameter("p1");
    // store parameter
    session.setAttribute("paramForLater", paramForLater);
    
    // store some data
    Person personData = new Person();
    session.setAttribute("personData", personData );
    
    // you can retrieve these object later in different jsp like this
    Person personData = (Person) session.getAttribute("personData");
    String param = (String ) session.getAttribute("paramForLater");
    

    Methods request.set/getAttribute() are used only, while handling current request. For example you may set some parameters in servlet(controller), then access them in the jsp (view) to which that same request was forwarded. in pattern like this:

    // in servlet get your data e.g. from database
    MyEntity entity = // code to get entity;
    request.setAttribute("entity", entity);
    request.getRequestDispatcher("view.jsp").forward(request, response);
    
    
    // then in jsp you can access that paramter 
    <%
    MyEntity e = (MyEntity) request.getAttribute("entity");
    ... // do something in entity
    %>
    

    You probably should use EL expression instead of scriplets, but this theme for another discussion :).

提交回复
热议问题