Design and implementation of activity module in springboot project?

Time:2020-9-25

Business description

Based on spring, mybatis, springboot, thymeleaf and Ajax technology, the query and addition of active modules are realized.

Project environment initialization

preparation

1. MySQL(5.7)
2. JDK (1.8)
3. Maven (3.6.3)
4. STS(4.7.1)

database initialized

Open the MySQL console and follow the steps below goods.sql Documents.
Step 1: log in to MySQL.

mysql –uroot –proot

Step 2: set the console encoding mode.

set names utf8;

Step 3: Implementation activity.sql File (remember not to open the file and copy it to the MySQL client).

source d:/activity.sql

among activity.sql The contents of the document are as follows:

drop database if exists dbactivity;
create database dbactivity default character set utf8;
use dbactivity;
create table tb_activity(
     id bigint primary key auto_increment,
     title varchar(100) not null,
     category varchar(100) not null,
     startTime datetime not null,
     endTime datetime not null,
     remark text,
     state tinyint,
     createdTime datetime not null,
     createdUser varchar(100)
)engine=InnoDB;
insert into tb_activity values (null,'ABS','cuoxiao','2020-02-02 15:00:00','2020-02-03 15:00:00','...',1,now(),'xiaoli');
insert into tb_activity values (null,'VALIDATE','cuoxiao','2020-02-02 15:00:00','2020-02-03 15:00:00','...',1,now(),'xiaoli');
insert into tb_activity values (null,'VALIDATE','cuoxiao','2020-02-02 15:00:00','2020-02-03 15:00:00','...',1,now(),'xiaoli');
insert into tb_activity values (null,'ABS','cuoxiao','2020-02-02 15:00:00','2020-02-03 15:00:00','...',1,now(),'xiaoli');
insert into tb_activity values (null,'ACCESS','cuoxiao','2020-02-02 15:00:00','2020-02-03 15:00:00','...',1,now(),'xiaoli');

Create a project and add dependencies

Step 1: Based on start.spring.io Create a project and set up basic information.

Design and implementation of activity module in springboot project?

Step 2: specify the project core dependencies when creating the project.
Design and implementation of activity module in springboot project?

Step 3: analyze the structure of the project after it is created.

Design and implementation of activity module in springboot project?

Project profile content initialization

#server
server.port=80
#server.servlet.context-path=/
#spring datasource
spring.datasource.url=jdbc:mysql:///dbactivity?serverTimezone=GMT%2B8&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root

#spring mybatis
mybatis.mapper-locations=classpath:/mapper/*/*.xml

#spring logging
logging.level.com.cy=debug

#spring thymeleaf
spring.thymeleaf.prefix=classpath:/templates/modules/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false

Project API architecture design

The API architecture design is shown in the figure
Design and implementation of activity module in springboot project?

Implementation of activity module query service

Business description

Query all activity information from the database, and then render it on the page (based on JS mode), as shown in the figure:

Design and implementation of activity module in springboot project?

Business timing analysis

Enter the URL to query the activity information in the browser address bar to obtain the activity information, and the timing process is shown in the figure

Design and implementation of activity module in springboot project?

Design and implementation of POJO class

Create an activity class and encapsulate the activity information obtained from the database based on this object. The code is as follows:

package com.cy.pj.activity.pojo;
import java.util.Date;
import lombok.Data;
@Data
public class Activity {
    private Integer id;
    private String title;
    private String category;
    private Date startTime;
    private Date endTime;
    private String remark;
    private Integer state;
    private Date createdTime;
    private String createdUser;
}

among ,@Data The annotation is Lombok annotation. You need to install the Lombok plug-in in in the IDE environment. Add the Lombok dependency to the project. If not, you can also add the set / get related methods yourself

Dao interface method and mapping definition

Define the data layer interface and query method of the activity module. The code is as follows:

package com.cy.pj.activity.dao;
import com.cy.pj.activity.pojo.Activity;

@Mapper
public interface ActivityDao {
    
     @Select("select * from tb_activity order by createdTime desc")
     List<Activity> findActivitys();
}

Definition and implementation of service interface method

Define the service interface and the method to obtain activity information. The code is as follows:

package com.cy.pj.activity.service;
import java.util.List;
import com.cy.pj.activity.pojo.Activity;
//Introducing classes in packages: Ctrl + Shift + O

public interface ActivityService {
    List<Activity> findActivitys();
}

Define the service interface implementation class and rewrite the interface method. The code is as follows:

package com.cy.pj.activity.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cy.pj.activity.dao.ActivityDao;
import com.cy.pj.activity.pojo.Activity;
import com.cy.pj.activity.service.ActivityService;

@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityDao activityDao;
    @Override
    public List<Activity> findActivitys() {
         return  activityDao.findActivitys();
    }
}

Definition and implementation of controller method

package com.cy.pj.activity.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cy.pj.activity.pojo.Activity;
import com.cy.pj.activity.service.ActivityService;

@Controller
public class ActivityController {
     @Autowired
     private ActivityService activityService;
     
     @RequestMapping("/activity/doActivityUI")
     public String doActivityUI(){
          return "activity";
     }
     
     /**Query all activity information*/
     @RequestMapping("/activity/doFindActivitys")
     @ResponseBody
     public List<Activity> doFindActivitys() {
         List<Activity>  list=activityService.findActivitys();
         return list;
     }
}

Design and implementation of activity list page

This page style is based on bootstrap (a front-end framework bootcss.com )First, add static resources to the project project, as shown in the figure

Design and implementation of activity module in springboot project?
Design activity.html Page, introduce bootstrap, jQuery and other related resources, as shown in the figure:

Design and implementation of activity module in springboot project?

stay activity.html Add HTML elements to the page to render activity data:

<table class="table">
    <thead>
        <tr>
            <th>title</th>
            <th>Category</th>
            <th>StartTime</th>
            <th>EndTime</th>
            <th>State</th>
            <th>Operation</th>
        </tr>
    </thead>
    <tbody id="tbodyId">
        < tr > < TD colSpan = "6" > data is loading.... < / td > < / TR >
    </tbody>
</table>

Asynchronous loading and local refresh of server activity data based on AJAX

<script type="text/javascript">
      function doFindActivitys(){
          var url="/activity/doFindActivitys"
          //Start Ajax technology to get server-side JSON data based on get request
          //By default, the getjson function converts the JSON string returned by the server into a JS object
          $.getJSON(url,function(result){
              var tBody=$("#tbodyId");
              tBody.empty (); // clear the original body content
              for(var i=0;i< result.length ; I + +) {// loop once, iterate one line
                  //Build current line object
                  var tr=`<tr>
                          <td>${result[i].title}</td>
                          <td>${result[i].category}</td>
                          <td>${result[i].startTime}</td>
                          <td>${result[i].endTime}</td>
                          <td>${result [i]. State = = 1?'valid ':' invalid '}</td>
                          <td><button type='button' class='btn btn-danger btn-sm'>delete</button></td>
                         </tr>`
                  //Append the contents of each line to tbody
                  tBody.append(tr);
              }
          });
      };
      doFindActivitys();
    </script>

Start Tomcat server for access test analysis

Start the project, enter the access address of the activity page in the browser, and present the activity information, as shown in the figure:

Design and implementation of activity module in springboot project?

Client breakpoint debugging analysis, as shown in the figure:

Design and implementation of activity module in springboot project?

Run time breakpoint settings, as shown in the figure:

Design and implementation of activity module in springboot project?

Enter the breakpoint method, as shown in the figure:

Design and implementation of activity module in springboot project?

Check the presentation of response data on the client, as shown in the figure:

Design and implementation of activity module in springboot project?

Bug analysis in the process of startup and operation

  • The URL configuration of database link is wrong, as shown in the figure:

Design and implementation of activity module in springboot project?

  • Null pointer exception, as shown in the figure:

Design and implementation of activity module in springboot project?

  • JS import error, as shown in the figure:

Design and implementation of activity module in springboot project?

Design and implementation of activity module in springboot project?

Design and implementation of activity module in springboot project?

  • JS syntax error, as shown in the figure:

Design and implementation of activity module in springboot project?

Activity module add business implementation

Business description

On the activity list page, design the Add button. When you click the Add button, a modal box will pop up. In the modal box, the activity added form elements are displayed, and the form prototype design is added,
As shown in the figure:
Design and implementation of activity module in springboot project?

Business timing analysis

The time sequence analysis of activity adding business is shown in the figure

Design and implementation of activity module in springboot project?

Dao interface method and mapping definition

Add a method to persist activity information in activitydao interface. The code is as follows:

int insertObject(Activity activity);

Add a mapping element to the activitymapper mapping file. The code is as follows:

 <insert id="insertObject" parameterType="com.cy.pj.activity.pojo.Activity"
             useGeneratedKeys="true" keyProperty="id">
          insert into tb_activity
          (title,category,startTime,endTime,remark,state,createdUser,createdTime) 
          values    
          (#{title},#{category},#{startTime},#{endTime},
          #{remark},#{state},#{createdUser},now())
 </insert>

Data acquisition and analysis of “# {}” expression, as shown in the figure:

Design and implementation of activity module in springboot project?

Get the database primary key ID value when executing the insert operation, as shown in the figure:

Design and implementation of activity module in springboot project?

Of course, SQL mapping can also be done in the form of annotation, as shown in the figure

Design and implementation of activity module in springboot project?

After the activity is created, if the end time is reached, the status of the activity will be updated dynamically. The code is as follows:

@Update("update tb_activity set state=0 where id=#{id}")
int updateState(Long id);

Definition and implementation of service interface method

In the activityservice interface, add a method to save activity information. The code is as follows:

int saveActivity(Activity entity);

Add the implementation of the interface method to the activityserviceimpl implementation class. The code is as follows:

@Override
public int saveActivity(Activity entity) {
        int rows=activityDao.insertObject(entity);
        Timer timer=new Timer();
         //This object can be responsible for performing some tasks (this object has a built-in thread and a task queue)
         //Start thread to execute task scheduling
        timer.schedule (New timertask() {// TimerTask is the task
            @Override
            public void run() {
                //Once the thread calling the task gets the CPU, it executes the run method of the task
                activityDao.updateState(entity.getId());
                timer.cancel (); // quit task scheduling (subsequent threads will also be destroyed)
            }
        } entity.getEndTime ()); // execute the task at the specified time
        return rows;
}

Definition and implementation of controller method

Add the method in activitycontroller to process the add request. The code is as follows:

@RequestMapping("/activity/doSaveActivity")
@ResponseBody
public String doSaveActivity(Activity activity) {
 activityService.saveActivity(activity);
 return "save ok";
}

Design and implementation of activity page adding form

stay activity.html Add form elements to the page to interact with users. First, add an add button on the activity page. The code is as follows:

<button type="button" class="btn btn-primary btn-sm"
            Data toggle = "modal" data target "ා mymodal" > create an activity
</button>

Add a modal box in the specified position (refer to bootcss.com )The code is as follows:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
            aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal"
                                                aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                        < H4 class = "modal title" id = "mymodal label" > create activity < / H4 >
                    </div>
                    <div class="modal-body">    
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default"data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary" onclick="doSaveObject()">
                        Save Changes</button>
                    </div>
                </div>
            </div>
</div>

In the “modal body” position of the modal box, add the form form. The code is as follows:

<form class="form-horizontal" th:action="@{/activity/doSaveActivity}" method="post">
<div class="form-group">
    < label for = "titleid" class = "col-sm-2 control label" > Title < / label >
        <div class="col-sm-10">
         <input type="text" class="form-control"  name="title" id="titleId" placeholder="title">
        </div>
</div>
<div class="form-group">
< label for = "categoryid" class = "col-sm-2 control label" > type < / label >
    <div class="col-sm-10">
        <select id="categoryId" name="category" class="form-control">
            < option value = "education training" > Education and training < / option >
            < option value = "enterprise activity" > enterprise activity < / option >
            < option value "> dating activity < / option >
        </select>
    </div>
</div>
<div class="form-group" >
< label for = "starttimeid" class = "col-sm-2 control label" > start time
    <div class="col-sm-10">
       <input type="text" class="form-control form_datetime"
         name="startTime" id="startTimeId" placeholder="start time">
    </div>
</div>
<div class="form-group">
    < label for = "endtimeid" class = "col-sm-2 control label" > end time
    <div class="col-sm-10">
           <input type="text" class="form-control form_datetime" 
            name="endTime" id="endTimeId" placeholder="end time">
    </div>
</div>
<div class="form-group">
    < label for = "remarkid" class = "col-sm-2 control label" > remarks < / label >
        <div class="col-sm-10">
           <textarea type="text" class="form-control"  rows="5" name="remark" id="remarkId">
            </textarea>
    </div>
</div>
</form>

Add JS code to handle the mode box save button event. The code is as follows:

function doSaveObject(){
        //1. Define the URL
        let url="/activity/doSaveObject";
        //2. Define request parameters
        var params=
      $("# saveformid"). Serialize(); // serialize() is a method to get form data directly in jQuery
        console.log("params",params);
        //3. Send asynchronous request
        $.ajax({
            type:"post",
            url:url,
            data:params,
            success:function(result){
                alert(result);
                //Hide modal box
                $('#myModal').modal('hide');
                //Re execute the query and refresh it locally
                findActivitys();
            }
        });
        
    }

Start Tomcat server for access test analysis

Start Tomcat and access the activity list page, as shown in the figure:
Design and implementation of activity module in springboot project?

On the activity list page, click the Add button, and then start the activity add module box to perform the add operation, as shown in the figure:
Design and implementation of activity module in springboot project?

Spring MVC is used to assign and analyze the method parameters, as shown in the figure

Design and implementation of activity module in springboot project?

The calendar control is expanded and implemented (start time and end time are realized by selection), and the effect is shown as follows:
Design and implementation of activity module in springboot project?

The implementation process of bootstrap datapicker control is shown in the figure
Design and implementation of activity module in springboot project?

Bug analysis in the process of startup and operation

  • Bindingexception, as shown in the figure:

Design and implementation of activity module in springboot project?

  • 400 abnormal, as shown in the figure:

Design and implementation of activity module in springboot project?

  • Server date format design, as shown in the figure:

Design and implementation of activity module in springboot project?

  • Integrity constraint exception, as shown in the figure:

Design and implementation of activity module in springboot project?

Summary

This module explains the class design, mapping design, interaction design and implementation in the activity module, and then can strengthen the design and implementation of business and technology based on the practice of this module.

Recommended Today

PHP 12th week function learning record

sha1() effect sha1()Function to evaluate the value of a stringSHA-1Hash. usage sha1(string,raw) case <?php $str = “Hello”; echo sha1($str); ?> result f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0 sha1_file() effect sha1_file()Function calculation fileSHA-1Hash. usage sha1_file(file,raw) case <?php $filename = “test.txt”; $sha1file = sha1_file($filename); echo $sha1file; ?> result aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d similar_text() effect similar_text()Function to calculate the similarity between two strings. usage similar_text(string1,string2,percent) case […]