Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Week05 Folder:
SurveyServlet:
SurveyServlet.java
// A Web-based survey that uses JDBC from a servlet.
//
import
import
import
import
import
import
import
import
import
import
import
import
import
java.io.PrintWriter;
java.io.IOException;
java.sql.Connection;
java.sql.DriverManager;
java.sql.Statement;
java.sql.ResultSet;
java.sql.SQLException;
javax.servlet.ServletConfig;
javax.servlet.ServletException;
javax.servlet.UnavailableException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
public class SurveyServlet extends HttpServlet
{
private Connection connection;
private Statement statement;
// set up database connection and create SQL statement
public void init( ServletConfig config ) throws
ServletException
{
// attempt database connection and create Statement
try
{
/*
Class.forName( config.getInitParameter( "databaseDriver" )
);
connection = DriverManager.getConnection(
config.getInitParameter( "databaseName" ),
config.getInitParameter( "username" ),
config.getInitParameter( "password" ) );
*/
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager.getConnection(
"Jdbc:Odbc:CT390", "","");
// create Statement to query database
statement = connection.createStatement();
} // end try
// for any exception throw an UnavailableException to
// indicate that the servlet is not currently
available
catch ( Exception exception )
{
exception.printStackTrace();
throw new UnavailableException(
exception.getMessage() );
} // end catch
} // end method init
// process survey response
protected void doPost( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
// set up response to client
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
// start XHTML document
out.println( "<?xml version = \"1.0\"?>" );
out.printf( "%s%s%s", "<!DOCTYPE html PUBLIC",
" \"-//W3C//DTD XHTML 1.0 Strict//EN\"",
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1strict.dtd\">\n" );
out.println(
"<html xmlns = \"http://www.w3.org/1999/xhtml\">"
);
// head section of document
out.println( "<head>" );
// read current survey response
int value =
Integer.parseInt( request.getParameter( "animal" )
);
String sql;
// attempt to process a vote and display current
results
try
{
// update total for current survey response
sql = "UPDATE survey SET votes = votes + 1 " +
"WHERE id = " + value;
statement.executeUpdate( sql );
// get total of all survey responses
sql = "SELECT sum( votes ) FROM survey";
ResultSet totalRS = statement.executeQuery( sql );
totalRS.next(); // position to first record
int total = totalRS.getInt( 1 );
// get results
sql = "SELECT surveyoption, votes, id FROM
surveyresults " +
"ORDER BY id";
ResultSet resultsRS = statement.executeQuery( sql
);
out.println( "<title>Thank you!</title>" );
out.println( "</head>" );
out.println( "<body>" );
out.println( "<p>Thank you for participating." );
out.println( "<br />Results:</p><pre>" );
// process results
int votes;
while ( resultsRS.next() )
{
out.print( resultsRS.getString( 1 ) );
out.print( ": " );
votes = resultsRS.getInt( 2 );
out.printf( "%.2f", ( double ) votes / total *
100 );
out.print( "% responses: " );
out.println( votes );
} // end while
resultsRS.close();
out.print( "Total responses: " );
out.print( total );
// end XHTML document
out.println( "</pre></body></html>" );
out.close();
} // end try
// if database exception occurs, return error page
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
out.println( "<title>Error</title>" );
out.println( "</head>" );
out.println( "<body><p>Database error occurred. "
);
out.println( "Try again later.</p></body></html>"
);
out.close();
} // end catch
} // end method doPost
// close SQL statements and database when servlet
terminates
public void destroy()
{
// attempt to close statements and database
connection
try
{
statement.close();
connection.close();
} // end try
// handle database exceptions by returning error to
client
catch( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
} // end method destroy
} // end class SurveyServlet
SurveyServlet.html
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Survey</title>
</head>
<body>
<form method = "post" action =
"/SurveyServlet/SurveyServlet">
<p>What is your favorite pet?</p>
<p>
<input type = "radio" name = "animal"
value = "1" />Dog<br />
<input type = "radio" name = "animal"
value = "2" />Cat<br />
<input type = "radio" name = "animal"
value = "3" />Bird<br />
<input type = "radio" name = "animal"
value = "4" />Snake<br />
<input type = "radio" name = "animal"
value = "5" checked = "checked" />None
</p>
<p><input type = "submit" value = "Submit" /></p>
</form>
</body>
</html>
JdbcDemo:
JdbcDemo1.java
/**
* @(#)JdbcDemo1.java
*/
import java.sql.*;
//import java.io.*;
class JdbcDemo1
{
Connection con;
Statement stmt;
ResultSet rs;
String sql, sql2, sql3, sql4, sql5;
public JdbcDemo1()
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(
"Jdbc:Odbc:CT390", "","");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM temp");
sql = "UPDATE temp SET age = age + 1 ";
//sql = "SELECT sum( age ) FROM temp";
//ResultSet totalRS = stmt.executeQuery( sql );
//totalRS.next(); // position to first record
//int total = totalRS.getInt( 1 );
//System.out.println(total);
while (rs.next())
{
String sName = rs.getString("name");
int iAge = rs.getInt("age");
System.out.println("Name: " + sName + " Age:
" + iAge);
}
sql = "UPDATE temp SET age = age + 1 ";
sql2 = "DELETE From temp Where name= 'Sam'";
sql3 = "INSERT into temp Values('Mary', 31)";
sql4 = "CREATE TABLE someTable(
name
VARCHAR(254)," +
"age
SMALLINT,"
+
"id INT,"
+
"salary
DOUBLE," +
"hiredate
DATE)";
sql5 = "DROP TABLE someTable";
stmt.executeUpdate(sql);
stmt.executeUpdate(sql2);
stmt.executeUpdate(sql3);
//stmt.executeUpdate(sql5);
stmt.executeUpdate(sql4);
con.commit();
con.close();
}
catch(SQLException e)
{
System.out.println("SQL Error " + e);
}
catch(ClassNotFoundException e)
{
System.out.println("Class Not Found Error: " +
e);
}
}
}
class JdbcDemo
{
public static void main(String args[])
{
new JdbcDemo1();
}
}
JavaBeans:
UserBean.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package my;
import java.beans.*;
import java.io.Serializable;
/**
*
* @author Your name
*/
public class UserBean implements Serializable {
public static final String PROP_SAMPLE_PROPERTY =
"sampleProperty";
private
private
private
private
String
String
String
String
sampleProperty;
ID;
fName;
lName;
private PropertyChangeSupport propertySupport;
public UserBean() {
propertySupport = new PropertyChangeSupport(this);
}
public String getSampleProperty() {
return sampleProperty;
}
public void setSampleProperty(String value) {
String oldValue = sampleProperty;
sampleProperty = value;
propertySupport.firePropertyChange(PROP_SAMPLE_PROPERTY,
oldValue, sampleProperty);
}
public void
addPropertyChangeListener(PropertyChangeListener listener)
{
propertySupport.addPropertyChangeListener(listener);
}
public void
removePropertyChangeListener(PropertyChangeListener
listener) {
propertySupport.removePropertyChangeListener(listener);
}
// setters
public void setID (String ID)
{
this.ID = ID;
}
public void setfName (String fName)
{
this.fName = fName;
}
public void setlName (String lName)
{
this.lName = lName;
}
// getters
public String getID() { return this.ID;}
public String getfName() { return this.fName;}
public String getlName() { return this.lName;}
}
Info.html
<!-To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN">
<html>
<head>
<title>Info Page</title>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
</head>
<body>
Please enter some info: <br><br>
<form action = "info.jsp" method ="post">
ID: <input type ="text" name = "ID"><br>
First Name: <input type ="text" name =
"fName"><br>
Last Name: <input type ="text" name =
"lName"><br>
<input type ="submit"<br>
</form>
</body>
</html>
info.jsp
<%@page contentType="text/html" %>
<%@page pageEncoding="UTF-8" %>
<%@page import= "java.io.*" %>
<jsp:useBean id="user" class="my.UserBean" scope="session"
>
<jsp:setProperty name="user" property="ID" value="TempId"
/>
</jsp:useBean>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Javabean JSP Page</title>
</head>
<body>
<h1>The following is info sent to this page:</h1>
<% String ID = request.getParameter("ID"); %>
<% String fName = request.getParameter("fName"); %>
<% String lName = request.getParameter("lName"); %>
<jsp:setProperty name="user" property="ID" value =
"<%= ID %>" />
<jsp:setProperty name="user" property="fName" value
= "<%= fName %>" />
<jsp:setProperty name="user" property="lName" value
= "<%= lName %>" />
<%-user.setID(ID);
user.setfName(fName);
user.setlName(lName);
--%>
<br>
<%= ID %>
<br>
<%= fName %>
<br>
<%= lName %>
<br>
<br>
Click <a href ="persistent.jsp">here</a> to
go to a persistent page
</body>
</html>
persistent.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.io.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Persistent Javabean JSP Page</title>
</head>
<body>
<h1>The following is taken from a bean:</h1>
<%! String persID; %>
<%! String persfName; %>
<%! String perslName; %>
<jsp:useBean id="user" class="my.UserBean"
scope="session" >
</jsp:useBean>
<% persID = user.getID(); %>
<% persfName = user.getfName(); %>
<% perslName = user.getlName(); %>
<%-- Scriptlet to save the bean to a serialized object --%>
<% String message="";
try
{
String name = persID;
String appRelativePath = "/WEB-INF/classes/" + name +
".ser";
String realPath =
application.getRealPath(appRelativePath);
FileOutputStream fos = new FileOutputStream(realPath);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(user);
oos.close();
message = "Successfully saved the bean as " + realPath;
}
catch (Exception e)
{
message = "Error: Could not save the bean";
}
%>
<%= message %>
<br>
<br>
Persistent Id: <jsp:getProperty name= "user" property
="ID"/>
<br>
Persistent First Name: <jsp:getProperty name= "user"
property ="fName" />
<br>
Persistent Last Name: <jsp:getProperty name= "user"
property ="lName" />
<br>
<br>
<br>
More Persistent Id: <%= persID %>
<br>
More Persistent First Name: <%= persfName %>
<br>
More Persistent Last Name:
<%= perslName %>
<br>
<br>
</body>
</html>
login.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN">
<html>
<head>
<title>Login Page</title>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
</head>
<body>
Please enter your access info: <br><br>
<form action = "login.jsp" method ="post">
<table cell border="2">
<tr>
<td>ID: </td><td><input type ="text" name =
"ID"></td></tr>
<tr>
<td> First Name (AKA Password): </td>
<td><input type ="text" name = "fName">
</td>
</tr>
</table>
<br>
<input type ="submit">
</form>
</body>
</html>
login.jsp
<%@page import="java.io.*" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>Login Results</title>
</head>
<body>
<h1>Login Results</h1>
<%
boolean found = false;
String theBeanName = null;
String result = null;
File f;
String appRelativePath = null;
String realPath = null;
String name = request.getParameter("ID");
ClassLoader classLoader =
this.getClass().getClassLoader();
if(name != null && !name.equals(""))
{
theBeanName = name;
appRelativePath = "/WEB-INF/classes/" + name +
".ser";
realPath =
application.getRealPath(appRelativePath);
f = new File(realPath);
//java.beans.Beans.instantiate(classLoader,
name + ".ser");
if (f.exists())
{
found = true;
result = "Data Found";
}
else
{
found = false;
result = "Data Not Found";
}
}
%>
<br>
<%= result %>
<br>
<%= name %>
<br>
<%= realPath %>
</body>
</html>