从同一个jsp文件中的数据库中检索数据到表中

时间:2014-02-27 12:05:04

标签: jsp servlets

嗨我正在使用jsp和servlet,我的问题是将数据从数据库检索到同一个jsp文件中我在jsp file.i中有两个表。我想把数据放到第二个表中。所以请帮我修补。下面是我的代码

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="com.sun.xml.internal.txw2.Document"%><html>
<%@page import="java.io.IOException" %>
<%@page import="java.io.PrintWriter" %>
<%@page import="java.sql.Connection" %>
<%@page import="java.sql.DriverManager" %>
<%@page import="java.sql.Statement" %>
<%@page import="java.sql.ResultSet" %>
<%@page import="javax.servlet.ServletException" %>
<%@page import="javax.servlet.http.HttpServlet" %>
<%@page import="javax.servlet.http.HttpServletRequest" %>
<%@page import="javax.servlet.http.HttpServletResponse" %>

second table

<%  
Class.forName("com.mysql.jdbc.Driver");

System.out.println("driver loaded");
System.out.println("Driver is loaded");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/charms?user=root&password=root");
System.out.println("Connection created");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from dealer_masters");%>

<table align="center" border="1">

  <tr>
    <td>Dealer Id</td>
    <td>Dealer Name</td>
    <td>Door no</td>
    <td>Street</td>
    <td>City</td>
    <td>District</td>
    <td>State</td>
    <td>Mobile</td>
    <td>Contact Person</td>
    <td>Phone No</td>

  </tr>
   <% while (rs.next()) {%>
  <tr>
   <td><%=rs.getString("deal_id_v")%></td>
    <td ><%=rs.getString("deal_name_v") %></td>
    <td><%=rs.getString("deal_door_no_v") %></td>
    <td><%=rs.getString("deal_street_v") %></td>
    <td><%= rs.getString("deal_city_v") %></td>
    <td><%= rs.getString("deal_district_v")%></td>
    <td><%= rs.getString("deal_state_v")%></td>
    <td ><%=rs.getString("deal_mobile_no_v")%></td>
    <td><%=rs.getString("deal_contactperson_v") %></td>
    <td><%=rs.getString("deal_phone_no_v") %></td>

  </tr>
 <%}%>
</table>
</form>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

您可以使用Jstl标签简化您的代码。请参阅下面的链接

答案 1 :(得分:0)

我有一个更好的解决方案...也许...有一个jsp文件获取用户名和密码。然后将信息传递到servlet,以便从mySQL数据库进行处理和数据检索...将数据存储到arrayList中,并将其传递到jsp文件进行显示。这是一些代码... Servlet文件。

public class myActorServlet extends HttpServlet {

private static final long serialVersionUID = 1L;
private String name;
private String user;
private String pass;
private String given_table;
private String tid;
private String firstname;
private String lastname;
private String action;

@Override
public void doPost(HttpServletRequest request,
        HttpServletResponse response)
        throws IOException, ServletException {

    response.setContentType("text/html");

    // connecting to database
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;

    PrintWriter out = response.getWriter();
    name = request.getParameter("screenName");
    user = request.getParameter("username");
    pass = request.getParameter("password");
    tid = request.getParameter("tid");
    firstname = request.getParameter("firstname");
    lastname = request.getParameter("lastname");
    action = request.getParameter("action");
    given_table = request.getParameter("tableName");

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet JDBC</title>");
    out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Hello, " + name + " </h1>");
    out.println("<h1>Servlet JDBC</h1>");

    /////////////////////////
    // init connection object
    String sqlSelect = "SELECT * FROM `" + given_table + "`";
    String sqlInsert = "INSERT INTO `" + given_table + "`(`firstName`, `lastName`) VALUES ('" + firstname + "', '" + lastname + "')";
    String sqlUpdate = "UPDATE `" + given_table + "` SET `firstName`='" + firstname + "',`lastName`='" + lastname + "' WHERE `id`=" + tid + "";
    String sqlDelete = "DELETE FROM `" + given_table + "` WHERE `id` = '" + tid + "'";

    //////////////////////////////////////////////////////////
    out.println(
            "<p>Reading Table Data...Pass to JSP File...Okay<p>");

    ArrayList<Actor> list = new ArrayList<Actor>();
    // connecting to database
    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/javabase", user, pass);
        stmt = con.createStatement();
        rs = stmt.executeQuery(sqlSelect);
        // displaying records

        while (rs.next()) {
            Actor actor = new Actor();
            actor.setId(rs.getInt("id"));
            actor.setLastname(rs.getString("lastname"));
            actor.setFirstname(rs.getString("firstname"));
            list.add(actor);
        }
        request.setAttribute("actors", list);
        RequestDispatcher view = request.getRequestDispatcher("myActors_1.jsp");
        view.forward(request, response);

    } catch (SQLException e) {
        throw new ServletException("Servlet Could not display records.", e);
    } catch (ClassNotFoundException e) {
        throw new ServletException("JDBC Driver not found.", e);
    } finally {
        try {
            if (rs != null) {
                rs.close();
                rs = null;
            }
            if (stmt != null) {
                stmt.close();
                stmt = null;
            }
            if (con != null) {
                con.close();
                con = null;
            }
        } catch (SQLException e) {
        }
    }
    out.println("</body></html>");

    out.close();
}

}

显示是在servlet调度并查看的JSP文件中完成的。

<html>
    <%
        //Actor actor = new Actor();
        ArrayList<Actor> list = new ArrayList<Actor>();
        list = (ArrayList<Actor>) request.getAttribute("actors");
    %>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Actor</title>
</head>

<body>

    <h2>This is Actor Class</h2>
    <table>
        <thead>
            <tr>
                <th>Id</th>
                <th>First Name</th>
                <th>Last Name</th>
            </tr>
        </thead>
        <tbody>
            <% for(int i = 0; i < list.size(); i++) {
                Actor actor = new Actor();
                actor = list.get(i);
                //out.println(actor.getId());
                //out.println(actor.getFirstname());
                //out.println(actor.getLastname());
            %>


            <tr>
                <td><%=actor.getId()%></td>
                <td><%=actor.getFirstname()%></td>
                <td><%=actor.getLastname()%></td>
               </tr>
            <%
            };
            %>
        </tbody>
    </table>

</body>

使用JSP文件中以html格式完成的标准输入形式输入来自用户的输入。...

<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>MySQL Database Website</title>
</head>
<body>
    <h1>Hello World!</h1>
    <!DOCTYPE html>
<html>
    <head>
        <title>Entry form</title>
    </head>
    <body>
        <h1>Entry Form</h1>
        <form name="InputForm" action="myActorServlet" method="Post">
            <table>
                <tbody>
                    <tr>
                        <td>Table:</td>
                        <td><input type="radio" name="tableName" value="product"/>Produce
                        <<input type="radio" name="tableName" value="customer" />Customer
                             <input type="radio" name="tableName" value="actor"  checked="checked" />Actor</td>
                    </tr>
                    <tr>
                        <td>Enter your name:</td>
                        <td><input type="text" name="name" /></td>
                    </tr>
                    <tr>
                        <td>Enter screen name:</td>
                        <td><input type="text" name="screenName" /></td>
                    </tr>
                    <tr>
                        <td>
                            Database Username:
                        </td>
                        <td>
                            <input type="text" name="username" size="30"/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Database Password:
                        </td>
                        <td>
                            <input type="password" name="password" size="30"/>
                        </td>
                    </tr>

                </tbody>
            </table>
            <input type="submit" name="submit" value="Submit"/>
            <input type="reset" name="clear" value="Clear" />
        </form>
    </body>
</html>