views:

72

answers:

2

Hey There!

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

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

What will be simples possible form of above 'function'?

Many thanks!

+2  A: 

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.

Drew
Scriptlets are bad. Use Java classes and taglibs/EL.
BalusC
Don't disagree, but that would be the "simplest" way to solve that problem, IMO.
Drew
+4  A: 

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.

BalusC
Much more extensible solution than mine, just not quite as simple. ;) +1
Drew
And maintenance-free :)
BalusC