標籤:
1、建立資料庫
根據需求建立相應的資料庫
確立資料庫的欄位、屬性、主鍵等
2、建立javaweb項目,搭建開發環境
在開發環境的/WebRoot/WEB-INF
下建立lib檔案夾,存放需要使用的jar包
常用的包:
mysqldriver.jar
beanutil.jar
commons-logging.jar
jstl.jar
standard.jar
3、java內部書寫,建立domain包
在其下書寫bean類,類的欄位與資料庫對應
4、定義dao和其介面
(1)介面dao包:對daoimlents包進行抽象(為了增加dao的課擴充性)
//增加客戶
//這裡對資料庫中的資料進行操作增刪,加入sql語句
模板:
Connection conn =null;
PreStatement stmt = null;
ResultSet rs = null;
if(c==null)
//參數不對異常見還有NUllException,就是參數為空白的時候
throw new IllegaException();
try{
conn=Jutil.getConnection();
stmt=conn.prepareStatement("sql語句");
stmt.setString(1,c.getName());
.
.
.
.
stmt.getexcuteUpdate();
}catch(Exception e){
throw new DaoException(e);
}finally{
Jtuil.release(*,*,*);*參數名字
}
void addCustomer(Customer c);
//根據id刪除客戶資訊。名字型現要實現的功能
void delCustomerById( String customerId);
//更改客戶的資訊 IdIsNullException如果參數id為null,則拋出異常
//建立異常包,命名IdIsNullException類繼承Exception
void updateCustomer(Customer c) throw IdIsNullException;
//查詢所有使用者資訊
List<Customer> findAll();
//根據客戶id查詢客戶資訊(單個某個客戶)
Customer findCustomerById(String customerId);
注意;
查詢方法還可拓展,比如根據使用者的其他愛好,地址,等資訊進行尋找使用者
(2)daoimlents包對dao具體實現,就是功能的實現在此書寫,
四大方法增刪改查
daoimlents implements dao{}
5、建立與資料庫連接的Jutil包
其中書寫Jutil類
兩個方法:
//書寫資料連結
//為增加擴充性一般情況,代碼中的String字串都寫在properties設定檔中,Class.forname("com.mysql.jdbc.Driver");
//建立properties文本,然後寫入
className=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/databaseName
user=root
password=123456
建立讀取此文本的方法
InputSteam in= Jutil.class.getClassLoader.getReSourseAsStream("propertiesname.properties");
Properties pro = new Properties();
pro.load(in);
url=pro.getProperties("url");
password=pro.getProperties("password");
user=pro.getProperties("user");
className=pro.getProperties("className");
public static Connection getConnection(){}
//書寫資源釋放
public static void relase(ResultSet st,Statement st,Connection conn){}
6、書寫模板位置
7、測試
java.lang.NoClassDefFoundError: Could not initialize class com.Jutil.Jutil
at com.daoImpl.CustomerDaoImpl.addCustomer(CustomerDaoImpl.java:44)
at com.test.CustomerDaoImplTest.testAddCustomer(CustomerDaoImplTest.java:30)
資料庫名字與javabean的名字不同,設定檔名字不同,沒有把jar包變成buildpath
8、業務層搭建
建立service介面
書寫service實現
因為業務層調用dao層
private CustomerDao dao= new CustomerDaoImpl();
9、servlet和jsp書寫
開啟web.xml將servlet設為首頁
servlet調用service所以需要
private Service s = new ServiceImpl();
servlet 建立顯示所有資訊的介面的串連
List<Customer> cs = s.findAll();
request.setAttribute("cs",cs);
request.getRequestDispathcher("/listshow.jsp").forword(request,response);
Jsp+servlet+mysql搭建套路