4

I am passing parameters from JSP page calendar.jsp to a servlet connect.java. In the Java class I am passing a query from a database. It retrievs data fine but I need it to print the result back to the JSP page.

I tried the following code but with an error at out.println().

@WebServlet("/calendar")
public class Connect extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
        String fromDate = request.getParameter("fromDate");
        String toDate = request.getParameter("toDate");
        System.out.println("fromDate---->"+fromDate);
        System.out.println("toDate---->"+toDate);
        String query = "SELECT action_time,user_action,user_ip,user_id FROM ksdi.login_detail where (action_time, action_time) OVERLAPS (DATE '"
                    + fromDate+ "',DATE '"+ toDate+ "'+ integer '1')" +
                    " order by action_time desc";

        Connection conn = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            conn = ConnectionUtil.getConnection();
            statement = conn.prepareStatement(query);
            resultSet = statement.executeQuery();

            if (resultSet.next()) {
                while (resultSet.next()) {
                    String action_time=resultSet.getString("action_time");
                    String user_action=resultSet.getString("user_action");
                    String user_ip=resultSet.getString("user_ip");
                    String user_id=resultSet.getString("user_id");
                    System.out.println((action_time) + " " + (user_action) + " "+(user_ip) + " "+(user_id) + " ");

                    response.setContentType("text/html");  
                    PrintWriter out = response.getWriter();  
                    out.println("action time"+((ResultSet) request).getString("action_time")+"<br />");  
                    RequestDispatcher view = request.getRequestDispatcher("calendar.jsp");  
                    view.forward(request,response);         
                }
            } else {
                System.out.println("not found");
            }
        } catch (SQLException e) {
            throw new ServletException("DB interaction failed", e);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
            if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
            if (conn != null) try { conn.close(); } catch (SQLException ignore) {}
        }
    }

}


Here is my JSP file:

<%@ page import="java.sql.*" %>
<%  String path = request.getContextPath();%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

    <script src="<%=path%>/js/calendar.js"></script>
    <link href="<%=path %>/css/calendar.css" rel="stylesheet">
</head>
<body>
<form action="calendar">
            <div class="container">
            From:<input  name="fromDate" type="text" class="calendarSelectDate" />
            To: <input   name="toDate"   type="text" class="calendarSelectDate" />
            <input type="submit" name="b1" value="Go">
        </div>          
<div id="calendarDiv"></div>


</form> 

</body>
</html>
informatik01
  • 16,038
  • 10
  • 74
  • 104
NewBee
  • 839
  • 7
  • 18
  • 42

3 Answers3

3

1) In your servlet code you are doing it wrong. You should either output using PrintWriter's println() or use RequestDispatcher's forward() method. But NOT both in the same servlet's method.

Quote from here: What is a request dispatcher and how do I use it?

Unlike the case with the 'include', the 'forward' discards the previous output that Servlet had written to the response.

See the examples in the above mentioned page.

And if you choose to use forward() then to pass the data previously retieved from your database, you can store that data in the request scope, i.e. set the request attributes, like

request.setAttribute("actionTime", action_time);

Of course you must do it before calling forward()!

Then in your JSP you can output that data using Expression Languge, like this:
test.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <h1>Testing the passed values</h1>
    <p>Action time: ${actionTime}</p>
    <!-- same way for other data -->
</body>
</html>


2) Another issue, in your servlet code there is a line that has this:
((ResultSet) request).getString("action_time")

Neaither ServletRequest nor HttpServletRequest has the method getString(). Although ResultSet has such method, but, in your case, it is pointless and wrong to cast a request to ResultSet.


P.S.
Using scriplets in JSP is discouraged

Community
  • 1
  • 1
informatik01
  • 16,038
  • 10
  • 74
  • 104
  • RequestDispatcher is only passing one result to jsp but i have multiple results that i am fetching from database/// – NewBee Feb 19 '13 at 11:15
  • 1
    @IshanKaushik Request dispatcher **forwards the request, not the result**. And in the _request_, you can set as many attributes as you like. Plus you can put all the results in some JavaBean, using **DTO** pattern (read here: [**Data Transfer Object**](http://en.wikipedia.org/wiki/Data_Transfer_Object)). Also read the article I gave the link for in my answer. Plus read some tutorials, like [Beginning & Intermediate Servlet & JSP Tutorials](http://courses.coreservlets.com/Course-Materials/csajsp2.html), and [Java Servlets](http://www3.ntu.edu.sg/home/ehchua/programming/java/JavaServlets.html). – informatik01 Feb 19 '13 at 15:28
0

The could is casting the returned HttpServletRequest request to a ResultSet, I think it should use the ResultSet's getString method with no casting.

   PrintWriter out = response.getWriter();  
   out.println("action time"+ resultSet.getString("action_time") + "<br />");  
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
0

Well set the values you fetch into httprequest like this in the servlet

PS: i have commented unnecessary lines

   //response.setContentType("text/html");  
     //PrintWriter out = response.getWriter();  
    // out.println("action time"+((ResultSet) request).getString("action_time")+"<br />"); 

        request.setAttribute("action_time",action_time);
        request.setAttribute("user_action",user_action);
        request.setAttribute("user_ip",user_ip);
        request.setAttribute("user_id",user_id);


     RequestDispatcher view = request.getRequestDispatcher("calendar.jsp");  
    view.forward(request,response);  

And in calendar.jsp to which you forward , access the values by

<%= request.getAttribute("action_time")%>
<%= request.getAttribute("user_action")%>
<%= request.getAttribute("user_ip")%>
<%= request.getAttribute("user_id")%>
Sudhakar
  • 4,823
  • 2
  • 35
  • 42