第80節:Java中的MVC設計模式
前言
瞭解java中的mvc模式.複習以及回顧!
事務,設定自動連線提交關閉.
setAutoCommit(false);
conn.commit();
conn.rollBack
隔離級別分別有:
讀未提交有髒讀
讀已提交有不可重複讀
可重複讀有幻讀
可序列化可以解決髒讀,幻讀,不可重複讀
資料庫連線池用於建立和管理連線物件.
DBCP和C3P0,分別瞭解程式碼設定和配置檔案設定
DBUtils可以簡化資料的增刪改查.
QueryRunner runner = new QueryRunner();
runner.update();
runner.query();
DBUtils通用的增刪改
public void testInsert(){
// 查詢
Connection conn = null;
Statement st = null;
try{
// 獲取連線物件
conn = JDBCUtil.getConn();
// 根據連線物件,得到state ment
st = conn.createStatement();
// 執行新增
String sql = "insert into t_stu values(null, `dashu`, 23)";
// 影響行數
int result = st.executeUpdate(sql);
if(result > 0){
System.out.println("新增成功");
}else{
System.out.println("新增失敗");
}
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCUtil.release(conn, st);
}
通用的增刪改方法
package com.dashucoding.commoncrud;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.junit.Test;
import com.dashucoding.util.JDBCUtil;
import com.dashucoding.util.JDBCUtil02;
public class CommonCRUDUtil {
@Test
public void testUpdate() {
// update("insert into account values(null, ?, ?)" , "dashu", 10);
// update("delete from account where id = ?", 1);
update("update account set money = ? where id = ?", 1999, 2);
}
// 通用的增刪改功能
public void update(String sql, Object ...args) {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = JDBCUtil02.getConn();
ps = conn.prepareStatement(sql);
for(int i = 0; i<args.length; i++) {
ps.setObject(i+1, args[i]);
}
ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JDBCUtil.release(conn, ps);
}
}
}
資料庫的後設資料
java.sql
介面 DatabaseMetaData
所有超級介面: Wrapper
public interface DatabaseMetaData extends Wrapper
資料庫的整體綜合資訊
方法
getCatalogs()
可以獲取在資料庫中使用的類別名稱
getCatalogSeparator()
獲取此資料庫用作類別和表名之間的分隔符的String
getCatalogTerm()
獲取資料庫供應商用於"catalog"的首選手語
getClientInfoProperties()
獲取驅動程式支援的客戶端資訊屬性的列表
getConnection()
獲取此後設資料物件所產生的連線
getDatabaseMajorVersion()
獲取底層資料庫的主版本號
getDatabaseProductName()
獲取此資料庫產品的名稱
getDatabaseProductVersion()
獲取此資料庫產品的版本號
getDefaultTransactionIsolation()
獲取此資料庫的預設事務隔離級別
getDriverMajorVersion()
獲取此JDBC驅動程式的主版本號
getDriverMinorVersion()
獲取此JDBC驅動程式的次版本號
getDriverName()
獲取此JDBC驅動程式的名稱
getDriverVersion()
獲取此JDBC驅動程式的String形式的版本號
引數的後設資料
java.sql
介面 ParameterMetaData
public interface ParameterMetaData extends Wrapper
獲取PreparedStatement物件中每個引數標記和屬性資訊的物件.
方法的摘要
getParameterClassName(int param)
獲取Java類的完全限定名稱
getParameterCount()
獲取PreparedStatement物件中的引數數量
getParameterMode(int param)
獲取指定引數的SQL型別
getParameterTypeName(int param)
獲取指定引數的特定於資料庫的型別名稱
getPrecision(int param)
獲取指定引數的指定兩列大小
getScale(int param)
獲取指定引數的小數點右邊的位數
isNullable(int param)
獲取是否允許在指定引數中使用null值
isSigned(int param)
獲取指定引數的值是否可以是帶符號的數字
結果集後設資料
java.sql
介面 ResultSetMetaData
public interface ResultSetMetaData extends Wrapper
用來描述資料的資料,叫做後設資料
資料庫後設資料,引數後設資料,結果集後設資料
package com.dashucoding.commoncrud;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.junit.Test;
import com.dashucoding.util.JDBCUtil;
import com.dashucoding.util.JDBCUtil02;
public class CommonCRUDUtil {
@Test
public void testUpdate() {
// update("insert into account values(null, ?, ?)" , "dashu", 10);
// update("delete from account where id = ?", 1);
update("update account set money = ? where id = ?", 1999, 2);
}
// 通用的增刪改功能
public void update(String sql, Object ...args) {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = JDBCUtil02.getConn();
ps = conn.prepareStatement(sql);
// 後設資料
// 獲取的有幾個問好
ParameterMetaData metaData = ps.getParameterMetaData();
int count = metaData.getParameterCount();
for(int i = 0; i<count; i++) {
ps.setObject(i+1, args[i]);
}
ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JDBCUtil.release(conn, ps);
}
}
}
TestDBUtils.java
// 刪除
queryRunner.update("delete from account where id = ?", 4);
// 更新
queryRunner.update("update account set money=? where id=?", 10000, 5);
// 執行查詢,查詢到的資料還是在那個result裡面然後呼叫下面的handle方法,由使用者手動封裝
Account account = queryRunner.query("select * from account where id =?", new ResultSetHandler<Account>(){
@Override
public Account handle(ResultSet rs) throws SQLException{
Account account = new Account();
while(rs.next()){
String name = rs.getString("name");
int money = rs.getInt("money");
account.setName(name);
account.setMoney(money);
}
return account;
}
}, 6);
快速查詢方法
@Test
public void testQuery(){
query("select * from account where id = ?", 介面的實現類物件, 3);
}
class A implements ResultSetHandler {
@Override
public void handle(ResultSet rs) {
// TODO Auto-generated method stub
}
}
通用的查詢方法
package com.dashucoding.commoncrud;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Test;
import com.dashucoding.domain.Account;
import com.dashucoding.util.JDBCUtil;
import com.dashucoding.util.JDBCUtil02;
public class CommonCRUDUtil {
class A implements ResultSetHandler<Account> {
@Override
public Account handle(ResultSet rs) {
// TODO Auto-generated method stub
try {
Account account = new Account();
if(rs.next()) {
String name = rs.getString("name");
int money = rs.getInt("money");
account.setName(name);
account.setMoney(money);
}
return account;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/*@Override
public Object handle(ResultSet rs) {
// TODO Auto-generated method stub
return null;
}*/
/*@Override
public void handle(ResultSet rs) {
// TODO Auto-generated method stub
try {
while(rs.next()) {
String name = rs.getString("name");
int money = rs.getInt("money");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
}
@Test
public void testQuery() {
/*query("select * from account where id=?", new ResultSetHandler() {
@Override
public void handle(ResultSet rs) {
// TODO Auto-generated method stub
}
},3);*/
/*Account account = query("select * from account where id = ?", new A(), 2);
System.out.println(account.toString());*/
query("select * from account where id = ?", new ResultSetHandler<Account>() {
@Override
public Account handle(ResultSet rs) {
// TODO Auto-generated method stub
return null;
}}, 2);
}
@Test
public void testUpdate() {
// update("insert into account values(null, ?, ?)" , "dashu", 10);
// update("delete from account where id = ?", 1);
// update("update account set money = ? where id = ?", 1999, 2);
}
public <T> T query(String sql, ResultSetHandler<T> handler, Object... args) {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = JDBCUtil02.getConn();
ps = conn.prepareStatement(sql);
// 後設資料
// 獲取的有幾個問好
ParameterMetaData metaData = ps.getParameterMetaData();
int count = metaData.getParameterCount();
for (int i = 0; i < count; i++) {
ps.setObject(i + 1, args[i]);
}
// 執行查詢工作,然後得到結果集
ResultSet rs = ps.executeQuery();
// 把結果集丟給呼叫者, 讓它去封裝資料,返回封裝資料
T t = (T) handler.handle(rs);
return t;
/*while(rs.next()) {
rs.getInt("id");
rs.getString("name");
}*/
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JDBCUtil.release(conn, ps);
}
return null;
}
// 通用的增刪改功能
/*public void update(String sql, Object... args) {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = JDBCUtil02.getConn();
ps = conn.prepareStatement(sql);
// 後設資料
// 獲取的有幾個問好
ParameterMetaData metaData = ps.getParameterMetaData();
int count = metaData.getParameterCount();
for (int i = 0; i < count; i++) {
ps.setObject(i + 1, args[i]);
}
ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JDBCUtil.release(conn, ps);
}
}*/
}
package com.dashucoding.domain;
public class Account {
private String name;
private int money;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
@Override
public String toString() {
return "Account [name=" + name + ", money=" + money + "]";
}
}
package com.dashucoding.commoncrud;
import java.sql.ResultSet;
public interface ResultSetHandler<T> {
// 資料封裝的規則,規範
T handle(ResultSet rs);
}
JSP開發模式
mvc的設計模式
javaBean資料的封裝+jsp
可以在jsp中直接寫java程式碼
<%
封裝資料
執行業務
準備資料
%>
特點維護比較難,jsp的頁面程式碼會臃腫
servlet + javabean + jsp
mvc模式:
m:model
模型層
封裝資料javabean
v:view
檢視層
jsp專注顯示
c:controller
控制層
servlet接收頁面的請求,找模型層去處理
三層架構
客戶端,web層,業務邏輯層,資料訪問層
servlet/jsp web層
javabean 業務邏輯層
dao 資料訪問層
web層 對應 controller view
業務邏輯層 對應 model
資料訪問層 對應 model
mvc模式: controller view model
controller: 接收請求,呼叫模型層出來資料,反饋給view
view: 用於顯示
model: 資料的封裝,資料的處理
學生管理系統中的增刪查改,分頁,模糊查詢
學生管理系統
歡迎使用學生管理系統, 按姓名查詢, 按性別查詢, 新增
有編號,姓名 ,性別,電話,生日,愛好,簡介,操作.
建立資料庫
dao環境搭建
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>首頁</title>
</head>
<body>
<h3><a href="StudentListServlet">顯示所有學生列表</a></h3><br>
</body>
</html>
package com.dashucoding.dao;
import java.sql.SQLException;
import java.util.List;
import com.dashucoding.domain.Student;
/*
* 這是針對學生表的資料訪問
*
* */
public interface StudentDao {
/*
* 查詢所有學生
* list<Student>
* */
List<Student> findAll() throws SQLException;
}
package com.dashucoding.dao.impl;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.dashucoding.dao.StudentDao;
import com.dashucoding.domain.Student;
import com.dashucoding.util.JDBCUtil02;
/*
* 這是studentdao的實現,針對前面定義的規範,做出具體的實現
* */
public class StudentDaoImpl implements StudentDao {
/*
* 查詢所有學生
* */
@Override
public List<Student> findAll() throws SQLException {
QueryRunner runner = new QueryRunner(JDBCUtil02.getDataSource());
String sql = "select * from stu";
List<Student> list = runner.query(sql, new BeanListHandler<Student>(Student.class));
return list;
}
}
package com.dashucoding.domain;
import java.util.Date;
/*
* 這是學生封裝的物件bean
* 根據表寫
* */
public class Student {
private int sid;
private String sname;
private String gender;
private String phone;
private String hobby;
private String info;
private Date birthday;
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
package com.dashucoding.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class StudentListServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package com.dashucoding.util;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JDBCUtil02 {
static ComboPooledDataSource dataSource = null;
static {
dataSource = new ComboPooledDataSource();
}
public static DataSource getDataSource() {
return dataSource;
}
/**
* 獲取連線物件
* @return
* @throws SQLException
*/
public static Connection getConn() throws SQLException{
return dataSource.getConnection();
}
/**
* 釋放資源
* @param conn
* @param st
* @param rs
*/
public static void release(Connection conn , Statement st , ResultSet rs){
closeRs(rs);
closeSt(st);
closeConn(conn);
}
public static void release(Connection conn , Statement st){
closeSt(st);
closeConn(conn);
}
private static void closeRs(ResultSet rs){
try {
if(rs != null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
rs = null;
}
}
private static void closeSt(Statement st){
try {
if(st != null){
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
st = null;
}
}
private static void closeConn(Connection conn){
try {
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
conn = null;
}
}
}
service層
dao只做一件事,資料操作層
service是業務層
查詢資料
package com.dashucoding.dao;
import java.sql.SQLException;
import java.util.List;
import com.dashucoding.domain.Student;
/*
* 這是針對學生表的資料訪問
*
* */
public interface StudentDao {
/*
* 查詢所有學生
* list<Student>
* */
List<Student> findAll() throws SQLException;
}
package com.dashucoding.dao.impl;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.dashucoding.dao.StudentDao;
import com.dashucoding.domain.Student;
import com.dashucoding.util.JDBCUtil02;
/*
*這是StudentDao的實現,針對前面定義的規範,做出具體的實現
* */
public class StudentDaoImpl implements StudentDao {
/*
* 查詢所有學生
* */
@Override
public List<Student> findAll() throws SQLException {
QueryRunner runner = new QueryRunner(JDBCUtil02.getDataSource());
return runner.query("select * from stu", new BeanListHandler<Student>(Student.class));
}
}
package com.dashucoding.domain;
import java.util.Date;
/*
* 這是學生封裝的物件bean
*
* */
public class Student {
private int sid;
private String sname;
private String gender;
private String phone;
private String hobby;
private String info;
private Date birthday;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int sid, String sname, String gender, String phone, String hobby, String info, Date birthday) {
super();
this.sid = sid;
this.sname = sname;
this.gender = gender;
this.phone = phone;
this.hobby = hobby;
this.info = info;
this.birthday = birthday;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Student [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", phone=" + phone + ", hobby="
+ hobby + ", info=" + info + ", birthday=" + birthday + "]";
}
}
package com.dashucoding.service;
import java.sql.SQLException;
import java.util.List;
import com.dashucoding.domain.Student;
/*
* 這是學生的業務處理規範
* */
public interface StudentService {
/*
* 查詢所有學生
* list<Student>
* */
List<Student> findAll() throws SQLException;
}
package com.dashucoding.service.impl;
import java.sql.SQLException;
import java.util.List;
import com.dashucoding.dao.StudentDao;
import com.dashucoding.dao.impl.StudentDaoImpl;
import com.dashucoding.domain.Student;
import com.dashucoding.service.StudentService;
/*
* 這是學生業務實現
* */
public class StudentServiceImpl implements StudentService{
@Override
public List<Student> findAll() throws SQLException {
StudentDao dao = new StudentDaoImpl();
return dao.findAll();
}
}
package com.dashucoding.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dashucoding.dao.StudentDao;
import com.dashucoding.dao.impl.StudentDaoImpl;
import com.dashucoding.domain.Student;
import com.dashucoding.service.StudentService;
import com.dashucoding.service.impl.StudentServiceImpl;
public class StudentListServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
// 查詢所有的學生
StudentService service = new StudentServiceImpl();
List<Student> list = service.findAll();
// 把資料儲存到作用域中
request.setAttribute("list", list);
// 跳轉頁面
request.getRequestDispatcher("list.jsp").forward(request,response);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
package com.dashucoding.util;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JDBCUtil02 {
static ComboPooledDataSource dataSource = null;
static {
dataSource = new ComboPooledDataSource();
}
public static DataSource getDataSource() {
return dataSource;
}
/**
* 獲取連線物件
* @return
* @throws SQLException
*/
public static Connection getConn() throws SQLException{
return dataSource.getConnection();
}
/**
* 釋放資源
* @param conn
* @param st
* @param rs
*/
public static void release(Connection conn , Statement st , ResultSet rs){
closeRs(rs);
closeSt(st);
closeConn(conn);
}
public static void release(Connection conn , Statement st){
closeSt(st);
closeConn(conn);
}
private static void closeRs(ResultSet rs){
try {
if(rs != null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
rs = null;
}
}
private static void closeSt(Statement st){
try {
if(st != null){
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
st = null;
}
}
private static void closeConn(Connection conn){
try {
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
conn = null;
}
}
}
小結業務邏輯
先寫一個jsp頁面,有個連結<a href="StudentListServlet"></a>
寫個Servlet,接收請求,去呼叫Service,由service去呼叫dao,寫dao,然後做dao實現,再寫Service,做Service的實現,在servlet儲存資料,做出頁面響應,在list.jsp上顯示資料.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>新增學生頁面</title>
</head>
<body>
<form method="post" action="AddServlet">
<table border="1" width="600">
<tr>
<td>姓名</td>
<td><input type="text" name="sname"></td>
</tr>
<tr>
<td>性別</td>
<td><input type="radio" name="gender" value="男">男 <input
type="radio" name="gender" value="女">女</td>
</tr>
<tr>
<td>電話</td>
<td><input type="text" name="phone"></td>
</tr>
<tr>
<td>生日</td>
<td><input type="text" name="birthday"></td>
</tr>
<tr>
<td>愛好</td>
<td><input type="checkbox" name="hobby" value="游泳">游泳 <input
type="checkbox" name="hobby" value="籃球">籃球 <input
type="checkbox" name="hobby" value="足球">足球 <input
type="checkbox" name="hobby" value="看書">看書 <input
type="checkbox" name="hobby" value="寫字">寫字</td>
</tr>
<tr>
<td>簡介</td>
<td><textarea name="info" rows="3" cols="20"></textarea></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="新增"></td>
</tr>
</table>
</form>
</body>
</html>
package com.dashucoding.dao;
import java.sql.SQLException;
import java.util.List;
import com.dashucoding.domain.Student;
/*
* 這是針對學生表的資料訪問
*
* */
public interface StudentDao {
/*
* 查詢所有學生
* list<Student>
* */
List<Student> findAll() throws SQLException;
void insert(Student student) throws SQLException ;
}
package com.dashucoding.dao.impl;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.dashucoding.dao.StudentDao;
import com.dashucoding.domain.Student;
import com.dashucoding.util.JDBCUtil02;
/*
*這是StudentDao的實現,針對前面定義的規範,做出具體的實現
* */
public class StudentDaoImpl implements StudentDao {
/*
* 查詢所有學生
*/
@Override
public List<Student> findAll() throws SQLException {
QueryRunner runner = new QueryRunner(JDBCUtil02.getDataSource());
return runner.query("select * from stu", new BeanListHandler<Student>(Student.class));
}
@Override
public void insert(Student student) throws SQLException {
// TODO Auto-generated method stub
QueryRunner runner = new QueryRunner(JDBCUtil02.getDataSource());
runner.update("insert into stu values(null, ?,?,?,?,?,?)",
student.getSname(),
student.getGender(),
student.getPhone(),
student.getBirthday(),
student.getHobby(),
student.getInfo()
);
}
}
package com.dashucoding.domain;
import java.util.Date;
/*
* 這是學生封裝的物件bean
*
* */
public class Student {
private int sid;
private String sname;
private String gender;
private String phone;
private String hobby;
private String info;
private Date birthday;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(int sid, String sname, String gender, String phone, String hobby, String info, Date birthday) {
super();
this.sid = sid;
this.sname = sname;
this.gender = gender;
this.phone = phone;
this.hobby = hobby;
this.info = info;
this.birthday = birthday;
}
public Student(String sname, String gender, String phone, String hobby, String info, Date birthday) {
super();
this.sname = sname;
this.gender = gender;
this.phone = phone;
this.hobby = hobby;
this.info = info;
this.birthday = birthday;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Student [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", phone=" + phone + ", hobby="
+ hobby + ", info=" + info + ", birthday=" + birthday + "]";
}
}
package com.dashucoding.service;
import java.sql.SQLException;
import java.util.List;
import com.dashucoding.domain.Student;
/*
* 這是學生的業務處理規範
* */
public interface StudentService {
/*
* 查詢所有學生
* list<Student>
* */
List<Student> findAll() throws SQLException;
void insert(Student student) throws SQLException ;
}
package com.dashucoding.service.impl;
import java.sql.SQLException;
import java.util.List;
import com.dashucoding.dao.StudentDao;
import com.dashucoding.dao.impl.StudentDaoImpl;
import com.dashucoding.domain.Student;
import com.dashucoding.service.StudentService;
/*
* 這是學生業務實現
* */
public class StudentServiceImpl implements StudentService{
@Override
public List<Student> findAll() throws SQLException {
StudentDao dao = new StudentDaoImpl();
return dao.findAll();
}
@Override
public void insert(Student student) throws SQLException {
// TODO Auto-generated method stub
StudentDao dao = new StudentDaoImpl();
dao.insert(student);
}
}
package com.dashucoding.servlet;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dashucoding.domain.Student;
import com.dashucoding.service.StudentService;
import com.dashucoding.service.impl.StudentServiceImpl;
/**
* 用於處理學生的新增請求
*/
public class AddServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
try {
// 1. 獲取客戶端提交上來的資料
String sname = request.getParameter("sname");
String gender = request.getParameter("gender");
String phone = request.getParameter("phone");
String birthday = request.getParameter("birthday");
String info = request.getParameter("info");
// String hobby = request.getParameter("hobby");//hobby : 游泳,寫字, 足球。
String[] h = request.getParameterValues("hobby");
String hobby = Arrays.toString(h);
hobby = hobby.substring(1, hobby.length() - 1);
// 2. 新增到資料庫
// string -- date
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(birthday);
Student student = new Student(sname, gender, phone, hobby, info, date);
StudentService service = new StudentServiceImpl();
service.insert(student);
// 3. 跳轉到列表頁
request.getRequestDispatcher("StudentListServlet").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
要的jar包,都在這.
結言
好了,歡迎在留言區留言,與大家分享你的經驗和心得。
感謝你學習今天的內容,如果你覺得這篇文章對你有幫助的話,也歡迎把它分享給更多的朋友,感謝。
達叔小生:往後餘生,唯獨有你
You and me, we are family !
90後帥氣小夥,良好的開發習慣;獨立思考的能力;主動並且善於溝通
簡書部落格: 達叔小生
https://www.jianshu.com/u/c785ece603d1
結語
- 下面我將繼續對 其他知識 深入講解 ,有興趣可以繼續關注
- 小禮物走一走 or 點贊