简体   繁体   中英

How to Include a JSP Fragment into a JSP Page while forwading from Servlet?

First, Please suggest me if my question heading is not correct.

Moving on to question: Say I am having below components:

search.jsp - A JSP Page with a Form to Submit Data

Search.java - A controller Servlet having both get() and post() defined separately so that it can acts as a dispatcher for path /search.jsp

searchResults.jspf - A Fragment with some JSTL code to show up the Search Results

What I want here is for every POST request the controller servlet has to do its calculation, set results as Request Attributes and than - forward the request to the view search.jsp that should include the Fragment after its own codes .

So that, I can have a View Defined in such a way as:

search.jsp
+
searchResults.jspf

on a single page.

Problem is, I can either do Forward or Include with the dispatcher as I don't know how can i Include a fragment while forwarding to a JSP into it.

Let me know if I need to post some code if necessary, or need any corrections.

In your search.jsp embed your searchResult.jsp using jsp:include:

<jsp:include page="searchResult.jsp"></jsp:include>

Exemple: 1. The servlet:

@WebServlet(name = "Servlet", urlPatterns = "/myForwardTest")
public class Servlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("search.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          doPost(request, response);
    }
 }
  1. search.jsp:

     <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>In search resust</title> </head> <body> Search.jsp embed searchResult.jsp <jsp:include page="searchResult.jsp" /> </body> </html> 
  2. searchResult.jsp

     <%@ page contentType="text/html;charset=UTF-8" language="java" %> <body> in searchResult </body> </html> 

You can include your jspf in your jsp like below:

<%@include file="searchResult.jspf" %>

you can set a statement to execute a certain section only if a particular test evaluates to true .

Ex:

if(.....==true){
<%@include file="searchResult.jspf" %>
}else{
<%@include file="someOther.jspf" %>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM