[Newbie] Implement a blog system with front-end and back-end separation based on servlet and deploy it to Linux

A good memory is not as good as a bad writing.
Record the completion process for novices.
This article mainly implements a servlet-based front-end and back-end separation blog system and deploys it on a Linux cloud server.

Blog system with separate front-end and back-end

什么是servlet?
	servlet是Tomcat这个HTTP服务器提供给Java的一组API,来完成构建动态页面这个任务.
什么是动态页面?
	指用户不同/时间不同/输入的参数不同,页面内容会发生变化.
什么是前后端分离?
	前端只向后端请求数据,而不请求具体的页面,后端也仅仅是返回数据.
	这样的设定使前端和后端更加解耦,由浏览器进行具体的页面渲染,减少了服务器的工作量.

1. Preparation work

1. Environment and software

  • Packet capture tool: Fiddler Classic
  • Deployment: tomcat 8 series (corresponding to servlet3.1)
  • Environment: jdk1.8
  • Back-end development tools: IDEA 2021 version, MySQL
  • Front-end development tool: VScode (the version that supports win7 is up to 1.70.3)

2. Blog system page design

①.Blog list page (blog_list.html)

Insert image description here

②.Blog text page (blog_detail.html)

Insert image description here

③. Blog login page (login.html)

Insert image description here

④. Blog editing page (blog_edit.html)

Insert image description here

3. Create a project (maven project)

Create a Maven project using IDEA

Menu->File->New Project->Maven

**picture**
After the project is created, you will get the following figure:

  • src represents the directory where the source code is located
  • main/java represents the root directory of the source code. Subsequently created .java files will be placed in this directory.
  • main/resources represents the directory where some resource files of the project are located
  • test/java represents the root directory of the test code

Insert image description here

4. Create a directory (copy the previous front-end page)

Create a webapp directory in the main directory, parallel to the java directory.

Create a WEB-INF directory inside the webapp directory,

And create a web.xml file, copy the following code into web.xml.

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
    <display-name>Archetype Created Web Application</display-name>
</web-app>

Insert image description here
Copy the previously written front-end page to the webapp directory

Insert image description here

5.Introduce dependencies (related jar packages)

Introduce the jar packages, mysql, and jackson that the Servlet API depends on in the pom.xml file.

Central Warehouse official website

Search for "servlet" in the central repository, select version 3.1.0, and copy the provided xml to pom.xml

Insert image description here

Search for "mysql" in the central warehouse, select version 5.1.49, and copy the provided xml to pom.xml

Insert image description here

Search for "jackson" in the central repository, select version 2.14.2, and copy the provided xml to pom.xml.

Insert image description here
Add the following to pom.xml,

Insert image description here

2. Design database and write code

1. Design database

当前的博客系统中,主要涉及两个实体:博客,用户.

创建两张表来表示博客和用户.

而博客与用户之间的关系:
	一对多,一个用户可以写多个博客,一个博客只属于一个用户.
	
因此创建的两张表如下:
	user(userId,username,password)
	blog(blogId,title,content,postTime,userId)

2. Write database code

①.Write database and table creation statements

Write the database and table creation statement and save it as db.sql for subsequent use when deploying other machines.
The contents of this table need to be manually copied to MySQL.

Insert image description here

②. Encapsulate database connection operation (DBUtil.java)

Insert image description hereInsert image description here

③.Create entity classes (classes corresponding to records in the table)

What attributes are in the entity class are closely related to the columns in the current table

User table -> User class correspondence (an object of User corresponds to a record in the table)
blog table -> Blog class correspondence (an object of Blog corresponds to a record in the table)

Insert image description here

There are some differences between the get and set methods for obtaining time.

Insert image description here

④.Encapsulate the addition, deletion, modification and query of the database

Create BlogDao.java for the blog table

Create UserDao.java for the user table

Insert image description here
You still need to pay attention to the time acquisition in adding a new blog in BlogDao.java.

Insert image description here

3. Implement blog function

1. Implement the function of obtaining blog list (blog list page)

通过数据库读取,数据显示到页面上.

基本思路:
	让博客列表页在加载的时候,通过ajax给服务器发一个请求,
	服务器查获数据库获取博客列表数据返回给浏览器,
	浏览器再根据数据构造页面内容.
	
实现步骤:
	1.约定前后端交互接口
	2.开发后端代码(BlogServlet.java 重写doGet方法)
	3.开发前端代码(blog_list.html)

①. Agree on the front-end and back-end interaction interfaces

On the blog list page, under the function of getting the blog list, what request is sent by the front end and what response is returned by the back end.

Insert image description here

②.Implement the back-end code (BlogServlet.java rewrites the doGet method)

Insert image description here

③.Implement the front-end code (blog_list.html)

During the loading process of the blog list page, an ajax request is triggered, the data in the server is accessed, and the obtained data is constructed into the page.
Modify the previously written blog list page.

Insert image description here

Every time a function is implemented, check in time to see if it has been completed.

Insert image description here

Capture packets

Insert image description here

2. Blog details page

基本思路:
	点击"查看全文"按钮,就能跳转到博客详情页中,跳转过去之后,
	在博客详情页中发起一个ajax,从服务器获取到当前的博客具体内容,再显示出来.

实现步骤:
	1.约定前后端交互接口
	2.实现后端代码(BlogServlet.java 重写doGet方法)
	3.实现前端代码(blog_detail.html)

①. Agree on the front-end and back-end interaction interfaces

Ⅰ关于请求
	此时路径和博客列表页是同一个.
	之前的博客列表,请求里没有query string,而现在的博客详情页是带有query string.
	因此就可以判断query string,存在就返回博客的详情页,不存在就返回博客列表.
	
Ⅱ关于响应
	此时的content不再像博客列表页一样截断了,它是完整的正文内容.

Insert image description here

②.Implement the back-end code (BlogServlet.java rewrites the doGet method)

Insert image description here

③.Implement the front-end code (blog_detail.html)

Modify the previously written content.

Insert image description here

3. Login page

基本思路:
	在此处输入用户名和密码,点击登录,就会触发一个http请求,
	服务器验证用户名和密码,就可以根据结果判定是否登录成功,
	如果成功就跳转到博客列表页.

实现步骤:
	1.约定前后端交互接口
	2.修改后端代码(LoginServlet.java 重写doPost方法)
	3.修改前端代码(login.html)
		把页面里加上form表单,使点击登录操作能够触发请求

①. Agree on the front-end and back-end interaction interfaces

Ⅰ关于响应
	得是form表单,响应是302,才能够进行页面跳转(form表单本身就会触发页面跳转)
	如果是ajax请求,响应也是302,但是无法跳转(ajax本身不会触发页面跳转)

Insert image description here

②. Modify the back-end code (LoginServlet.java rewrites the doPost method)

Insert image description here

③.Implement the front-end code (login.html)

Add a form to the page so that clicking on the login operation can trigger a request.

Insert image description here

4. Implement page mandatory login requirements

当用户访问博客列表页/详情页/编辑页,要求用户必须是已经登陆的状态,
如果用户还没登陆,就强制跳转到登录页面.

基本思路:
	在页面加载的时候,专门发起一个新的ajax(一个页面可以发起多个ajax请求),
	以博客列表页为例,会先发一个请求获取博客列表页,再发个ajax获取用户的登录状态,
	如果未登录,页面就会跳转到登录页.

实现步骤:
	1.约定前后端交互接口
	2.实现后端代码(LoginServlet.java 重写doGet方法)
	3.实现前端代码(好几个页面里)

①. Agree on the front-end and back-end interaction interfaces

Ⅰ关于响应
	响应就把当前登录的用户信息返回回来,
	如果未登录,就返回一个userId为0的user对象.

Insert image description here

②.Implement the back-end code (LoginServlet.java rewrites the doGet method)

Insert image description here

③. Implement front-end code (blog_list.html / blog_edit.html / blog_detail.html)

Insert image description here

5. Display user information

1.如果是博客列表页,此处显示登录用户信息.
2.如果是博客详情页,此时显示的是该文章的作者.

实现步骤:
	1.约定前后端交互接口
	2.修改后端代码(AuthorServlet.java 重写doGet方法)
	3.修改前端代码

①. Agree on the front-end and back-end interaction interfaces

Ⅰ.关于博客列表页
	后端代码已经有了,只需稍微调前端代码,把得到的用户信息显示出来即可.
	
Ⅱ.关于博客详情页
	重新来实现

Insert image description here

②.Implement the back-end code (AuthorServlet.java rewrites the doGet method)

Implementation code for displaying user information function on blog details page

Insert image description here

③.Implement front-end code

Blog list page (blog_list.html), add user information to the previous code.

Insert image description here

Blog details page (blog_detail.html, getAuthor() function)

Insert image description here

6. Exit the login state (logout)

判定登录状态:
	1.看是否能查到Http Session对象
	2.看session对象里有没有user
	
实现退出登录:销毁HttpSession,或者销毁user
但是getSession能够创建获取会话,没有删除会话的方法,直接删除不好删,
可以通过设置会话的过期时间来达到类似的效果.
因此更好的办法是将user对象销毁,使用removeAttribute就删了.

之前的逻辑中,httpsession 和里面的user一定是一荣俱荣,一损俱损.
但是引入注销逻辑后,就会出现有httpsession无user的情况,
因此之前的判定登陆状态,也要判定user.

实现步骤:
	1.约定前后端交互接口
	2.修改后端代码(LogoutServlet.java 重写doGet方法)
	3.修改前端代码

①. Agree on the front-end and back-end interaction interfaces

②.Implement the back-end code (logoutServlet.java rewrites the doGet method)

Insert image description here

③.Implement front-end code

The request at this time is triggered through the a tag and is no longer ajax.

Insert image description here

7. Publish a blog

实现步骤:
	1.约定前后端交互接口
	2.实现后端代码(BlogServlet.java doPost)
	3.实现前端代码

①. Agree on the front-end and back-end interaction interfaces

使用form表单
同时让form里面能够感知到博客的内容.

一篇博客:
	blogId 自增主键,数据库自己生成
	title 
	content
	postTime 当前时刻
	userId 作者信息,看提交的用户是谁,从会话中就能够拿到
	因此只需要知道title和content

Insert image description here

②.Implement the back-end code (BlogServlet.java rewrites the doPost method)

Insert image description here

③.Implement front-end code

Insert image description here

in
Insert image description here

这是editor.md文档要求的写法.
editor.md 对于form表单也是支持的,就是可以在form里放一个隐藏的textarea.
editor.md 就会自动把用户输入的markdown内容贴写道textarea里,
后续点击submit就能自动提交.

4. Deploy on Linux

1.Linux environment setup

Purchase a cloud server directly from a server manufacturer such as Tencent Cloud or Alibaba Cloud.
Using a cloud server not only makes the environment easy to set up, but also avoids trouble. Projects deployed on the cloud server can be directly accessed by the external network,
making the programs you write real. For everyone to use.

①.Enter the official website to purchase cloud servers

Tencent Cloud Service Organ Network

Operating system select CentOS 7.6 64-bit

Insert image description hereInsert image description here

②. Check the public IP address and reset the password

After the purchase is completed, you can find the server you purchased in the console. Click on it to see the public IP address of the server.

Insert image description here

You need to set a password for first time use

Insert image description here

③. Use a separate terminal tool to log in

About copy and paste under XShell Copy
: ctrl + insert
Paste: shift + insert

Install and download XShell link

After installation, open the interface as shown in the figure

Insert image description here
Click on file and select New

Insert image description here
Seeing the command prompt means the connection is successful.

Insert image description here

④.Install the corresponding software program

Ⅰ.jdk
直接使用包管理器进行安装(基于yum安装)
安装的这个过程需要联网(云服务器本身就是联网的)

语句:
	找到要安装的包名
	yum list | grep jdk
	进行安装
	yum install java-1.8.0-openjdk-devel.x86_64

Insert image description here

Insert image description here

安装后,查看是否安装成功,显示如下就是安装成功了.

语句:
	javac

Insert image description here

Ⅱ. tomcat 8 series
手动安装tomcat,从官网上下载的.zip压缩包,上传到Linux上,就可以直接使用了.

将在官网下载的.zip压缩包拖拽到Linux里.
如果拖拽失败,可能需要先输入:yum install lrzsz

Download the Tomcat compressed package, drag and drop the Tomcat official website link
Insert image description here
into Linux.

Insert image description here

再解压压缩包,如果解压失败,可能需要先输入:yum install unzip

语句:
	unzip apache-tomcat-8.5.88.zip

Insert image description here

进入tomcat的bin目录,给所有的.sh文件赋予可执行权限

语句:
	cd apache-tomcat-8.5.88/
	ll
	cd bin/
	ll
	chmod +x *.sh
	ll
	
.sh文件都变成绿色,就是可执行文件了.

Insert image description here

Ⅲ.mysql
关于mysql
yum上的是MariaDB,从实用角度上MariaDB和MySQL之间是兼容的.

安装语句:
	安装mariadb服务
	yum install -y mariadb-server
	安装mariadb命令行客户端
	yum install -y mariadb
	安装 mariadb C library
	yum install -y mariadb-libs
	安装 mariadb 开发包
	yum install -y mariadb-devel
	启动服务
	systemctl start mariadb
	设置服务开启自启动
	systemctl enable mariadb
	查看服务状态
	systemctl status mariadb
	使用命令行客户端尝试连接
	mysql -uroot

Just enter the above statements one by one, and finally the connection is successful.

Insert image description here

关于数据库中中文显示乱码问题.解决方法如下,依旧逐条输入语句.


语句:
	查看数据库默认编码格式
	show variables like 'chara%';
	退出数据库(或者按ctrl + d)
	quit;
	修改配置文件/etc/my.cnf
	vim /etc/my.cnf
	重启mysql服务
	systemctl restart mariadb
	mysql -uroot -p
	再次查看编码格式
	show variables like 'chara%';

Insert image description here

Insert image description here

在打开的my.cnf文件中,添加以下标红语句.
如果没有[client],[mysql],[mysqld]其中任何字段,就自己添加上去

关于vim的一些操作
vim是文本编辑器
创建文件/打开文件 : vim [文件名]
进入插入模式:
	vim打开文件后是普通模式,需要进入插入模式才能进行文本编辑.
	使用i键可以进入插入模式.
保存:
	在插入模式下不能保存文件,需要先回到普通模式,按下esc回到普通模式.
	在普通模式下输入:w再按下回车即可保存文件.
退出:
	在插入模式不能退出,需要先回到普通模式.
	在普通模式下输入:q再按下回车即可退出.
	也可以直接使用:wq同时执行保存和退出.

语句:
	[mysql]
	default-character-set=utf8
	
	[mysqld]
	datadir=/var/lib/mysql
	socket=/var/lib/mysql/mysql.sock
	symbolic-links=0
	character-set-server=utf8
	default-storage-engine=innodb
	
	[client]
	socket = /var/lib/mysql/mysql.sock
	default-character-set=utf8

Insert image description here
After modifying and saving the file, restart the mysql service and check the encoding format.

Insert image description here

Chinese is displayed normally

Insert image description here

2. Deploy the web project to Linux

①. Create database and table in mysql of cloud server

Copy and paste the contents of the previously written db.sql into the cloud server mysql client and run it directly.

The database and table creation is completed, as shown in the figure.

Insert image description here

②. Fine-tune the code

The local database, port number, user name, password and cloud server database may be different, so fine-tuning is required.

Change the password in the DBUtil.java file. If the password is not set deliberately, the password here will be empty.

Insert image description here

You may also need to change the port number and check the port number used by mysql.

语句: 
	netstat -anp | grep mysql

Insert image description here

③Use waven to create a war package

In the pom.xml file, add the statement

Insert image description here
Use maven to build a war package.

Click Maven on the right, select the package in the Lifecycle directory, right-click and select Run Maven Build.

Insert image description here

Generate the war package in the target directory.

Insert image description here

④.Copy the war package to the cloud server

Copy the war package to the webapps directory of the cloud server.

Enter the webapps directory of tomcat

语句:
	 cd apache-tomcat-8.5.88/
	 cd webapps/
	  ll
	  
注意: cd apache-tomcat-8.5.88/ 这里的apache-tomcat-8.5.88/是跟自己下载的tomcat压缩包文件名对应的

Insert image description here

Drag the war package into it

Insert image description here
Switch back to the directory and start the tomcat server.

语句:
	cd ..
	cd bin/
	sh startup.sh

Insert image description here

Use netstat to verify whether tomcat starts successfully.

语句: 
	netstat -anp | grep 8080

Insert image description here

In addition, in order to ensure the security of the machine, cloud server manufacturers have introduced security mechanisms. By default, only port 22 of the machine is accessible to the outside world. If you want other ports to be accessed from the outside, you need to manually open them.

Therefore, if you want to access the web page normally, you need to open port 8080, log in to Tencent Cloud, click on the recently purchased cloud server, select the firewall option, and then choose to add rules.

Insert image description here
Just open port 8080. After clicking OK, it may take a few minutes for it to take effect.
Insert image description here

⑤.Verification

Web page to verify whether deployment is successful

Blog login page

Blog login page

Insert image description here
Blog list page

Insert image description here
Blog details page

Insert image description here
Blog edit page

Insert image description here

at last

My project source code address: github-BlogSystem

Guess you like

Origin blog.csdn.net/tenju/article/details/131159468