<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %><%
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "php", "密碼");
if (request.getMethod() == "POST") {
String name = request.getParameter("ItemName");
String description = request.getParameter("ItemDescription");
String price = request.getParameter("ItemPrice");
String sql = "INSERT INTO Items VALUES (NULL, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, name);
stmt.setString(2, description);
stmt.setString(3, price);
stmt.executeUpdate();
response.sendRedirect("items.jsp");
}
%><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Items</title>
<script type="text/javascript" src="
http://ajax.microsoft.com/ajax/jquery/jquery-1.7.min.js"></script>
<script>
function checkForm() {
if ($("#ItemName").val() == "") {
$("#ItemName").focus();
return false;
} else if ($("#ItemDescription").val() == "") {
$("#ItemDescription").focus();
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<%
String sql = "SELECT * FROM Items ORDER BY ItemID";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
%>
<ul class="Items">
<% while (rs.next()) { %><li>
<h3><%=rs.getString("ItemName")%></h3>
<p><%=rs.getString("ItemDescription")%></p>
<p>Price: <%=rs.getString("ItemPrice")%></p>
</li><%
}
stmt.close();
rs.close();
%>
</ul>
<form name="NewItem" method="post" action="" onSubmit="return checkForm()">
<p>
<label for="ItemName">Name: </label><br>
<input type="text" name="ItemName" id="ItemName">
</p>
<p>
<label for="ItemDescription">Description:</label><br>
<textarea name="ItemDescription" rows="4" id="ItemDescription"></textarea>
</p>
<p>
<label for="ItemPrice">Price: </label><br>
<input name="ItemPrice" type="text" id="ItemPrice" value="10.0">
</p>
<p><input type="submit" name="button" id="button" value="Submit"></p>
</form>
</body>
</html>
<%
conn.close();
%>