Diary System
Written in front
The system adopts the traditional MVC development mode of Jsp+Servlet+Model, the front-end uses the mainstream BootStrap technology, and the database uses Mysql to realize the personal diary system. The highlights are the comprehensive use of Bootstrap, the use of ckeditor and FileUpload component to upload pictures, and the application of MD5 encryption (the project is not developed by myself, but learning the knowledge therein).
I. Demand:
- Landing registration
- Addition and deletion of diary
- Classification of diaries (additions, deletions and revisions)
- Personal Center (avatar, name, signature, etc.)
2. Database design:
-
Three tables:
t_user (userId,userName,password,nickName,imageName,mood)//password is set longer (50) because it uses MD5 encryption.
T_diary (diaryId, title, content, type Id, release Date) / content is long, data type is text, release Date format is datetime
t_diaryType(diaryTypeId,typeName) -
Primary and foreign key settings (foreign keys: Primary keys in other tables are called foreign keys):
The type Id foreign key in t_diary is associated with the diaryTypeId primary key in t_diaryTaye (the corresponding relationship is many-to-one)
navicat sets foreign keys:
Foreign key name: can not fill in, the system automatically generated;
Field Name: Set'typeId'as the foreign key;
Reference DadaBase: A database associated with foreign keys;
Reference Table: Associated tables;
Outside field name: the associated field (here is "diaryTypeId", which can be the same as the field name);
Delete: The action selected when deleting
When refreshing: the action selected when updating
(When setting foreign keys, there are four values to choose from when deleting and updating: CASCADE, NO ACTION, RESTRICT, SET NULL. I tried them all myself. The differences are as follows:
CASCADE: When the parent table deletes and updates, the child table deletes and updates the associated records.
SET NULL: When the parent table delete and update, the child table will set the column where the foreign key field of the associated record is located as null, so note that the foreign key cannot be set as not null when designing the child table.
RESTRICT: If you want to delete the records of the parent table and have records related to the parent table in the child table, you are not allowed to delete the records in the parent table.
NO ACTION: With RESTRICT, it is also the first time to check the foreign key. -
Notes on the design table:
1. For the id primary key: int, primary key, not allowed to be empty, automatic increment
2. For dates, special formats are required: such as datetime
3. Long text, such as diary content, can be formatted as text.
4. For other attributes, as long as it contains Chinese character type, such as name, password will be set to varchar type, length can be set according to demand.
3. Background code
Four bags:
Dao: Data Access Object Layer
Model: Model layer
Util: Tool Layer
Web: Web Access Layer
- Util:
Connect to the database:
Note: Add Mysql to get jar package: mysql-connector-java
public class DbUtil2 { private String dbUrl="jdbc:mysql://localhost:3306/db_diary"; private String dbUserName="root"; private String dbPassword="l1542735938"; private String jdbcName="com.mysql.jdbc.Driver"; //Getting Connections: First load the driver, then connect public Connection getCon() throws Exception{ Class.forName(jdbcName); Connection con =DriverManager.getConnection(dbUrl,dbUserName,dbPassword); return con; } //Close connection public void closeCon(Connection con) throws Exception{ if (con!=null){ con.close(); } }
- model
Build related classes according to the tables in the database. - dao
Used to verify the password of login account, etc.
For example, verify the login information:
public User login(Connection con ,User user) throws Exception{ User resultUser=null;//Return Null if it does not exist //Find out if there is a user in the database String sql="select *from t_user where userName=?and password=?"; PreparedStatement pstmt=con.prepareStatement(sql); pstmt.setString(1, user.getUserName()); pstmt.setString(2, user.getPassword()); ResultSet rs=pstmt.executeQuery(); if(rs.next()){//If it exists, initialize resultUser resultUser=new User(); resultUser.setUserId(rs.getInt("userId")); resultUser.setUserName(rs.getString("userName")); resultUser.setPassword(rs.getString("password")); } return resultUser; }
- web
Matters needing attention:- First add tomcat's package (buildPath)
- Inheriting HttpServlet
- doPost,doGet methods that override parent classes
Code
package web; import java.io.IOException; import java.sql.Connection; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dao.UserDao; import model.User; import util.DbUtil; public class LoginServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Get the session object to save the current login object HttpSession session=req.getSession(); //Get front-end user information for validation String userName=req.getParameter("userName"); String password=req.getParameter("password"); Connection con= null; DbUtil dbUtil=new DbUtil(); UserDao userDao=new UserDao(); try { con=dbUtil.getCon(); User currentUser=userDao.login(con, new User(userName,password)); if(currentUser==null){ }else{ session.setAttribute("currentUser", currentUser); resp.sendRedirect("main.jsp"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { dbUtil.closeCon(con); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }