19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

}<br />

// Set the action for processing the answers<br />

out.println("");<br />

out.println("");<br />

out.println("");<br />

}<br />

out.close(); // Close stream<br />

/** Process the HTTP Post request */<br />

public void doPost(HttpServletRequest request, HttpServletResponse<br />

response) throws ServletException, IOException {<br />

// Set response type and output stream <strong>to</strong> the browser<br />

response.setContentType("text/html");<br />

PrintWriter out = response.getWriter();<br />

}<br />

// Obtain the HttpSession<br />

HttpSession httpSession = request.getSession();<br />

// Get the Address object in the HttpSession<br />

Address address = (Address)(httpSession.getAttribute("address"));<br />

try {<br />

s<strong>to</strong>reStudent(address);<br />

out.println(address.getFirstName() + " " + address.getLastName()<br />

+ " is now registered in the database");<br />

out.close(); // Close stream<br />

}<br />

catch(Exception ex) {<br />

out.println("Error: " + ex.getMessage());<br />

}<br />

/** Initialize database connection */<br />

private void initializeJdbc() {<br />

try {<br />

// Load the JDBC driver<br />

Class.forName("<strong>com</strong>.mysql.jdbc.Driver");<br />

System.out.println("Driver loaded");<br />

}<br />

// Establish a connection<br />

Connection conn = DriverManager.getConnection<br />

("jdbc:mysql://localhost/javabook" , "scott", "tiger");<br />

System.out.println("Database connected");<br />

// Create a Statement<br />

pstmt = conn.prepareStatement("insert in<strong>to</strong> Address " +<br />

"(lastName, firstName, mi, telephone, email, street, city, "<br />

+ "state, zip) values (?, ?, ?, ?, ?, ?, ?, ?, ?)");<br />

}<br />

catch (Exception ex) {<br />

System.out.println(ex);<br />

}<br />

/** S<strong>to</strong>re an address <strong>to</strong> the database */<br />

private void s<strong>to</strong>reStudent(Address address) throws SQLException {<br />

pstmt.setString(1, address.getLastName());<br />

40

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!