how to fetch data from servlet ????

how to fetch data from servlet ????

how to fetch data from servlet ????

View Answers

May 22, 2013 at 10:36 AM

hi friend,

Please explain what do you want to do exactly. Specify, from where you want to get data using servlet for example, whether from an html form, database, or from else where.

  1. getParameter(String name): A simple method of HttpServletRequest to get the value from an html form.

  2. How to get data from database : To get data from database you would have to first make a connection with database. To know more in detail how to get data from database using servlet you may go through the following links below, may this will be helpful for you

http://www.roseindia.net/jdbc/jdbcconnectivity.shtml

http://www.roseindia.net/servlets/databaseconnectionservlet.shtml

Thanks.


May 22, 2013 at 11:48 AM

view.jsp

<%@page import="java.sql.Statement"%> 
<%@page import="java.sql.DriverManager"%> 
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.ResultSet"%> 
<%@page contentType="text/html" pageEncoding="UTF-8"%> 

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>View</title>
    </head>
    <body>
      <center> 


}
          <h1>Welcome Madhab</h1>
          <form action="NewServlet" method="POST">
              <input type="submit" value="Click!">
          <table border="2">
  <tr>
    <th>S.No</th>
    <th>State</th>
    <th>Capital</th>
  </tr>
  <tr>
      <% try {ResultSet rs = (ResultSet) request.getAttribute("data"); 
     while (rs.next()) {%>             

  <td><input type="text" value="<%=rs.getString("state_id")%>"</td> 
<td><input type="text" value="<%=rs.getString("state_name")%>"</td>
<td><input type="text" value="<%=rs.getString("capital")%>"</td>
</tr> 
<% }} 
catch (Exception e) { 
                  } %>        
          </table> 
      </form>
</center> 
</body>

May 22, 2013 at 11:49 AM

view.serverlet

 try {       
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/state_capital_db", "root", "root");

        String query = "select * from state_details"; 
        Statement s = null; 
        s = (Statement) con.createStatement(); 
        ResultSet rs = null;  
        rs = s.executeQuery(query);  
        request.setAttribute("data", rs);  
        RequestDispatcher rd = request.getRequestDispatcher("view.jsp");  
        rd.forward(request, response);  

    } catch (Exception e) {       
        out.print(e.toString());   
    }
    finally {       
        out.close();
    }
    }
    }









Related Tutorials/Questions & Answers:

Ads