Eutherpy
Eutherpy

Reputation: 4571

Java servlets - navigate to page

I have the following project structure:

enter image description here

I am trying to navigate to concerts.jsp from index.jsp:

index.jsp

<li class="active"><a href="/ConcertsController">Concerts</a></li>

This is my ConcertsController:

@WebServlet("/ConcertsController")
public class ConcertsController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ConcertsController() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().append("Served at: ").append(request.getContextPath());
        request.getRequestDispatcher("/WEB-INF/pages/concerts.jsp").forward(request, response);
    }
        ...
    }

When I run the app, and click on the link in index.jsp, localhost:8080/ConcertsController URL opens and I get the

The requested resource is not available

error.

Edit 1: I am using Tomcat v7.0, servlets v3.0 and Java 8.

Edit 2 (possible duplicate): Well, surely I need to be able to do this without using the jstl library.

Edit 3: When localhost:8080/ConcertsController opens, I get the "resource not found" error. But when I manually edit the url to localhost:8080/AppName/ConcertsController, it works.

Upvotes: 0

Views: 3005

Answers (3)

Har Krishan
Har Krishan

Reputation: 273

Use

           <a href="${pageContext.request.contextPath}/ConcertsController">

Also when forwarding the request to cencerts.jsp use ServletContext.getRequestDispatcher(....)

ServletRequest.getRequestDispatcher() method will evaluate the path relative to the path of the request. But for the method of ServletContext, the path parameter cannot be relative and must start with /( / means at the root of web application not current relative path).

Upvotes: 1

SpringLearner
SpringLearner

Reputation: 13844

URL localhost:8080/ConcertsController means Application name is ConcertsController, port number is 8080 and the application is run locally. But you do not have ConcertsController Application. so you are getting error

The requested resource is not available

There are 2 solutions

  1. if you are not using JSTL.

Change <a href="/ConcertsController"> to <a href="<%${pageContext.request.contextPath}%>/ConcertsController">

  1. If JSTL is used then <c:set var="contextPath" value="${pageContext.request.contextPath}" /> and then change <a href="/ConcertsController"> to <a href="${contextPath}/ConcertsController">

Upvotes: 1

Serenity
Serenity

Reputation: 1

Try using the following:

request.getRequestDispatcher("/pages/concerts.jsp").forward(request, response);

instead of:

request.getRequestDispatcher("/WEB-INF/pages/concerts.jsp").forward(request, response);

Upvotes: -1

Related Questions