Home > OS >  Jsp can't get session attribute value
Jsp can't get session attribute value

Time:07-19

I wrote a servlet.

request.setAttribute("itemCount", 1000);
request.getRequestDispatcher("test.jsp").forward(request, response);

And in test.jsp I wrote:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<% 
String name=(String)session.getAttribute("itemCount"); 
out.print("Total items are: " name); 
%>
<p>Number of items: ${itemCount} </p>
</body>
</html>

But the second row is

Number of items: 1000

while the first row is

Total items are null

So what's the issue?Any help? Thx.

CodePudding user response:

In your servlet, you can try using:

request.getSession().setAttribute("itemCount", 1000);

& then in your jsp, you can access itemCount the way you are accessing.

Or alternatively,

use

<% 
String name=(String)request.getAttribute("itemCount"); 

in your jsp if you don't want to change any code in servlet (also mentioned by tgdavies in comment)

  • Related