CREATE TABLE `tb_goods1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
`price` float DEFAULT NULL,
`unit` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
`manufacturer` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
)
2 創(chuàng)建網(wǎng)站
3 新建Servlet 名稱是GoodsServlet 包名是com.jht.servlet
4 引用Tomcat, 附加jar包文件 <Build Path菜單>
mysql-connector-java-3.0.16-ga-bin :數(shù)據(jù)庫操作類
jstl-api-1.2 JSP標(biāo)準(zhǔn)標(biāo)簽庫
jstl-impl-1.2 JSP標(biāo)準(zhǔn)標(biāo)簽庫
5 創(chuàng)建實體類 GoodsForm 包名是 com.jht.model
代碼如下:
public class GoodsForm {
private int id = 0; // 編號屬性
private String name = ""; // 商品名稱屬性
private float price = 0.0f; // 單價屬性
private String unit = ""; // 單位屬性
private String manufacturer = ""; // 廠商屬性
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setPrice(float price) {
this.price = price;
}
public float getPrice() {
return price;
}
public void setUnit(String unit) {
this.unit = unit;
}
public String getUnit() {
return unit;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getManufacturer() {
return manufacturer;
}
}
6 編寫數(shù)據(jù)庫連接與操作類
package com.jht.tools;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class ConnDB {
public Connection conn=null;
public Statement stmt=null;
public ResultSet rs=null;
private static String propFileName="connDB.properties";
private static Properties prop=new Properties();
private static String dbClassName="com.mysql.jdbc.Driver";
private static String dbUrl="jdbc:mysql://127.0.0.1:3306/db_Database07?user=root&password=111&characterEncoding=UTF-8";
public ConnDB() { //定義構(gòu)造方法
try { //捕捉異常
//將Properties文件讀取到InputStream對象中
InputStream in = getClass().getResourceAsStream(propFileName);
prop.load(in); // 通過輸入流對象加載Properties文件
dbClassName = prop.getProperty("DB_CLASS_NAME"); // 獲取數(shù)據(jù)庫驅(qū)動
dbUrl = prop.getProperty("DB_URL", dbUrl); //獲取URL
} catch (Exception e) {
e.printStackTrace(); // 輸出異常信息
}
}
public static Connection getConnection() {
Connection conn = null;
try { //連接數(shù)據(jù)庫時可能發(fā)生異常因此需要捕捉該異常
Class.forName(dbClassName).newInstance(); //裝載數(shù)據(jù)庫驅(qū)動
//建立與數(shù)據(jù)庫URL中定義的數(shù)據(jù)庫的連接
conn = DriverManager.getConnection(dbUrl);
} catch (Exception ee) {
ee.printStackTrace(); //輸出異常信息
}
if (conn == null) {
System.err
.println("警告: DbConnectionManager.getConnection() 獲得數(shù)據(jù)庫鏈接失敗.\r\n\r\n鏈接類型:"
+ dbClassName
+ "\r\n鏈接位置:"
+ dbUrl); //在控制臺上輸出提示信息
}
return conn; //返回數(shù)據(jù)庫連接對象
}
/*
* 功能:執(zhí)行查詢語句
*/
public ResultSet executeQuery(String sql) {
try { // 捕捉異常
conn = getConnection(); // 調(diào)用getConnection()方法構(gòu)造Connection對象的一個實例conn
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(sql); //執(zhí)行SQL語句,并返回一個ResultSet對象rs
} catch (SQLException ex) {
System.err.println(ex.getMessage()); // 輸出異常信息
}
return rs; // 返回結(jié)果集對象
}
/*
* 功能:關(guān)閉數(shù)據(jù)庫的連接
*/
public void close() {
try { // 捕捉異常
if (rs != null) { // 當(dāng)ResultSet對象的實例rs不為空時
rs.close(); // 關(guān)閉ResultSet對象
}
if (stmt != null) { // 當(dāng)Statement對象的實例stmt不為空時
stmt.close(); // 關(guān)閉Statement對象
}
if (conn != null) { // 當(dāng)Connection對象的實例conn不為空時
conn.close(); // 關(guān)閉Connection對象
}
} catch (Exception e) {
e.printStackTrace(System.err); // 輸出異常信息
}
}
}
7 配置文件connDB.properties 內(nèi)容如下:
DB_CLASS_NAME=com.mysql.jdbc.Driver
DB_URL=jdbc:mysql://127.0.0.1:3306/c2cd?user=root&password=root&characterEncoding=UTF-8
8 web.xml 文件配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>GoodsServlet</servlet-name>
<servlet-class>com.jht.servlet.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>
9 index.jsp 代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Insert title here</title>
</head>
<body>
<c:redirect url="GoodsServlet">
<c:param name="action" value="query" />
</c:redirect>
</body>
</html>
10 GoodsList.jsp 代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>Insert title here</title>
</head>
<body>
<table width="450" height="47" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#333333">
<tr>
<td height="30" colspan="5" bgcolor="#EFEFEF">·商品列表</td>
</tr>
<tr>
<td width="36" height="27" align="center" bgcolor="#FFFFFF">編號</td>
<td width="137" align="center" bgcolor="#FFFFFF">商品名稱</td>
<td width="85" align="center" bgcolor="#FFFFFF">單價</td>
<td width="38" align="center" bgcolor="#FFFFFF">單位</td>
<td width="148" align="center" bgcolor="#FFFFFF">廠商</td>
</tr>
<c:forEach var="goods" items="${requestScope.goodsList}">
<tr>
<td height="27" bgcolor="#FFFFFF">
<c:out value="${goods.id}"/></td>
<td bgcolor="#FFFFFF">
<c:out value="${goods.name}"/></td>
<td bgcolor="#FFFFFF">
<c:out value="${goods.price}"/>(元)</td>
<td bgcolor="#FFFFFF">
<c:out value="${goods.unit}"/></td>
<td bgcolor="#FFFFFF">
<c:out value="${goods.manufacturer}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
11 顯示數(shù)據(jù)庫中的商品信息
t1.jsp頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "<html>
<head>
<base href="<%=basePath%>">
<title>應(yīng)用EL表達(dá)式訪問JavaBean的屬性</title>
<link rel="stylesheet" type="text/css" href="CSS/style.css">
</head>
<body><form name="form1" method="post" action="t2.jsp">
<table width="403" height="230" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#666666">
<tr>
<td height="30" colspan="2" bgcolor="#EFEFEF">·用戶注冊</td>
</tr>
<tr>
<td width="88" align="center" bgcolor="#FFFFFF">用 戶 名:</td>
<td width="359" bgcolor="#FFFFFF"><input name="username" type="text" id="username"></td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">密 碼:</td>
<td bgcolor="#FFFFFF"><input name="pwd" type="password" id="pwd"></td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">確認(rèn)密碼:</td>
<td bgcolor="#FFFFFF"><input name="repwd" type="password" id="repwd"></td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">性 別:</td>
<td bgcolor="#FFFFFF"><input name="sex" type="radio" class="noborder" value="男">
男
<input name="sex" type="radio" class="noborder" value="女">
女</td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">愛 好:</td>
<td bgcolor="#FFFFFF"><input name="affect" type="checkbox" class="noborder" id="affect" value="體育">
體育
<input name="affect" type="checkbox" class="noborder" id="affect" value="美術(shù)">
美術(shù)
<input name="affect" type="checkbox" class="noborder" id="affect" value="音樂">
音樂
<input name="affect" type="checkbox" class="noborder" id="affect" value="旅游">
旅游 </td>
</tr>
<tr>
<td colspan="2" align="center" bgcolor="#FFFFFF">
<input name="Submit" type="submit" class="btn_grey" value="提交">
<input name="Submit2" type="reset" class="btn_grey" value="重置"></td>
</tr>
</table>
</form>
</body>
</html>
編寫保存信息的javaBean
package com.jht.wgh;
public class UserForm {
private String username=""; //用戶名屬性
private String pwd=""; //密碼屬性
private String sex=""; //性別屬性
private String[] affect=null; //愛好屬性
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getPwd() {
return pwd;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getSex() {
return sex;
}
public void setAffect(String[] affect) {
this.affect = affect;
}
public String[] getAffect() {
return affect;
}
}
編寫t2.jsp,在該頁中,使用request內(nèi)置對象的setCharacterEncoding()方法設(shè)置請求的編碼方式為UTF-8,然后使用<jsp:userBean>動作指令在頁面中創(chuàng)建一個javaBean實例,再使用<jsp:setProperty>動作指令設(shè)置javaBean實例的各種屬性值,最后使用EL表達(dá)式將JavaBean的各種屬性顯示到頁面中。
t2.jsp代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%request.setCharacterEncoding("UTF-8");%>
<jsp:useBean id="userForm" class="com.jht.wgh.UserForm" scope="page"/>
<jsp:setProperty name="userForm" property="*"/>
<jsp:setProperty name="userForm" property="affect" value='<%=request.getParameterValues("affect")%>'/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>應(yīng)用EL表達(dá)式訪問JavaBean的屬性</title>
<link rel="stylesheet" type="text/css" href="CSS/style.css">
</head>
<body>
<table width="403" height="218" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#666666">
<tr>
<td height="30" colspan="2" bgcolor="#EFEFEF">·顯示用戶填寫的注冊信息</td>
</tr>
<tr>
<td width="88" align="center" bgcolor="#FFFFFF">用 戶 名:</td>
<td width="359" bgcolor="#FFFFFF"> ${userForm.username}</td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">密 碼:</td>
<td bgcolor="#FFFFFF"> ${userForm.pwd}</td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">性 別:</td>
<td bgcolor="#FFFFFF"> ${userForm.sex}</td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">愛 好:</td>
<td bgcolor="#FFFFFF"> ${userForm.affect[0]} ${userForm.affect[1]} ${userForm.affect[2]} ${userForm.affect[3]}</td>
</tr>
<tr>
<td colspan="2" align="center" bgcolor="#FFFFFF">
<input name="Button" type="button" class="btn_grey" value="返回" onClick="window.location.href='t1.jsp'">
</td>
</tr>
</table>
</body>
</html>
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;
}
}
package com.jht.model;
/*
* 商品數(shù)據(jù)庫操作類
* @author
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class GoodsDao {
/**
* 保存商品信息
* @param goods
*/
public void saveGoods(Goods goods){
try {
// 加載驅(qū)動
Class.forName("com.mysql.jdbc.Driver");
// 數(shù)據(jù)庫連接url
String url = "jdbc:mysql://localhost:3306/c2cd?characterEncoding=UTF-8";
// 獲取數(shù)據(jù)庫連接
Connection conn = DriverManager.getConnection(url, "root", "root");
// sql語句
String sql = "insert into tb_goods(name,price,description) values(?,?,?)";
// 創(chuàng)建PreparedStatement對象
PreparedStatement ps = conn.prepareStatement(sql);
// 對sql語句中參數(shù)賦值
ps.setString(1, goods.getName());
ps.setDouble(2, goods.getPrice());
ps.setString(3, goods.getDescription());
ps.executeUpdate(); // 更新操作
ps.close(); // 關(guān)閉ps
conn.close(); // 關(guān)閉conn
} catch (Exception e) {
e.printStackTrace();
}
}
}
(注意:在一個Servlet 對象中,最常用的方法是doGet()和doPost()方法,這2個方法分別用于處理HTTP的Get和Post請求。例如,<form>表單對象所聲明的method屬性為"post",提交到Servlet對象處理時,Servlet將調(diào)用doPost()方法進(jìn)行處理。)
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
// 設(shè)置response編碼
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
// 設(shè)置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 數(shù)據(jù)表腳本如下:
/*
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;
package com.jht;
public class Counter {
private int count=0;
public int getCount()
{
return ++count;
}
}
<body>
<!-- 創(chuàng)建一個session范圍的counter對象 -->
<jsp:useBean id="counter_session" class="com.jht.Counter" scope="session"/>
<!-- 創(chuàng)建一個application范圍的counter對象 -->
<jsp:useBean id="counter_application" class="com.jht.Counter" scope="application" />
作用域
<br>
session:
<jsp:getProperty name="counter_session" property="count" />
<br>
application:
<jsp:getProperty name="counter_application" property="count"/>
</body>
package com.jht;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* 字符編碼過濾器
* @author
*/
public class CharacterEncodingFilter implements Filter{
// 字符編碼(初始化參數(shù))
protected String encoding = null;
// FilterConfig對象
protected FilterConfig filterConfig = null;
// 初始化方法
public void init(FilterConfig filterConfig) throws ServletException {
// 對filterConfig賦值
this.filterConfig = filterConfig;
// 對初始化參數(shù)賦值
this.encoding = filterConfig.getInitParameter("encoding");
}
// 過濾器處理方法
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// 判斷字符編碼是否有效
if (encoding != null) {
// 設(shè)置request字符編碼
request.setCharacterEncoding(encoding);
// 設(shè)置response字符編碼
response.setContentType("text/html; charset="+encoding);
}
// 傳遞給下一過濾器
chain.doFilter(request, response);
}
// 銷毀方法
public void destroy() {
// 釋放資源
this.encoding = null;
this.filterConfig = null;
}
}
package com.jht;
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;
/**
* Servlet implementation class MyServletnew
*/
@WebServlet("/MyServletnew")
public class MyServletnew extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public MyServletnew() {
// 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
PrintWriter out = response.getWriter();
// 獲取表單參數(shù)
String name = request.getParameter("name");
if(name != null && !name.isEmpty()){
System.out.println(name);
out.print("你好 " + name);
out.print(",<br>歡迎來到我的主頁。");
}else{
out.print("請輸入你的中文名字!");
}
out.print("<br><a href=index.jsp>返回</a>");
out.flush();
out.close();
}
}
2 創(chuàng)建Servlet 設(shè)置java package(com.servlet)和class name(MyServlet)。
設(shè)置:
選擇Add Library上下文路徑:/MyServlet
HTTP請求類型:GET
請求參數(shù):null
請求URI:/test1/MyServlet
請求URL:http://localhost:8080/test1/MyServlet
請求Servlet路徑:/MyServlet
注意:Web Deployment Assembly增加Add,對mysql.jar的引用