Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

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

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 WelcomeServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)      throws ServletException, IOException
    {
        HttpSession session = request.getSession();
        session.setAttribute("MyAttribute", "test value");

        // response.sendRedirect("index.jsp");
        RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
        dispatcher.forward(request, response);
    }

}

And simple jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Index page</title>
</head>
<body>
Index page
<br />
 <% 
Object sss = request.getAttribute("MyAttribute"); 
String a = "22";

%>

   <%= request.getAttribute("MyAttribute"); %>
</body>
</html>

Whatever I do attribete at jsp is null.

What is wrong at this simple code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...