Narley Brittes
Narley Brittes

Reputation: 151

How to set an attribute in a jsp page with hyperlink (request scope)

I think the title above is a bit confusing. What I'm trying to achieve:

I have a jps page(located in WEB-INF) with a hyperlink in it that will call another jsp (in WEB-INF) via servlet.

I understand that this can be achieved using the following:

<a href="ServletName">Go to this page</a>

But because there will be lots of hyperlinks, my idea was to have a general servlet(OpenPagesServlet) to handle all those pages.

Something like this:

JSP page:

<% request.setAttribute("page", "page1.jsp");%>
<a href="OpenPagesServlet">Page 1</a>

OpenPagesServlet in doGet method:

String page = (String) request.getAttribute("page");
request.getRequestDispatcher("/WEB-INF/" + page).forward(request, response);

I tried the code above and I get:

HTTP Status 404 - Not Found

type Status report

messageNot Found

descriptionThe requested resource is not available.

But if I try with session.setAttribute / sesion.getAttribute the code works fine, but I don't want to have sessions on each time I click on hyperlinks.

The other approach I found was to use:

<a href="OpenPagesServlet?value=page1">Page 1</a>

and inside the servlet:

String page = (String)request.getParameter("value");
request.getRequestDispatcher("/WEB-INF/" + page).forward(request, response);

It worked, but this approach is not good because the page can then be accessed directly using the url:

http://localhost:8080/WebApp/OpenPagesServlet?value=page1

So...my question is why request.setAttribute/request.getAttribute is returning 404? Is there a different approach to achieve what I'm trying to do?

Upvotes: 0

Views: 3097

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280102

An HttpServletRequest and its attributes only live for the duration of one HTTP request/response cycle. After yo've set the attribute in the JSP, the JSP is rendered and sent as part of the HTTP response body. The Servlet container considers the request handled and clears its attributes. The attribute is now gone.

It is therefore no longer available in the next request that arrives after the user clicks the link.

The session attribute or request parameter is fine. Consider looking into the Front Controller pattern.

Also, consider using the core tag library (in particular the url tag) instead of scriptlets for constructing your links.

Upvotes: 3

Related Questions