A simple demo of Web Contact System - my attempt to connect database in a dynamic webpage through Java servlet. See scottsun folder for details
All pages are dynamic pages except Add Contact Page - [addContact.html]
- MyEclipse 2014: IDE tool of your choice.. I have MyEclipse 2014 set up on my computer already
- Sublime Text: I use this to write addContact.html, ContactSystem.sql, and db.properties
- MySQL
- Tomcat
- JavaSE
SQL for your database, you can change the database name and information inside, but if you do that, you neeed to change your property file and Java code too.
ContactSystem.sql
create database webcontactsystem;
use webcontactsystem;
create table Contact (
id int not null primary key auto_increment,
firstName char(20) not null,
lastName char(20) not null,
gender char(1) not null,
age tinyint not null,
tel char(30),
email char(30)
);
db.properties - save this file under /webapps/../WEB-INF/classes
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/webcontactsystem?useSSL=true
user=root
password=123456
You need to import the following libs:
beanutils
beanutils logging
mysql connector
My order of coding each file:
- Contact.java
- JDBCUtil.java
- BaseDao.java
- ContactDao.java
- ContactDaoImplements.java
- addContact.html
- web.xml
- AddContactServlet.java
- ListContactServlet.java
- DeleteContactServlet.java
- QueryContactServlet.java
- UpdateContactServlet.java
now you are done and you can start testing
- database table field name to be consistant with your code.
- do not miss a space when generating html in the servlet,
I made a mistake that missed a space here and took me so long to find out(crying face):
right before method=POST, it need a space, otherwise, it will not submit to UpdateContactServlet, correct coding:
html += "<form action=UpdateContactServlet?id=" + contact.getId() + "method=POST>";
html += "<form action=UpdateContactServlet?id=" + contact.getId() + " method=POST>";
- Everything above can be done in JSP or Spring framework for better result, but here we are focusing on CRUD to the database from webpages.