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.