Personal blog system (separated front-end and back-end)

努力经营当下,直至未来明朗!


普通小孩也要热爱生活!

1. Project Introduction

The personal blog system is implemented by separating the front and back ends, using a database to store relevant data, and using tomcat for project deployment. The front-end mainly consists of four pages: login page, list page, details page and edit page. The above simulation implements the simplest blog list page. It combines the backend to implement the following main functions: login, edit blog, logout, delete blog, and forced login.
However, this project does not have a user registration function. User information can only be stored in the database in advance and then verified and logged in; and user avatars cannot be set by themselves. During the writing process of the front-end page, the avatar picture has been written as static; The number of articles and categories in the user information are not implemented in the back-end, and are directly written as static in the front-end page.


2. Project effects

Tomcat must be turned on to operate the following pages.

  1. log in page
    Insert image description here

  2. List page/Home page
    1

  3. Blog details page
    2

  4. edit page
    3


3. Project realization

1. Basic process of software development

① Feasibility analysis;
② Requirements analysis: clarify what problems the program will solve, what it will look like, and what functions it will have. (In actual development, it is formulated by the product manager)
③ Outline design
④ Detailed design
⑤ Coding
⑥ Testing
⑦ Release

2. Blog system requirements analysis

① Realize the display function of blog list page
② Realize the display function of blog details page
③ Login function (registration is not implemented for the time being)
④ Restrict user permissions (mandatory login)
⑤ Display user information
⑥ Realize logout (log out)
⑦ Publish blog
⑧ Delete blog

3. Blog system outline design

(When writing code, you must "plan before taking action")
In fact, the main thing here is [database design]

Our current business is relatively simple and only requires two tables:

① Blog table blog (blogId, title, content, postTime, userId)
② User table user (userId, userName, password) (Functions such as Gitee address and article classification are not considered for now)

4. Create maven project

Note: ① auto-increment starts from 1
② The size of text is 64kb. Blog content generally does not exceed 64kb, and screenshots in blogs are not stored together with the text.

5. Write code for database operations

  1. Introduce dependencies: servlet3.1.0, mysql5.1.49, jackson2.13.4.1
  2. The DataSource that encapsulates the database (single case mode + thread safety)
    not only encapsulates the DataSource, but also encapsulates the establishment and disconnection of the database.

Supplement:
① ctrl+alt+t: surround function
② Connection is java.sql.Connection, not java.mysql.Connection

  1. When closing and releasing resources, the first way is to try...catch the three connections that need to be released respectively. The second way is to use only one try...catch connection for the three connections that need to be released.

Writing method one is better.
Reason: If an exception is thrown in a certain link in the first writing method, it will not affect the subsequent close operation. The second way of writing will enter the catch once an exception occurs. At this time, the subsequent close cannot be executed, which will cause resource leakage.
(Directly throwing exception throws is also written in the same way, which will cause resource leakage.)

  1. Create an entity class based on requirements.
    An entity class object corresponds to a record in the table.

How to write entity class?
——How to write the table structure, how to write the entity class.

The datetime and timestamp types in mysql are represented by TimeStamp in java.

  1. To further encapsulate the additions, deletions, modifications and queries involved in the above entity classes, that is, to encapsulate the jdbc code.
    Dao: Data Access Object
    The operation of accessing the database can be performed using these Dao objects.

statement.executeUpdate(); The data returned indicates how many rows are affected

6. Conduct front-end and back-end interaction (key points)

Let the page initiate an http request and the server returns an http response. (You need to agree on what the http request looks like and what the response looks like)
1)Blog list page:
① Don’t hard-code the data, but let the page get the current blog list from the database.

(First paste all relevant files of the front end into the webapp directory)

② When the page is loading, it initiates an http request through ajax and obtains the blog list data from the server.
Insert image description here

③ When there is a problem with the web, the first thing that comes to mind is "Capture packets” to see if it is a front-end or back-end problem. (If some are not captured, force refresh ctrl+f5 )

Note: The favicon that appears in fiddler is a request sent by the browser to obtain the page icon. If the website does not have an icon, 404 will appear.
10

① In a program with separate front-end and back-end, getting the page and getting the data in the page are separate requests.
② If there is only a page without data, and the packet capture cannot capture the request to obtain data, it means that there is a problem with the front-end code, and the front-end did not send the ajax request correctly.

Note: The method will only take effect after it is called! !
Be careful! ! Guaranteed that no null pointer exception will occur! !

Problems and solutions:
① What we want to present isformattime, but you will find that the timestamp appears at this time!
11
Reason :

Through packet capture, it is found that the response data returned by the server is a timestamp.
12
In the server code, the time queried from the mysql database is placed in the postTime attribute, and then it is converted into a json string through jackson and returned; that is: In the process of converting to json, it is turned into a timestamp.
13

Solution :

So how does Jackson obtain the timestamp in the Blog object? Obtained through the getter method.
15

So just change the getter method so that it returns a String instead of a TimeStamp. String is a formatted time and date!
16

① ThisSimpleDateFormat classTimestamp can be converted into formatted time!
(For usage examples, please refer to: SimpleDateFormat class usage )
17
② The timestamp needs to be converted into formatted time. The specific format needs to be specified in the construction method!
③ (The parameter format can be specified by yourself, but the specific letters cannot be changed. Each has its own meaning, such as MM means month, mm means minute. The specific parameter meaning can be confirmed online when using it!)

18
(Format time and date)


② In addition, another problem was found: in the listArticle orderThe most recently released should be at the top, but currently they are arranged in order of first released at the top.
20

Therefore, the solution : add a sort when querying.
21


③ At this time, if the inserted blog content is relatively long, it will occupy a large list page because the entire text is displayed; but logically speaking, the blog list page should display the main text."Summary" information

22
(long article)

Solution :
Truncate the content in the blog list page until the length reaches a certain value.Take out a part of the substring. (It’s ok if you decide the length yourself)
23

25
(Effect)

[Note] When there is a problem with our program, how should we solve it?

① Be sure to sort out the process of the code in question
② Be able to find the relevant code (debugging, not looking by comparison!!)


2)Implement blog details page
① Click to view the full text to jump to the details page, and see the corresponding blog text in the details page.

② Processing method:
Click to view the full text. At this time, a get request will be initiated, which is requesting the blog_detail.html page; at this time, we also need to tell the server which blog we are requesting!
Convention: Add query string to the request page URL to identify the specific blog. (The query string has been added for identification when the "View Full Text" button is generated)
28

③ After entering the blog details page, you need to have the blog details page initiate an ajax request again to obtain the blog content corresponding to the current blogId from the server; then the blog details page will add the obtained data to the browser page.

④ Operation steps:
1) Agree on the front-end and back-end interaction interfaces.
Initiate an ajax request on the blog details page to obtain specific blog content.
29
2) Implement server code
to return data according to the above agreement

3) Implement client code
to obtain blog data through ajax requests initiated by the page

Notelocation.search is used to obtain query string
30

(Every time the code is modified, the server must be restarted)

However, you will find that when you click "View Full Text", the page you jump to is still the previous result. This triggers the browser's cache !

① Reason:
The browser needs to obtain the current page data from the remote server through the network, which may be time-consuming. In order to improve efficiency at this time, the approach is to let the browser cache the necessary data; there is no need to access the network next time. Instead, the cache is read directly.
② Method:
Therefore, in order to ensure that the data is obtained from the network, it is necessary to force refresh ctrl+f5 .

If you find a problem with the front-end page, use fn+f12 to call up the console to check for abnormalities.

Supplement:
① The compiler in VS is cl.exe, and the compiler in IDEA is javac... Compilers are generally command line.
②IDE is an integrated development environment, IDE != IDEA


question

① The blog text is expected to be in markdown format (after all, the blog editing page is a markdown editor, the submitted data is in markdown format, and the data stored in the database is also in markdown format, so the final display should also be in markdown format) ② Display
31
results It is plain text (not as expected, expected to be rendered markdown)
32

Solution:
Use the editor.md library to complete rendering.
Introduce editor.md dependency into blog_detail.html
33
35

36
(after rendering)

If you want the background of the content to display a translucent effect, just modify the settings and it will be OK.

37
(This effect is not good)

39
(Transparent means that the current element completely applies the background of the parent element)


3)Blog login
Login logic :

① The user visits login.html and enters the username and password.
② Clicks the login button and initiates a request, submitting the username and password to the server.
③ The server verifies the identity. If the verification is successful, it jumps to the blog details page.

① Agree on the front-end and back-end interfaces
40
(note: requests go to the front-end and responses go to the back-end)

②Write front-end code

41
Be sure to specify the name attribute in order to correspond to the key in the key-value pair!
43

③Write the back-end code
LoginServlet


4) Implemented in blog list page, details page and edit pageAccess requires forced login. (common)

Business logic :

In the blog list page, details page and edit page, an ajax request is initiated when the page is loaded. This ajax request is to obtain the current login status from the server. If you are not currently logged in, you will be redirected directly to the login page. If you are already logged in, no processing will be done.

① Front-end and back-end interactive interface:
50
② Front-end code: Determine whether the status code is 200 or 403. If it is 200, nothing will happen. If it is 403, it will force a jump.
51

③ Back-end code:
It simply checks whether the current user is logged in, that is: obtains the session and the user object in it. If it can be obtained, it means it has been logged in and returns 200, otherwise it returns 403.
52

Because login restrictions and jumps are used in many pages, but we do not need to perform repetitive work, so we directly create a new folder js in the front-end code and create a new file app.js to store these repeated codes. To achieve code reuse.


5) In the list page and details pageDynamically display user information

Logic settings :

① Blog list page: While the page is loading, the currently logged- in user information is obtained from the server and displayed on the page. ② Blog details page: Obtain the blogger
user information from the server while the page is loading , and display the information on the page.

① Front-end and back-end interaction interface:
55
② Write back-end code

56
(I used two sql queries, but it can actually be done with one sql: joint query or subquery)

③ Write front-end code
57

Summary】Writing web program routines
In fact, the functions implemented above do the same thing:

① Business logic sorting
② Design front-end and back-end interaction
③ Write front-end code: basically ajax (send a request) + dom (display on the page according to the request) operation
④ Write back-end code: basically servlet + jdbc + jackson operation
(before and after The order of writing code is uncertain)

Supplement: ① When pictures are stored in the database, the path of the picture
is stored , and the picture is saved on the hard disk in the form of a file. ② It is not recommended to store pictures directly into the database. Pictures are binary data and are not friendly to relational databases.


6)Log out(Logout status)
Windows logout is actually sign out.

Business logic :

① There is a logout button in the navigation bar of the blog list page/details page/edit page, and our implementation is an a tag. When clicked, an http request will be sent to the server (not ajax, but if you want to use Ajax is also OK)
② The http request sent tells the server that we want to log out, and the server will delete the user object in the conversation and redirect to the login page.
③ Note: What is deleted is the user object in the session rather than the HttpSession object, because HttpSession does not have a direct method for deletion (Servlet does not provide it). Although the session can be deleted by setting the expiration time, it is not a good idea. Select; In addition, the condition we implement to determine the login status is that HttpSession exists && user exists, so the user object can be deleted directly here

① Front-end and back-end interactive interface
60

② Front-end code
You only need to set a value for the href attribute of the a tag, and there is no need to write any js code.

Backend code:
LogoutServlet


7)Post a blog

Business logic :

Obtain user-submitted data from the blog editing page and save it to the database. The user will fill in the title and text on the blog editing page, and after clicking "Publish Article", initiate an http request. After receiving the data, the server will construct a Blog object and insert it into the database.

Blog object:
61

① blogId is automatically generated
② title and content are content submitted by the user
③ postTime is directly the time inserted into the database, no need to specify it manually, that is: now()
④ userId: The user who logged in when publishing the article is the author, and the information of the logged in user is in in HttpSession .

① Front-end and back-end interactive interface:
62
② Implement server code (response)

[ Supplement ]
Under normal circumstances, you should be logged in to initiate a POST /blog request, so why do you need to check again whether you are logged in?
Reason :

① What if there is a manual structure? If you use postman to construct the request directly, you can bypass the login and directly insert the blog data.
② To construct a blog object, you need to know the userId. At this time, you can only know the author of the article (userId) if you know who is logged in. The userId comes from the HttpSession object getAttribute.

③ Implementation of front-end code (client code):
(It does not involve js coding either)

63
① When writing < textarea name="content" style="display:none"> < /textarea>, the markdow content entered by the user on the page can be automatically obtained by textarea; but when editor.md needs to be initialized Add a new attribute: saveHTMLtoTextarea: true
65

② I found a problem at this time: the Markdown editor page size has shrunk.
66
This is obviously a problem with the front-end style, so I checked the front-end style (fn+f12)
67
(I found that the blog-edit-container is normal, but the form has shrunk)
③ Also That is to say: if the form tag does not specify a height, it will shrink itself, causing the internal sub-elements to shrink as well.
Solution: Specify a height for the form, just as high as the parent element.
68
69


8)Delete blog

Business logic :

① Authors can only delete their own articles, not other people’s articles.
② There is currently no administrator role.
③ Add a delete button to the navigation bar of the blog details page . When the button is clicked, the delete operation will be triggered. It is an HTTP GET request initiated through the href attribute of the a tag.
④ Verification will be performed when deleting: only if the currently logged in user is the author of the article can it be truly deleted, otherwise it will prompt that there is no deletion permission.

① Front-end and back-end interactive interface:
70

② Implementing the server (back-end code):
Most of the code is used to determine illegal situations. This is a good awareness.

③ Implement browser (front-end) code:

① Add an a tag directly
71

② But you will find that when you click delete, the blogId is not included in the URL, which makes it impossible to delete.
③ So: You can slightly modify the content in the href attribute through js code when the page is loaded, so that the blogId is included in the URL.
75
72

③ Pay attention to the distinction: location.href (full path) and location.seach (query string)
73

location is the global object that comes with the dom api (the global object in js)


4. Project code

  1. Environment:
    IDEA + MySQL + smart tomcat + VSCode

  2. Project layout
    00

  3. Project code:
    Gitee link: Personal blog system


Summarize

  1. Many problems were encountered in the process of implementing a simple personal blog system, among whichConventions on front-end and back-end interactive interfacesExtremely important! !
  2. Only by repeating and practicing can you better understand the project and its implementation.
    yyy

If you have any suggestions or questions, please send a private message or comment directly!
Welcome to the little window! or See you in the comments section!

Guess you like

Origin blog.csdn.net/weixin_54150521/article/details/128448773