2

I have a jsp page containing a form where a user fills in some value. Now i pass these values into a servlet which processes it and retieves a related set of data. Now, i am able to retrieve the data in the servlet page, but am not able to display it on the same jsp page at which i fetched the request.


I do not want to use java code inside jsp. I wish to do the same using servlets only. I do not want to do something like this


<% if(rollno==null)
      // then display the form
   else 
      // process the request on the jsp page itself  
%>

I want to process all my reults in a servlet file and then dispaly the result on the jsp page by passing data from servlet to jsp. I am posting my code below :


<form id="form" method="post" action="searchServlet">
Student Roll No :<br><input type="text" value="" name="rollno"><br><br>
<input type="submit" value="SHOW DETAILS" />
</form>

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
            String rollno=request.getParameter("rollno");
            ResultSet rs=null;

            Class.forName("com.mysql.jdbc.Driver");  
            String url="jdbc:mysql://localhost/schooldatabase";
            Connection con = DriverManager.getConnection(url,"root","passwd");

            Statement st= (Statement) con.createStatement();
            String strquery="SELECT name,regno FROM `schooldatabase`.`student_info` WHERE rollno="+ rollno+ ";";

            if(!con.isClosed()) {
                rs=st.executeQuery(strquery);

                while(rs.next())
                {
                    out.println(rs.getString("name"));
                    out.println(rs.getString("regno"));
                }
            }

            else
            {    // The connection is closed 
            }
          }           

            catch(Exception e)
            {
                out.println(e);
            }

             finally {            
               out.close();
            }
}
Chitransh Saurabh
  • 377
  • 6
  • 12
  • 23

1 Answers1

4

You shouldn't be doing the presentation in the servlet. You should not have any of those lines in the servlet.

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

// ...
                out.println(rs.getString("name"));
                out.println(rs.getString("regno"));

// ...

            out.println(e);

You should instead be storing the data in a sensible collection and be setting it as a request attribute and finally forward the request/response to a JSP which in turn generates the proper HTML around all those data. Something like this:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        List<Student> students = studentDAO.find(request.getParameter("rollno"));
        request.setAttribute("students", students); // Will be available as ${students} in JSP
        request.getRequestDispatcher("/WEB-INF/students.jsp").forward(request, response);
    } catch (SQLException e) {
        throw new ServletException("Cannot obtain students from DB", e);
    }
}

with this in the students.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
    <c:forEach items="${students}" var="student">
        <tr>
            <td>${student.name}</td>
            <td>${student.regno}</td>
        </tr>
    </c:forEach>
</table>

For a more concrete example, see also this answer: Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555