Joe.wang
Joe.wang

Reputation: 11793

Get Attribute variable passed from servlet

All, I have a attribute variable set in the servlet. and want to get it in the jsp. But I have some questions about it. Say you have the code .

In the servlet.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("BeerSelected", "BlackBeer");
        RequestDispatcher disp=request.getRequestDispatcher("SelectResult.jsp");
        disp.forward(request,response);
    }

In the JSP

this code works

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

But why below code doesn't work? jsp doesn't render the value .

<%request.getAttribute("BeerSelected");%>

Neither does below code.

<%request.getAttribute("BeerSelected").toString();%>

I don't know why toString() doesn't work. thannks.

Upvotes: 0

Views: 1388

Answers (1)

JB Nizet
JB Nizet

Reputation: 691635

Because to send something to the response writer, you must use <%= ... %>, or explicitely write to the writer:

<% out.println(request.getAttribute("BeerSelected")); %>

Your code is equivalent to the following Java code:

request.getAttribute("BeerSelected");

So this calls the method, but doesn't do anything with what it returns.

That said, you should forget completely about scriptlets, which shouldn't be used for years and years. Use the JSP EL and the JSTL to display (and correctly escape) your value:

<c:out value="${BeerSelected}" />

Also, an attribute is, by convention, spelled like a Java variable: beerSelected and not BeerSelected.

Upvotes: 4

Related Questions