How can I set a session variable in a servlet and get it in a JSP?

后端 未结 3 1392

I\'m learning java and try to pass some variable from servlet to jsp page. Here is code from servlet page

@WebServlet(\"/Welcome\")
public class WelcomeServl         


        
相关标签:
3条回答
  • 2020-12-18 15:47

    you are getting if from request not session.

    It should be

    session.getAttribute("MyAttribute")
    

    I suggest you to use JavaServer Pages Standard Tag Library or Expression Language instead of Scriplet that is more easy to use and less error prone.

    ${sessionScope.MyAttribute}
    

    or

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    
    <c:out value="${sessionScope.MyAttribute}" />
    

    you can try ${MyAttribute}, ${sessionScope['MyAttribute']} as well.

    Read more

    • Oracle Tutorial - Using JSTL

    • Oracle Tutorial - Expression Language

    0 讨论(0)
  • 2020-12-18 15:55

    You set an attribute in a session. You have to retrieve it from a session:

    Object sss = session.getAttribute("MyAttribute");
    

    And since you are dispatching the request, you actually don't need a session. You can set the attribute in a request object in your servlet:

    request.setAttribute("MyAttribute", "test value");
    

    Then read it as you are already doing in you JSP.

    0 讨论(0)
  • 2020-12-18 16:02

    You should avoid scriptlets because they are java code in HTML, they break MVC pattern, they are ugly, odd and deprecated.

    Simply replace :

    <% 
    Object sss = request.getAttribute("MyAttribute"); 
    String a = "22";
    
    %>
    

    with simply using EL ${MyAttribute}

    But if you want to stick with scriptlets, you should get the attribute from the proper scope which is session in your case.

    0 讨论(0)
提交回复
热议问题