Roman
Roman

Reputation: 66216

How to pass variable from a servlet to a jsp page?

I have a servlet (front-controller), which analyse the request, prepare some necessary data (model) and then should pass it to the jsp to be rendered.

How should I pass the data from servlet to jsp? (I hoped that it was possible to add new parameters to parameters map in the request object, but that map is unmodifiable).

I can add attributes to the request but I don't know how to retrieve them from the jsp.

All the data should be in the request scope. What's the correct way?

Upvotes: 6

Views: 7698

Answers (2)

Sid
Sid

Reputation: 4995

You can use the request or the session scope for this. Apart from the answer by Nikita Rybak, you can use

request.getSession().setAttribute("key","value");

And then use it in JSP using scriplet.

<%=session.getAttribute("key")%>

Note that in the example given by Nikita, Expression Language(EL) has been used(I am not sure if it's JSTL tags). You need to explicitly state that EL is not to be ignored by using the isELIgnored property.

<%@ page isELIgnored="false" %>

Upvotes: 3

Nikita Rybak
Nikita Rybak

Reputation: 68036

I can add attributes to the request but I don't know how to retrieve them from the jsp.
You don't need to specifically 'retrieve' them, just referring them works

request.setAttribute("titleAttribute", "kittens are fuzzy");

and then

Title here: ${titleAttribute}

Upvotes: 6

Related Questions