Dynamic includes in JSP

Does anyone know how I can include a file whose name is passed in via a querystring?
i.e.
<%
String requestedPage = request.getParameter("function");
if (requestedPage != null) {%>
<jsp:include page="<%=requestedPage%>" flush="true"/>
<% } %>
Obviously this does not work...can someone suggest an alternative to accomplish the include??
Thanks!

String requestedPage = request.getParameter("function");
if (requestedPage != null)
RequestDispatcher rd = application.getRequestDispatcher(requestedPage); 
rd.include(request, response);

Similar Messages

  • Dynamic include in a custom tag, called from a jsp

    Hello, I would like to be able to dynamically include other jsp's from within a custom tag that I create. is this possible?
    in a jsp page i would just write <%@ include file="file.jsp" %> and all would be ok... but if i do an out.println( "<%@ include file=\"file.jsp\" %>" ); inside a custom tag bean then it doesn't work. it just prints out the command to the page as plain text.
    I do understand why this is happening, but can anyone offer me a way around this problem?
    Thanks in advance,
    Randy

    That's actually the same result as you get with a normal include - The method I suggested is a dynamic include similar to the <jsp:include> tag, not the <%@ include %> tag.
    When you use a dynamic include, the included page is compiled and 'invoked' as serarately, and the result is what gets included, not the actual source. To get the behaviour you want would require an include directive (the <%@ include %> tag) which I don't think has an equivalence you can use inside a custom tag.
    What you can do is pass attributes from the tag class like this:
    pageContext.setAttribute(<name>, <object>, pageContext.REQUEST_SCOPE);
    and then remove them after the include using pageContext.removeAttribute.
    I'm not certain, but this implies that if you declare your variables with a <jsp:usebean> tag with request scope, instead of normal Java variable declarations, you should be able to use them in the page included by the custom tag.
    *** in the jsp ***
    <jsp:useBean id="myVar" scope="request" class="java.lang.String" />
    <% myVar = "Something"; %>
    // Now call the tag which uses the pageContext.include() mehtod.
    *** end ***
    *** in the include ***
    <jsp:useBean id="myVar" scope="request" class="java.lang.String" />
    <%= myVar + " something else" %>
    *** end ***
    Let me know if it works.

  • Dynamic inludes in JSP

    Is there any ability to conduct dynamic includes in JSP pages?
    I mean that include should go or not in runtime depending on the some condition.

    yes.

  • Dynamic include file in JSP page

    <span class="value">Hi
    i have index.jsp , this page can include jsp
    pages dynamically by passing the name of the page to be included to the
    index page with out .jsp , so if i want to include page "code.jsp" i
    put: .../index.jsp?page=code , this have to include code.jsp page
    i made the following code , but it did not find the file
    so can any one help plz ?
            String pg=request.getParameter("page");
            if( pg!= null && ! "".equals(pg)){
                    File f=new File(request.getParameter("page")+".jsp");
                    if(f.exists()){
                            out.print("file exist");
                            %>
                            <jsp:include page="<%=request.getParameter("page")+".jsp" %>" />
            <%
                    }else{
                            out.print("file not exist");
         

    What does the file existing or not really have to do with it?
    You can try it like this:
    String pg=request.getParameter("page");
            if( pg!= null && ! "".equals(pg)){
                    String webPath = pg + " .jsp";
                    String realPath = request.getRealPath(webPath);
                    File f=new File(realPath);
                    if(f.exists()){
                            out.print("file exist");
                            %>
                            <jsp:include page="<%= webPath %>" />
            <%
                    }else{
                            out.print("file not exist");
            }Alternatively you could try using a request dispatcher:
    RequestDispatcher rd = request.getRequestDispatcher(webPath);
    if (rd == null){
      // doesn't exist
    }

  • Trying to dynamic include HTML into a JSP

    All,
    I am trying to include an HMTL file into a JSP file. I wish to do this dymanically. So, the following is not an option:
    <%@ include file="relativeURL" %>
    So, I am forced to resort to such measures as the following:
    <jsp:include page="<%=myPath%>"/>
    However, I get the following error:
    java.lang.IllegalStateException: Response has already been committed
         at java.lang.Throwable.fillInStackTrace(Native Method)
         at java.lang.Throwable.fillInStackTrace(Compiled Code)....
    I tried it like this:
    <jsp:include page="<%=myPath%>" flush="true"/>
    I encoutered the same result. I have JSP 1.2 running Tomcat 3.1 with Apache 1.3.14, all on SunOS. Thanks in advance for any help.
    Nicholas

    One of the worst error messages you can get is the IllegalStateException. It simply means that an attempt has been made to forward or include but only a portion of the include was sent. In a situation like this the best way to handle the dynamic page content is to include it from a Servlet by sending the information you need through beans. Including the Servlet rather than the dynamic path would clear those errors right up. One thing to keep in consideration is that you can't just get the page and display it, you have to buffer it in so the state can be kept alive without timing out like it does with the dynamic include.
    Hope that helps. Been there, done that, I know how frustrating the error was.

  • Dynamically include jsp:param

    Is it possible to include <jsp:param> inside <jsp:forward> dynamically? There are two ways:
    1)
    <jsp:forward ...>
    <% if (...) { %>
         <jsp:param ... />
    <% } %>
    </jsp:forward>
    2)
    <jsp:forward ...>
    <util:if predicate="...">
         <jsp:param ... />
    </util:if>
    </jsp:forward>
    assuming <util:if> is some kind of conditional evaluation tag.
    The JSP 1.2 pfd2 says:
    The jsp:param element is used to provide key/value information. This element is
    used in the jsp:include , jsp:forward and jsp:params elements. A translation
    error shall occur if the element is used elsewhere.
    This seems to indicate that 2) is not allowed, but it is not clear whether or not 1) is allowed.
    I think it is desirable to allow both methods of dynamically including jsp:param elements.
    Any comments?

    1. doesn't work. You're not allowed to have <% %> scriplets inside of a jsp:forward tag. You can however include <%= %> tags. So you could set the value of a parameter dynamically and include the in the jsp:param tag
    2. I don't know about.
    -Derek

  • How i will dynamically include jsp pages in a dynamic richfaces tab?

    Hello experts,
    I am unable to include jsp in dynamically created richfaces tab
    i am able to create the tabs sucessfully,but could not include the jsps in these tabs
    Please help???
    following is the code
              HtmlTab t;
                   t = new HtmlTab();
                   t.setId(id);
                   t.setName(id);
                                                    IncludeTag in=new IncludeTag();
                                                    t.setData(in);
                                                    tabpanel.getChildren().add(t);

    Another approach is to parse the blog's RSS feed into your HTML page with a PHP script.
    This is your wife's RSS feed:
    http://ninjabaker1.blogspot.com/feeds/posts/default?alt=rss
    Feed for All has a free script.  I just tested it and it seems to work ok with Blogger's RSS.
    http://www.feedforall.com/free-php-script.htm
    Nancy O.
    Alt-Web Design & Publishing
    Web | Graphics | Print | Media  Specialists 
    http://alt-web.com/
    http://twitter.com/altweb

  • How can I do a dynamic include of a page fragment?

    I have a technical support website with a lot of simple html pages. What I want to do is hyperlink from the index page to another page, which would display these html pages as a page fragment, dynamically based on a session bean set by the hyperlink.
    I basically want to do this, if it was possible:
    <jsp:directive.include file="#{SessionBean1.pageToDisplay}"/>
    Now the FAQ's has a topic "How can I do a dynamic include of a page fragment?", which would seem to answer my question.
    But this is all it says, and it makes no sense to me. Could someone please translate? :)
    "Using a page fragment file (but using instead of the usual Creator approach) will accomplish a dynamic include."

    Here is 1 solution:
    First add this to the jsp:root tag:
    xmlns:c="http://java.sun.com/jsp/jstl/core"
    Then surround the page fragment directive with something like this:
                            <div style="position: absolute; left: 24px; top: 408px">
                                <c:if test="${SessionBean1.count > 0}">
                                    <jsp:directive.include file="testPF.jspf"/>
                                </c:if>
                            </div>

  • How can i include a jsp file in servlet?

    hi
    i generate a dynamic page from servlet.
    i need to include a jsp file in same servlet.
    i try like this --
    out.println("<HTML>");
    out.println("<HEAD><TITLE>First</TITLE></HEAD>");
    out.println("<BODY>");
    out.println("<%@ include file=\"abc.jsp\">");
    out.println("<FORM>");
    out.println("</FORM>");
    out.println("</BODY>");
    out.println("</HTML>");

    Replace your line with
    RequestDispatcher rd = request.getRequestDispatcher("abc.jsp");
    rd.include(request, response);

  • How to include more jsp?

    Hi,
    I've header.jsp, footer.jsp, content.jsp (which is loaded dynamically) and a main.jsp. I would include all jsp into main.jsp.
    This is the header.jsp
    <div id="logo" align="top">
    <img src="http://www.company.com/images/logo-red.gif"/>
    <div class="user-info">Welcome, <h:outputText value="#{user.email}"/></div>
    </div>
    The footer.jsp is
    <div id="footer">
    <div id="footer-copyright">Copyright &copy; 2006 MyCompany, Inc.</div>
    </div>
    The content.jsp is
    <h:dataTable value="#{controller.renderedSteps}" var="vitem"
    rowClasses="stepdescription-text">
    <h:column>
    <h:outputText id="stepDescription" value="#{vitem.step.description}"/>
    </h:column>
    <h:column>
    <h:commandButton value="next step"
    action="#{controller.nextStep}"
    rendered="#{vitem.isRendered}"
    disabled="#{vitem.isDisabled}" />
    </h:column>
    </h:dataTable>
    The body of main.jsp is
    <body>
    <f:view>
    <h:panelGrid>
    <jsp:include page="header.jsp"/>
    <jsp:include page="content.jsp"/>
    <jsp:include page="footer.jsp"/>
    </h:panelGrid>
    </f:view>
    </body>
    The problem is that when I load the main.jsp seems that the <div> are ignored.
    I'm very new in JSF and JSP\HTML.
    Thanks

    Use f:subview and use f:verbatim.
    First, f:verbatim... This JSF tag allows you to write HTML verbatim to your page. Whenever you have an HTML tag in any included page from a JSF app, it must be wrapped in f:verbatim. It is also good practice to use f:verbatim in your main page too, though it is not absolutely required. Do not wrap JSF tags in f:verbatim, it will not work.
    A general rule of thumb is to attempt to use as little HTML as possible. The JSF tag set with CSS actually eliminates the need for a great deal of HTML. I suggest picking up a good book that explains each component in the JSF library. Such as Core JavaServer Faces by David Geary and Cay Horstmann. Some free chapters can be found here (Check out "Basic Standard Components): http://www.horstmann.com/corejsf/
    Seconly, use f:subview when including a page. Either inside the included JSP or around the include statement. Like so:
    <f:subview id="header">
        <jsp:include page="header.jsp"/>
    </f:subview>
    OR
    <f:subview id="header">
    <f:verbatim><div id="logo" align="top">
    <a href="http://www.mycompany.com/">
    <img src="http://www.company.com/images/logo-red.gif"/>
    </a>
    <div class="user-info">Welcome, </f:verbatim><h:outputText value="#{user.email}"/><f:verbatim></div>
    </div></f:verbatim>
    </f:subview>For more information, check out this related forum posting:
    http://forum.java.sun.com/thread.jspa?threadID=715984&start=10&tstart=0
    Hope this helps!
    CowKing

  • How to create a dynamic include

    I would like to construct a dynamic include depending on URL searchstring data. In my mind it looks like this:
    <%@ include file = request.getParameter("subnav")+".jsp" %>
    but for my Server it�s more like this :-))
    index.jsp(110,25) Attribute value should be quoted
    It might be a problem on the execution time of the include command but I don�t know how to get around it.
    Elmar

    The JSP's include directive (<%@ include) can be used to include files at the translate stage. So, you can't parameterize the file name. But the JSP's include tag (<jsp:include...) includes the file at runtime and hence you can parameterize it as I have shown in my earlier reply.
    Hope this helps. And this is the solution I believe.
    Sudha

  • Include a jsp in another

    I wanr to include a jsp into another, but dinamically. I have a file named Inicio.jsp. This file has a link that calls the servlet "ServletMenu". This servlet decides which jsp page to load. But I want to load "inside" the Inicio.jsp.
    Here a send some code
    Inicio.jsp: shows a menu
    <tr>
    <td>Menu 1</td>
    </tr>
    ServletMenu
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    String operacion = (String)request.getParameter("operacion");
    if(operacion.equalsIgnoreCase("menu1")) {
    RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/WebModulo1/Menu1");
    dispatcher.forward(request, response);
    Menu1 contains a form
    The page given by the servlet should show everything that is shown in Inicio.jsp and in the middle of the page should be the content of the Menu1.jsp.
    Am I clear? The idea is mantain a fix menu and load only dynamic content in the middle of the page.
    hope you can help

    I have the code working but ServletMenu only loads the Menu1.jsp and that is not what I want.
    I' m developing an Intranet site. Depending on the user that is logged, the menu that is shown, because not all users have access to all the system tasks.
    I thought of having the pages containing the menu shown to the user done statically and in the middle of that statical page load the content of a dynamic page.
    For example, suppose I have in the server the pages Inicio.jsp, that shows the menu, and Menu1.jsp that shows the same things that Inicio.jsp (but the link to menu1should not exit) and whatever is loaded when the user clicks in the link menu1 of the Inicio.jsp page. The "whatever is loadded" will be another .jsp page, that should be inside Menu1.jsp.
    Hope I'm clearer this time
    Thanks

  • Dynamic include inside custom tag body

    I am trying to perform the dynamic include of another JSP from within the body of a custom tag using JSP1.1. It cannot be done using <jsp:include> since flush=true is required and thus an exception is thrown when called from inside the body of a custom tag - it can be done in JSP1.2 since flush does not have to be set to true but upgrading is not possible at this time.
    Does anyone know of any custom tag or the code needed to perform this function with JSP1.1?
    I am using Tomcat 3.2.3.
    Using a RequestDispatcher and calling include() does not have the desired effect since the output is witten directly to the response and does not go into the correct position in the calling JSP.
    I think the solution involves making a call to the included JSP (is it possible to use a RequestDispatcher that doesn't write directly to the page output stream?) and then append the response to the BodyContent object which is buffering the body content of the custom tag until the doAfterBody() method is called. Is it possible to create a dummy ServletResponse object to pass to the RequestDispatcher and then obtain the HTML response from the internal buffer?

    I don't know if there is a solution to the problem you are having with JSP 1.1. If you look in the spec, it actually warns you that dynamic includes can not be done inside a body tag. The spec actually states that the included code shout write directly to the response and not to the BodyContent.
    I was excited to find out they had fixed this in JSP 1.2, but they seem to have foiled me again. If my tag calls PageContext.include(), the spec says that include must call the flush method, which causes BodyContent to throw an exception since flush is not a valid call.

  • JSF dynamic include and custom tag

    Anybody has experience to enclude custom tags between <f:verbatim> </f:verbatim> ? The custom code embeded this tags won't work, my code as below:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <%-- jsf:pagecode language="java" location="/JavaSource/pagecode/jsp/Server_request.java" --%><%-- /jsf:pagecode --%>
    <%@taglib uri="http://www.ibm.com/jsf/html_extended" prefix="hx"%>
    <%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
    <%@taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
    <%@taglib uri="/WEB-INF/mytaglib.tld" prefix="first" %>
    <HTML>
    <HEAD>
    <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
         pageEncoding="ISO-8859-1"%>
    <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <META name="GENERATOR" content="IBM Software Development Platform">
    <META http-equiv="Content-Style-Type" content="text/css">
    <LINK href="../theme/Master.css" rel="stylesheet"
         type="text/css">
    <TITLE>server_request.jsp</TITLE>
    <LINK rel="stylesheet" type="text/css" href="../theme/stylesheet.css"
         title="Style">
    </HEAD>
    <f:view>
         <BODY><hx:scriptCollector id="scriptCollector1">
         <P><hx:outputLinkEx styleClass="outputLinkEx" value="header"
                   id="linkEx1">
                   <h:outputText id="text1" styleClass="outputText" value="Header"></h:outputText>
              </hx:outputLinkEx><BR></P>
    <jsp:include page="server_req.jsp"/>
              <hx:outputLinkEx styleClass="outputLinkEx" value="Footer" id="linkEx2">
                   <h:outputText id="text2" styleClass="outputText" value="Footer"></h:outputText>
              </hx:outputLinkEx>
         </hx:scriptCollector></BODY>
    </f:view>
    </HTML>
    <%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
    <%@taglib uri="/WEB-INF/mytaglib.tld" prefix="first"%>
    <f:subview id="server_req">
    <f:verbatim>
    <first:hello/>
    </f:verbatim>
    </f:subview>

    I don't know if there is a solution to the problem you are having with JSP 1.1. If you look in the spec, it actually warns you that dynamic includes can not be done inside a body tag. The spec actually states that the included code shout write directly to the response and not to the BodyContent.
    I was excited to find out they had fixed this in JSP 1.2, but they seem to have foiled me again. If my tag calls PageContext.include(), the spec says that include must call the flush method, which causes BodyContent to throw an exception since flush is not a valid call.

  • Dynamically include variables...

    I have an application that is in 7 different languages. Based on client language setting I serve them up different content on the JSP pages. I basically have 7 resource files that look like this (each has different text for field1):
    <%
    String field1 = "English Text";
    %>
    I dynamically include this on each page like:
    <%
    String inc="includes/resources/"+ pageLang +".jsp";
    %>
    <jsp:include page="<%= inc %>" flush="true"/>
    This all works fine, no errors. The problem occurs when I try and call field1 on the main page:
    <%= field1 %>
    At this point I get an : Undefined variable: field1
    Does anyone have any idea why this would happen? Any ideas how to work around it?
    Thanks.

    You need to pass all your defined variables as parameters into your included jsp page. For this, you can use the following construct:
    <jsp:include page="spanish_content.jsp">     
       <jsp:param name="field1" value="<%= field1 %>" />     
    </jsp:include>These parameters can be then read in your included JSP by using the standard request.getParameter()-method. Unfortunately this requires you to convert your values into Strings and parse them back into their respective types inside the included page.
    You could also use the HttpSession to relay the parameters, although that may produce a bunch of problems. Do it like this in the including page:
    session.setAttribute( "field1", field1 );And in your included page:
    String field1 = (String) session.getAttribute( "field1" );For a better alternative for i18n, take a look at this:
    http://jakarta.apache.org/taglibs/doc/i18n-doc/intro.html
    .P.

Maybe you are looking for

  • Receipt Matching with Invoice (AP) - Line to be Checked by Default

    Hi, As per finance requirement, they need line to be checked by default in Match Receipt Window. Is there any option available? I did personalization for selecting check box value to 'Y'  and it is working. But that time it is not taking Qty Invoiced

  • Synchroniz​ing two counter frequency inputs with multiple analog inputs

    Hello all, I'm fairly new to LabVIEW and I'm trying to collec​t data from multiple sources with synchronized tim​ing on the acquisition but I'm having trouble figu​ring it out. My problem is that I've got two count​er frequency inputs, one optical ta

  • My NI-FBUS 4.0 disk will not read. Can I get a copy?

    My computer's hard drive crashed and my programs need to be re-installed, but my NI-FBUS 4.0 disk will not read. I suspect it is corrupted somehow. Can I buy/get a copy of the disk to match my USB FF interface?

  • Need Help, iPod died.

    Okay Im not exactly where to put this thread but I thought this would be fine sinec its general. Okay so awhile ago I got water in my iPod =/ Though miraculously it didn't die. I charged it up and it worked fine, except the click wheel won't work at

  • Add/Remove datagridview event from other class

    Hi, I have a 'Class A' which have a datagridview object with cellvaluechanged event. i pass this datagridview as byreference to 'Class B'. i need to remove/add the cellvaluechanged event of given datagridview object from 'Class B'. below is my code T