Home  >  Article  >  Java  >  How does Javaweb build a complete personal blog system?

How does Javaweb build a complete personal blog system?

WBOY
WBOYforward
2023-04-21 21:55:071196browse

Basic process of the project

1. Preparation work

Dependency package introduced in pom.xml

<dependencies>
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf</artifactId>
        <version>3.0.12.RELEASE</version>
    </dependency>

    <!-- Servlet依赖包:官方提供的servlet标准 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <!-- 开发编译时需要这个依赖包,运行时不需要 -->
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.49</version>
    </dependency>
    
	<!-- 数据绑定包,提供JAva对象与JSON数据格式进行序列化 -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.12.3</version>
    </dependency>
    
    <!--    引入单元测试框架,方便我们做测试    -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.1</version>
    </dependency>
</dependencies>

The Jackson dependency is introduced for serialization, Deserialization operation
Function: Enable data and objects to be converted to each other to ensure data integrity

Jackson is a Java class library used to process JSON format data. It has very good performance and often Used for JSON serialization (converting objects to JSON strings) and deserialization (converting JSON strings to specified data types)

Serialization and deserialization operations:

public class WebUtil {

    //判断是否登录,通过请求对象获取session,如果session存在且登录时
    // 保存的键为user,值是用户对象,这个数据存在,就表示已登录
    //返回user:已登录就返回session中保存的用户,未登录返回null
    public static User checkLogin(HttpServletRequest req){
        User user = null;
        //如果从tomcat保存的session的map数据结构中,获取session,false表示获取不到,返回null
        HttpSession session = req.getSession(false);
        if(session!=null){
            user = (User)session.getAttribute("user");
        }
        return user;
    }

    //这个对象可以使用单例
    private static ObjectMapper M = new ObjectMapper();

    //反序列化:转换一个输入流中包含的json字符串为一个java对象
    //使用泛型:传一个什么类型给我,就返回一个该类型的对象
    public static <T> T read(InputStream is,Class<T> clazz){
        try {
            return M.readValue(is,clazz);
        } catch (IOException e) {
            throw new RuntimeException("json反序列化出错",e);
        }
    }

    //序列化:将一个任意类型的java对象,转换为一个json字符串
    public static String write(Object o){
        try {
            return M.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("json序列化出错",e);
        }
    }

2. Database design

1. Create the required table:

  • user (user table)

  • acticle( Article table)

2. Design the corresponding database entity class:

How does Javaweb build a complete personal blog system?

3. Database connection tool:

//数据库工具类:提供获取数据库连接,释放资源的统一代码
public class DBUtil {
    //静态变量,是类加载的时候初始化,只执行一次
    private static MysqlDataSource ds;
    //一个程序,连接一个数据库,只需要一个连接池,其中保存了多个数据库连接对象
    //1.获取连接池,内部使用,不开放
    private static DataSource getDataSource(){
        //ds类加载的时候,初始化为null,方法使用的时候,每次都判断一下
        if(ds==null){//判断为空,就创建及初始化属性
            ds=new MysqlDataSource();
            ds.setURL("jdbc:mysql://127.0.0.1:3306/blog");
            ds.setUser("root");
            ds.setPassword("010124");
            ds.setUseSSL(false);//不安全连接,如果不设置,也不影响,只是有警告
            ds.setCharacterEncoding("UTF-8");
        }
        return ds;
    }

    //2.获取数据库连接对象:开放给外部的jdbc代码使用
    public static Connection getConnection(){
        try {
            return getDataSource().getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("获取数据库连接出错,可能是url,账号密码写错了",e);
        }
    }
    
    //3.释放资源
    //查询操作需要释放三个资源,更新操作(插入,修改,删除)只需要释放前两个资源
    public static void close(Connection c, Statement s, ResultSet r){
        try {
            if(r!=null) r.close();
            if(s!=null) s.close();
            if(c!=null) c.close();
        } catch (SQLException e) {
            throw new RuntimeException("释放数据库资源出错",e);
        }
    }

    //提供更新操作方便的释放资源功能
    public static void close(Connection c, Statement s){
        close(c,s,null);
    }

    public static void main(String[] args) {
        System.out.println(getConnection());
    }
}

4. CRUD operation (Dao class) of user table and article table:

How does Javaweb build a complete personal blog system?

3. Prepare the front-end page

1. Write before Deploy a good front-end static page to the webapp directory

2. Encapsulate ajax:

In the front-end and back-end interaction, we need to use ajax for data interaction
Put the previously encapsulated ajax function Copy it and put it in a separate js file for subsequent use

function ajax(args){//var ajax = function(){}
    let xhr = new XMLHttpRequest();
    // 设置回调函数
    xhr.onreadystatechange = function(){
        // 4: 客户端接收到响应后回调
        if(xhr.readyState == 4){
            // 回调函数可能需要使用响应的内容,作为传入参数
            args.callback(xhr.status, xhr.responseText);
        }
    }
    xhr.open(args.method, args.url);
    //如果args中,contentType属性有内容,就设置Content-Type请求头
    if(args.contentType){//js中,if判断,除了判断boolean值,还可以判断字符串,对象等,有值就为true
        xhr.setRequestHeader("Content-Type", args.contentType);
    }
    //如果args中,设置了body请求正文,调用send(body)
    if(args.body){
        xhr.send(args.body);
    }else{//如果没有设置,调用send()
        xhr.send();
    }
}

3. Design a class: used to return to the front-end ajax callback

//设计一个类,用于返回给前端ajax回调
public class JsonResult {
    private boolean ok;//表示执行一个操作是否成功
    private Object data;//操作成功,且是一个查询操作,需要返回一些数据给前端

	//同样省略getter、setter和toString
}

4. Implement the Servlet that matches the front-end Required functions

How does Javaweb build a complete personal blog system?

5. Difficulties of the project

  • realize that users are not allowed to access the homepage content without logging in and are redirected to the login page, secondly It is also illegal for users to access an interface without logging in. They must also be redirected to the login page.

  • After the article is published, a new article must be inserted into the database. View the full text To convert data in markdown format to HTML

  • After successful login, you must also create a session and save user information for later use

The above is the detailed content of How does Javaweb build a complete personal blog system?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete