Aplikacja WWW - projekt - serwlety - Java Server Pages - 28.04.2009
Otworzyć projekt Project_I w środowisku NetBeans
Utworzyć bazę danych Access, utworzyć tabele: Person,.....
Utworzyć plikowy DNS do bazy.
package pss;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Display_Data_Servlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("<html><head>");
out.print("</head><body>");
out.print("<form action=\"");
out.print( req.getRequestURI() );
out.print("\" method=\"post\">");
out.print("<input type=\"submit\" ");
out.print("value=\" \"> ");
out.print("Display Records</form>");
out.print("</body></html>");
out.close();
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.print("<html><head>");
out.print("</head><body>");
out.print("<code><pre>");
out.print("<font color=green>ID\tFirst ");
out.println("Name\tLast Name\n</font>");
// debugging info
long time1 = System.currentTimeMillis();
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:pss_data");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM Data");
// displaying records
while(rs.next()) {
out.print(rs.getObject(1).toString());
out.print("\t");
out.print(rs.getObject(2).toString());
out.print("\t\t");
out.print(rs.getObject(3).toString());
out.print("\n");
}
} 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) {}
}
// debugging info
long time2 = System.currentTimeMillis();
out.print("</pre></code>");
out.print("<p>Search took : ");
out.print( (time2 - time1) );
out.print(" ms.</p>");
out.print("<p\"><a href=\"");
out.print( req.getRequestURI() );
out.print("\">Back</a></p>");
out.print("</body></html>");
out.close();
}
}
Zadanie
Utworzyć bazę danych Access - pss_baza oraz plikowy DNS do tej bazy.
Do strony głównej projektu dodać wpis z wywołaniem powyższego serwletu.
W podobny sposób wyświetlić dane z tabel: Person, Customer, Product, Problem.
Pliki: Display_Data_Servlet