📄 studentdbservlet.java
字号:
// File: StudentDBServlet.java
// Listing 3
//
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import shod.register.*;
/**
* This servlet provides data entry and retrieval of
* student data in a database. <p>
*
* The server administrator/web-master can pass arguments to
* the servlet at loading/intialization time by specifying the
* arguments as part of the server configuration. <p>
*
* Servlet Parameters
* <ul>
* <li>dbDriver - name of the database driver class name (ie sun.jdbc.odbc.JdbcOdbcDriver)
* <li>dbURL - complete database URL (ie jdbc:odbc:StudentDatabase)
* <li>userid - user id
* <li>passwd - password
* </ul>
*
* Default Servlet Parameters <br>
* These values will be used if not provided.
* <ul>
* <li>dbDriver - sun.jdbc.odbc.JdbcOdbcDriver
* <li>dbURL - jdbc:odbc:StudentDatabase
* <li>userid - <none>
* <li>passwd - <none>
* </ul>
*
* @author Chad (shod) Darby, darby@j-nine.com
* @version 0.6, 5 Jan 1998 - 0.9, 31 July 1998
*
*/
public class StudentDBServlet extends HttpServlet implements SingleThreadModel
{
// data members
private String dbDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
private String dbURL = "jdbc:odbc:StudentDatabase";
private String userid = "";
private String passwd = "";
private StudentDataAccessor myDataAccessor = null;
private String CR = "\n";
/**
* This method is called the first time the servlet is loaded. Simply
* makes a connection to the database.
*/
public void init(ServletConfig config) throws ServletException
{
super.init(config);
System.out.println("StudentDBServlet init: Start");
String value = null;
// read in parameter value for dbDriver
if ( (value = config.getInitParameter("dbDriver")) != null )
{
dbDriver = value;
}
// read in parameter value for dbDriver
if ( (value = config.getInitParameter("dbURL")) != null )
{
dbURL = value;
}
// read in parameter value for used id
if ( (value = config.getInitParameter("userid")) != null )
{
userid = value;
}
// read in parameter value for dbDriver
if ( (value = config.getInitParameter("passwd")) != null )
{
passwd = value;
}
myDataAccessor = new StudentDataAccessor(dbDriver, dbURL, userid, passwd);
}
/**
* This method is used for applets.
*
* Receives and sends the data using object serialization.
*
* Gets an input stream from the applet and reads a student object. Then
* registers the student using our data accessor. Finally, sends a confirmation
* message back to the applet.
*/
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
ObjectInputStream inputFromApplet = null;
Student aStudent = null;
PrintWriter out = null;
BufferedReader inTest = null;
try
{
// get an input stream from the applet
inputFromApplet = new ObjectInputStream(request.getInputStream());
show("Connected");
// read the serialized student data from applet
show("Reading data...");
aStudent = (Student) inputFromApplet.readObject();
show("Finished reading.");
inputFromApplet.close();
// use our business object to register the student
// in the database
System.out.println(aStudent);
myDataAccessor.registerStudent(aStudent);
show("Complete.");
// send back a confirmation message to the applet
out = new PrintWriter(response.getOutputStream());
response.setContentType("text/plain");
out.println("confirmed");
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* This method is used by HTML clients and applets.
*
* Handles a request and reads information from HTML form data.
*
* Figures out if the HTML form is sending a request to register
* or display the students. Also, handles a request from an applet
* to simply display the students.
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
System.out.println("in doGet(...)");
String userOption = null;
userOption = request.getParameterValues("UserOption")[0];
System.out.println("userOption == " + userOption);
if (userOption == null)
{
// simply display the students
show("Displaying the students");
displayStudents(request, response);
}
else if (userOption.equals("Register"))
{
// register a new student into the database
registerStudent(request, response);
}
else if (userOption.equals("AppletDisplay"))
{
// begin applet communication to display students
System.out.println("userOption = " + userOption);
appletDisplayStudents(response);
}
}
/**
* This method is used for applets.
*
* Displays the students to the applet. This is accomplished by
* getting the student list and returning a vector of students. This
* vector is returned to the applet using object serialization.
*/
protected void appletDisplayStudents(HttpServletResponse response)
{
// build the student vector by accessing the database
System.out.println("okay, building vector");
Vector studentVector = myDataAccessor.getStudentList();
// send the student vector back to the applet using
// object serialization
System.out.println("sending response");
sendStudentList(response, studentVector);
}
/**
* This method is used for applets.
*
* Performs the nuts and bolts of sending the student list. The technique used is
* object serialization. The process is accomplished by opening an ObjectOutputStream
* to the client connection. This is accomplished via the HttpServletResponse parameter.
* Next the object is written to the client followed by flushing and closing the stream.
*
*/
protected void sendStudentList(HttpServletResponse response, Vector studentVector)
{
ObjectOutputStream outputToApplet;
try
{
outputToApplet = new ObjectOutputStream(response.getOutputStream());
System.out.println("Sending student vector to applet...");
outputToApplet.writeObject(studentVector);
outputToApplet.flush();
outputToApplet.close();
System.out.println("Data transmission complete.");
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
*
* This method is used for HTML clients.
*
* An HTML page is created that contains a list of students. This method
* is used to send back an HTML page to a servlet or CGI that requested a list
* of students.
*/
protected void displayStudents(HttpServletRequest request,
HttpServletResponse response)
{
Student aStudent = null;
try
{
show("inside displaying students");
// build the html page heading
String htmlHead = "<html><head><title>List of Students</title></head>" + CR;
// build the html body
String htmlBody = "<body><center>" + CR;
htmlBody += "<h1>Student List</h1>" + CR;
htmlBody += "<hr></center><p>" + CR;
// build the table heading
String tableHead = "<center><table border width=100% cellpadding=5>" + CR;
tableHead += "<tr>" + CR;
tableHead += "<th> </th>" + CR;
tableHead += "<th>Student Name</th>" + CR;
tableHead += "<th>E-mail</th>" + CR;
tableHead += "<th>Company</th>" + CR;
tableHead += "<th>Course Expectations</th>" + CR;
tableHead += "</tr>" + CR;
// execute the query to get a list of the students
Vector studentVector = myDataAccessor.getStudentList();
// build the table body
String tableBody = "";
int rowNumber = 1;
Enumeration enum = studentVector.elements();
while (enum.hasMoreElements())
{
aStudent = (Student) enum.nextElement();
tableBody += aStudent.toTableString(rowNumber);
rowNumber++;
}
// build the table bottom
String tableBottom = "</table></center>";
// build html page bottom
String htmlBottom = "</body></html>";
// build complete html page
htmlBody += tableHead + tableBody + tableBottom;
htmlBody += "<p><hr>";
htmlBody += "<center><a href=/StudentDB/index.html>Return to Course Home Page</a>";
htmlBody += "<p><i>" + this.getServletInfo() + "</i>";
htmlBody += "</center>";
String htmlPage = htmlHead + htmlBody + htmlBottom;
// now let's send this dynamic data
// back to the browser
PrintWriter outputToBrowser = new PrintWriter(response.getOutputStream());
response.setContentType("text/html");
outputToBrowser.println(htmlPage);
outputToBrowser.flush();
outputToBrowser.close();
show("finished");
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Build a student object based on the form data
*/
protected Student buildStudent(HttpServletRequest request)
{
Student theStudent = null;
try
{
String lastName = request.getParameterValues("LastName")[0];
String firstName = request.getParameterValues("FirstName")[0];
String email = request.getParameterValues("Email")[0];
String company = request.getParameterValues("Company")[0];
String dateString = request.getParameterValues("CourseStartDate")[0];
String courseTitle = request.getParameterValues("CourseTitle")[0];
String courseLocation = request.getParameterValues("CourseLocation")[0];
String expectations = request.getParameterValues("Expectations")[0];
theStudent = new Student(lastName, firstName, email, company,
dateString, courseTitle, courseLocation,
expectations);
}
catch (Exception e)
{
System.out.println(e);
}
return theStudent;
}
/**
* This method is used for students.
*
* Creates a new student based on the form data and registers the student
* in the database. Next, creates a confirmation page for the client.
*/
protected void registerStudent(HttpServletRequest request,
HttpServletResponse response)
{
// create a new student based on the form data
Student aStudent = buildStudent(request);
// now use the business object to insert data into the database
myDataAccessor.registerStudent(aStudent);
// build confirmation page
String htmlPage = "<html><head><title>Confirmation Page</title></head>";
htmlPage += "<body>";
htmlPage += "<center><h1>Confirmation Page</h1></center><hr>";
htmlPage += "The following information was entered successfully";
htmlPage += aStudent.toWebString();
htmlPage += "<hr>";
htmlPage += "<center><a href=/StudentDB/index.html>Return to Home Page</a> | ";
htmlPage += "<a href=/servlet/StudentDBServlet>View Student List</a>";
htmlPage += "<p><i>" + this.getServletInfo() + "</i>";
htmlPage += "</center></body></html>";
try
{
// now let's send this dynamic data
// back to the browser
PrintWriter outputToBrowser = new PrintWriter(response.getOutputStream());
response.setContentType("text/html");
outputToBrowser.println(htmlPage);
outputToBrowser.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Simply closes the database connection
*/
protected void cleanUp()
{
// close the database connections
myDataAccessor.cleanUp();
}
/**
* Destroys the servlet and calls cleanup to close the database connection
*/
public void destroy()
{
System.out.println("StudentDBServlet: destroy");
cleanUp();
}
/**
* Returns servlet information
*/
public String getServletInfo()
{
return "<i>Student Registration Servlet, v.06</i>";
}
/**
* Simple method for logging messages to the console.
*/
protected void show(String msg)
{
System.out.println(msg);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -