Daniel Ribeiro
Daniel Ribeiro

Reputation: 10234

Include .jsp page inside another dynamically according to url

I'm using Java with Servlets and JSP to create a basic application.

I have this basic html file I call the base layout, which has the basic page structure, with the navigation menus, header and footer.

I also have a register.jsp page, in which the user can register.

How can I include that register.jsp into the base layout when the user hits the /register url?

Currently, I dump the html content of the register page from the Servlet using the PrintWriter object and use ajax to render the content on the base page dynamically. But this is really a bad practice.

Upvotes: 1

Views: 2337

Answers (2)

MaVRoSCy
MaVRoSCy

Reputation: 17839

Yes indeed that is bad practice.

The simpler choice that can be done easily is to convert your html file to a jsp. Then within the jsp you can include any other resource you want. Consider this example:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <jsp:include  flush="true" page="/templates/css.jsp"/>
        <jsp:include  flush="true" page="/templates/scripts.jsp"/>
    </head>
    <body>
        <div id="container">
            <div id="header">
                <jsp:include  flush="true" page="/templates/header.jsp"/>
                <jsp:include  flush="true" page="/templates/top_menu_visitor.jsp"/>
            </div>
            <div id="wrapper">
                <jsp:include  flush="true" page="/templates/top_content_visitors.jsp"/>
            </div>
            <div id="footer">
                <jsp:include  flush="true" page="/templates/footer_credits.jsp"/>
            </div>
        </div>
    </body>
</html>

In this example you have a template page that includes many components, most of wich are common between different pages. This can be very well be your index.jsp. For the register jsp you just have to create a new jsp page like this and just change a couple of section.

This is one way to go. In Java EE, there are many frameworks that can automate this process.

Upvotes: 1

gerrytan
gerrytan

Reputation: 41123

You can use <jsp:include> combined with <c:if> conditional block that checks current URL.

Current request URL can be obtained using ${pageContext.request.requestURI}

There's also Apache Tiles library that help overcome lack of reusability on JSP

See more about <jsp:include> on Java EE5 tutorial: http://docs.oracle.com/javaee/5/tutorial/doc/bnajb.html

Upvotes: 0

Related Questions