Hello. This is what i'm trying to do:

public class ComputeSearch extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter exit=response.getWriter();

exit.println("<%@ include file=\"GetByPath.jsp?path=1/2/5/\" %>");
    }
}

The problem is that the server does not compile that jsp line. It just prints it ! Any idea how to make it compile and use it as a link?

Dani AI

Generated

Short answer: printing a JSP directive from a servlet just sends plain text. The JSP include directive (<%@ include %>) is a translation-time (static) include, so it is handled when the JSP is translated — writing that string with response.getWriter() will not make the container compile or execute the JSP. Use a server-side dispatch instead: RequestDispatcher.forward(...) to hand the request to the JSP or RequestDispatcher.include(...) to merge the JSP output into the servlet response. (docs.oracle.com)

Example pattern (different from the code already posted in the thread):

req.setAttribute("path", "1/2/3");
RequestDispatcher rd = req.getServletContext().getRequestDispatcher("/WEB-INF/views/GetByPath.jsp");
rd.include(req, res);   // or rd.forward(req, res);

Pass data with request attributes (not getParameter) — attributes set with request.setAttribute(...) are available to the forwarded/included JSP. In the JSP prefer EL rather than scriptlets, for example Path: ${requestScope.path} (or use request.getAttribute("path") from scriptlets). (docs.oracle.com)

Troubleshooting tips: do not commit the response (call getWriter() and flush) before forward() — forward must occur before the response is committed. Verify the dispatcher path (relative vs. context-root differences) and check for a null RequestDispatcher if the path is wrong. If a true URL query string is required, use sendRedirect(...) (new request) or explicitly attach a query string to the dispatcher per the spec, but attributes are the safer, portable choice. (docs.oracle.com)

Acknowledgement: this expands on original attempt and the dispatcher advice from ; ’s example shows the same forward/include flow end-to-end.

Recommended Answers

All 8 Replies

Alex_ ,
It just print it. Do know request dispatcher?

I'm sorry? .. I don't think i know about a request dispatcher, haven't heard of.
I'm new to java/jsp, i've started learning it form zero 2 weeks ago.
Please tell me how can i make it compile the line instead of printing it. Please!

Thank you adatapost, but it's still not clear for me how to exactly do it, for i have tried the following :

public class ComputeSearch extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("path","1/2/3/");
request.setAttribute("chapter","ChTitle");
request.setAttribute("start","Number1");
request.setAttribute("end", "Number2");
RequestDispatcher dispatcher = request.getRequestDispatcher("/GetByPath.jsp");
  if (dispatcher != null)
 dispatcher.forward(request, response);
 else System.err.println("Error: dispathcer is null");
    }
}

.. and nothing happens. The url in the browser does change to the servlet's adress, but the page remains the same.

Do not use / root with resource name.

RequestDispatcher dispatcher = request.getRequestDispatcher("GetByPath.jsp");

Thanks!
I do the following in my jsp page :

String path= request.getParameter("path");

but it returns null. The parameters that where given to the servlet are still there in jsp, but not so for the new ones. Please tell, is there something i'm not doing right?

String path=(String) request.getAttribute("path");
EmmployeeList.java
-------------------

public class EmpList extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public EmpList() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }
    private ServletConfig config;
      //Setting JSP page
      String page="DataPage.jsp";
    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        List dataList = new ArrayList();  
        
        try{

            DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521","hr","hr");
            PreparedStatement ps = conn.prepareStatement("Select first_name,salary from employees WHERE salary < 2500");
            
//            ps.setInt(1,Integer.parseInt(args[0]));
            ResultSet rs = ps.executeQuery();
            while(rs.next()){

//                System.out.println(rs.getString(1)+" earns "+rs.getString(2));
                 dataList.add(rs.getString(1));
                 dataList.add(rs.getString(2));
              
            }
            rs.close();
        }
        catch(Exception e){
              System
        .out.println("Exception is ;"+e);
              }
              request.setAttribute("data",dataList);
              //Disptching request
              RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/empList.jsp");
              if (dispatcher != null){
                dispatcher.forward(request, response);
              } 
          
    }
        
    

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        //call the doGet method
        this.doGet(request, response);
        
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occure
     */
    public void init() throws ServletException {
        // Put your code here
        this.config=config;
    }

}


empList.jsp
------------
<table border="1" width="303">
<tr>
<td width="119"><b>ID</b></td>
<td width="168"><b>Message</b></td>
</tr>
<%Iterator itr;%>
<% List data= (List)request.getAttribute("data");
for (itr=data.iterator(); itr.hasNext(); )
{
    String name = (String)itr.next();
    String sal = (String)itr.next();
    out.println("<tr>");
    out.println("<td>" + name + "</td>");
    out.println("<td>" + sal + "</td>");
    out.println("<td><a href=EmpEdit1?id=" + name + ">Edit</a></td>");
    out.println("<td><a href=EmpDel1?id=" + name + ">Delete</a></td>");
    
%>

</tr>
<%}%>
</table>


EmpEdit1.java
--------------
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String id = request.getParameter("id");
        PrintWriter out = response.getWriter();
        
        out.println(id);
        
List dataList = new ArrayList();  
        String fname ="";
        String sal="";
        try{

            DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
            Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521","hr","hr");
            PreparedStatement ps = conn.prepareStatement("SELECT first_name,salary FROM employees WHERE salary<2500 AND first_name='"+id+"'");
            
//            ps.setInt(1,Integer.parseInt(args[0]));
            ResultSet rs = ps.executeQuery();
            while(rs.next()){

//                System.out.println(rs.getString(1)+" earns "+rs.getString(2));
                 fname = rs.getString(1);
                 sal = rs.getString(2);
                 dataList.add(rs.getString(1));
                 dataList.add(rs.getString(2));

                 out.println(fname);
                 out.println(sal);
                 
              
            }
            rs.close();
        }
        catch(Exception e){
              System
        .out.println("Exception is ;"+e);
              }
        request.setAttribute("data",dataList);
        request.setAttribute("fname",fname);
        request.setAttribute("sal",sal);
          //Disptching request

        
        RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/empEdit.jsp");
        
        if (dispatcher != null)
        dispatcher.forward(request, response);
        //response.sendRedirect("jsp/empEdit.jsp?id="+id);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.sendRedirect("empEdit.jsp");
    }

empEdit.jsp
-------------
<body>
    <form name="edit" action="empEdit" method="post">
      <html>
      <table border="1" cellspacing="2">
        <% List data= (List)request.getAttribute("data");
        String name = (String)request.getAttribute("fname");
        String sal = (String)request.getAttribute("sal");

    out.println("<tr>");
    out.println("<td>Employee Name </td>");
    out.println("<td><input type='text' name='name' value='" + name + "' /></td>");
    out.println("</tr>");
    out.println("<tr>");
    out.println("<td>Salary </td>");
    out.println("<td><input type='text' name='sal' value='" + sal + "' /></td>");
    out.println("</tr>");
    out.println("<tr>");
    out.println("<td align='right' colspan='2'><input type='submit' value='Save' /></td>");
    out.println("</tr>");    

    
%>
            </table>
        </html>
        <input type="hidden" name="id" value="<%="book.getId()"%>"> 
    </form>
  </body>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.