Question

I'm looking for help/advice with creating simple JSP website using equivalent of PHP include+switch function.

The goal is that I want to be able to switch between multiple JSP include pages in one main page.

What would be the simplest possible form of above 'function'?

Was it helpful?

Solution

There you have the <jsp:include> for. You can use EL to specify the page attribute.

Create a /WEB-INF/main.jsp file which look like:

<!doctype html>
<html lang="en">
    <head>
        <title>Title</title>
    </head>
    <body>
        <jsp:include page="${page}" />
    </body>
</html>

You can control the ${page} value with help of a page controller servlet. Something like:

public class PageController extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("page", "/WEB-INF" + request.getPathInfo());
        request.getRequestDispatcher("/WEB-INF/main.jsp").forward(request, response);
    }

}

Map this servlet in web.xml as follows:

<servlet>
    <servlet-name>pageController</servlet-name>
    <servlet-class>com.example.PageController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>pageController</servlet-name>
    <url-pattern>/page/*</url-pattern>
</servlet-mapping>

This way the servlet is accessible through http://example.com/context/page/foo.jsp and in this URL example it will then get /foo.jsp from the pathinfo and thus set the page attribute with the value /WEB-INF/foo.jsp so that it is available in EL as ${page} so that the jsp:include knows what it should include. No need for nasty scriptlets or switch statements.

In the /WEB-INF/foo.jsp you can just write down HTML as if it is placed inside the HTML <body> tag.

Note that the JSP files are placed in /WEB-INF, this is done so to prevent direct access by URL so that the users cannot request them without going through the page controller, such as for example http://example.com/context/foo.jsp which would only return the partial content (the to-be-included page).

Hope this helps.

OTHER TIPS

Try

<%  if ( expression1 ) { %>
    <%@ include file="file1.jspf" %>
<% } else if(expression2) { %>
    <%@ include file="file2.jspf" %>
<% } %>

Or, if you have the option, check out JSF2 and/or Facelets. It has much more powerful templating capabilities.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top