2 創建一個新的servlet(包名是com.jht.controller,類名是:GoodsServlet)
3 修改Build Path(增加Tomcat引用和mysql-connector-java-5.1.6-bin引用)
4 增加web.xml
文件內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns=" xmlns:xsi=" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
<servlet>
<servlet-name>GoodsServlet</servlet-name>
<servlet-class>com.jht.controller.GoodsServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GoodsServlet</servlet-name>
<url-pattern>/GoodsServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
5 index.jsp文件內容如下:
<html>
<head>
<title>錄入商品信息</title>
<style type="text/css">
*{font-size: 12px;}
</style>
<script type="text/javascript">
function save(form){
if(form.name.value == ""){
alert("請輸入商品名稱!");
return false;
}
if(form.price.value == ""){
alert("請輸入商品價格!");
return false;
}
if(form.description.value == ""){
alert("請輸入商品描述!");
return false;
}
}
</script>
</head>
<body>
<form action="GoodsServlet" method="post" onsubmit="return save(this);">
<table border="1" align="center" width="300">
<tr>
<td align="center" colspan="2">
<br><h1>錄入商品信息</h1>
</td>
</tr>
<tr>
<td align="right">商品名稱:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td align="right">價 格:</td>
<td><input type="text" name="price"></td>
</tr>
<tr>
<td align="right">商品描述:</td>
<td><textarea name="description" cols="30" rows="3"></textarea></td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="submit" value="提 交">
<input type="reset" value="重 置">
</td>
</tr>
</table>
</form>
</body>
</html>
6 創建com.jht.model包名
7 在此包下面創建Goods 類和GoodsDao類
Goods內容如下:
package com.jht.model;
public class Goods {
private String name; // 商品名稱
private double price; // 單價
private String description; // 描述信息
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
GoodsDao內如如下:
package com.jht.model;
/*
* 商品數據庫操作類
* @author
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class GoodsDao {
/**
* 保存商品信息
* @param goods
*/
public void saveGoods(Goods goods){
try {
// 加載驅動
Class.forName("com.mysql.jdbc.Driver");
// 數據庫連接url
String url = "jdbc:mysql://localhost:3306/c2cd?characterEncoding=UTF-8";
// 獲取數據庫連接
Connection conn = DriverManager.getConnection(url, "root", "root");
// sql語句
String sql = "insert into tb_goods(name,price,description) values(?,?,?)";
// 創建PreparedStatement對象
PreparedStatement ps = conn.prepareStatement(sql);
// 對sql語句中參數賦值
ps.setString(1, goods.getName());
ps.setDouble(2, goods.getPrice());
ps.setString(3, goods.getDescription());
ps.executeUpdate(); // 更新操作
ps.close(); // 關閉ps
conn.close(); // 關閉conn
} catch (Exception e) {
e.printStackTrace();
}
}
}
8 修改GoodsServlet文件
(注意:在一個Servlet 對象中,最常用的方法是doGet()和doPost()方法,這2個方法分別用于處理HTTP的Get和Post請求。例如,<form>表單對象所聲明的method屬性為"post",提交到Servlet對象處理時,Servlet將調用doPost()方法進行處理。)
package com.jht.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jht.model.Goods;
import com.jht.model.GoodsDao;
/**
* Servlet implementation class GoodsServlet
*/
@WebServlet("/GoodsServlet")
public class GoodsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public GoodsServlet() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// 設置response編碼
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
// 設置request編碼
request.setCharacterEncoding("UTF-8");
// 獲取輸出流
PrintWriter out = response.getWriter();
// 獲取商品信息
String name = request.getParameter("name");
String price = request.getParameter("price");
String description = request.getParameter("description");
Goods goods = new Goods(); // 實例化商品對象
// 對商品對象屬性賦值
goods.setName(name);
goods.setPrice(Double.valueOf(price));
goods.setDescription(description);
// 實例化GoodsDao
GoodsDao goodsDao = new GoodsDao();
goodsDao.saveGoods(goods); // 保存商品信息
out.print("保存商品信息成功!");
out.flush();
out.close();
}
}
9 數據表腳本如下:
/*
Navicat MySQL Data Transfer
Source Host : localhost:3306
Source Database : c2cd
Target Host : localhost:3306
Target Database : c2cd
Date: 2012-07-09 14:41:20
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for tb_goods
-- ----------------------------
DROP TABLE IF EXISTS `tb_goods`;
CREATE TABLE `tb_goods` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
`price` double DEFAULT NULL,
`description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;