2011-02-13 101 views
6

內容我有這個servlet:包括一個jsp的一個servlet

public class SaveImage extends HttpServlet { 

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     PrintWriter out = null; 
     try { 
      out = response.getWriter(); 
      out.println("<html>"); 
      ... 

      // I want to include here the content of this jsp: 
      // /WEB-INF/mybox.jsp 
      // (also, with the full context of the servlet) 

      ... 
      out.println("</html>"); 
      out.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

有沒有做這件事(響應已承諾?)有問題,我該怎麼辦呢?

回答

12
request.getRequestDispatcher("/WEB-INF/my.jsp").include(request, response); 

但是,你不應該像這樣輸出html的servlet。只需使用jsp,即可使用<jsp:include /><%@ include file=".." %>

+0

很好謝謝。 – BenoitParis 2011-02-13 16:48:00

2

感謝ozho,您已幫助我爲2年的待定項目提供最終形狀。謝謝。 實際上,要將tomcat的請求從sun web服務器7重定向到應用程序服務器,由於jsp不直接在tomcat中顯示,所以技術是在app.config中使用passthrough並讓tomcat處理請求。

  import java.io.IOException; 

      import javax.servlet.RequestDispatcher; 
      import javax.servlet.ServletContext; 
      import javax.servlet.ServletException; 
      import javax.servlet.http.HttpServlet; 
      import javax.servlet.http.HttpServletRequest; 
      import javax.servlet.http.HttpServletResponse; 

      /** 
      * Servlet implementation class MY... Parvez Ahmad Hakim 
      */ 
      public class MY extends HttpServlet { 
       private static final long serialVersionUID = 1L; 

       /** 
       * @see HttpServlet#HttpServlet() 
       */ 
       public MY() { 
       super(); 
       // TODO Auto-generated constructor stub 
       } 

       /** 
       * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
       */ 
       protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  


        String pageName =request.getParameter("req");  
        if(pageName==null){ 
         pageName="IC_LIC_Login.jsp";// default page 
        } 
        request.getRequestDispatcher(pageName).include(request, response); 



       } 

       /** 
       * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
       */ 

       protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
        String pageName =request.getParameter("req");  

        request.getRequestDispatcher(pageName).include(request, response); 
       } 


      }