Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

preface

In the previous article, we wrote the POJO, DAO, and mapper for the DAO layer. From now on, we will write the Service layer and controller layer.

The service layer

Reservation service operation code

Before writing the Service layer, we first define a data field of the return code of the reservation book operation, which is used to feedback the customer information.

Return code instructions
1 Make an appointment success
0 Make an appointment to failure
– 1 Make an appointment to repeat
2 – A system exception
package com.cunyu.utils;

import com.cunyu.dto.AppointDto;
import lombok.AllArgsConstructor;
import lombok.Getter;

/ * * *@author : cunyu
 * @version : 1.0
 * @className : AppointStateEnum
 * @date: 2020/7/24 he *@description: Defines the data dictionary for reservation services */

@Getter
@AllArgsConstructor
public enum AppointStateEnum {

    SUCCESS(1."Reservation successful"), FAILURE(0."Reservation failed"), REPEAT(-1."Duplicate appointment"), SYSTEMERROR(-2."System exception");

    private int state;
    private String stateInfo;

    / * * *@paramStat Status code *@return
     * @descriptionObtain status code corresponding to enum *@date 2020/7/24 10:57
     * @author cunyu1943
     * @version1.0 * /
    public static AppointStateEnum stateOf(int stat) {
        for (AppointStateEnum state : values()
        ) {
            if (stat == state.getState()) {
                returnstate; }}return null; }}Copy the code

Data transfer layer

After defining the data dictionary of reservation business, create a new data transmission class to transmit our reservation results;

package com.cunyu.dto;

import com.cunyu.pojo.Appointment;
import com.cunyu.utils.AppointStateEnum;
import lombok.Data;
import lombok.NoArgsConstructor;

/ * * *@author : cunyu
 * @version : 1.0
 * @className : AppointDto
 * @date: 2020/7/24 they *@description: For data transmission, encapsulation */

@Data
@NoArgsConstructor
public class AppointDto {
    private int bookId;
    / / status code
    private int state;
    // Status information
    private String stateInfo;
    // Successfully scheduled object
    private Appointment appointment;

    // Failed to reserve the constructor
    public AppointDto(int bookId, AppointStateEnum appointStateEnum) {
        this.bookId = bookId;
        this.state = appointStateEnum.getState();
        this.stateInfo = appointStateEnum.getStateInfo();
    }

    // The constructor was successfully reserved
    public AppointDto(int bookId, AppointStateEnum appointStateEnum, Appointment appointment) {
        this.bookId = bookId;
        this.state = appointStateEnum.getState();
        this.stateInfo = appointStateEnum.getStateInfo();
        this.appointment = appointment; }}Copy the code

Service business code writing

BookService.java

package com.cunyu.service;

import com.cunyu.dto.AppointDto;
import com.cunyu.pojo.Book;

import java.util.List;

/ * * *@author : cunyu
 * @version : 1.0
 * @className : BookService
 * @date : 2020/7/24 10:44
 * @description: Book Service interface */


public interface BookService {

    / * * *@paramBookId bookId *@returnThe book with the corresponding ID *@descriptionQuery books by book ID *@date2020/7/24 so *@author cunyu1943
     * @version1.0 * /
    Book getById(int bookId);

    / * * *@param
     * @returnA list of all books *@descriptionGet book list *@date2020/7/24 so *@author cunyu1943
     * @version1.0 * /
    List<Book> getList(a);

    / * * *@paramBookId bookId *@paramStudentId studentId *@return
     * @descriptionReturns the reservation result *@date2020/7/24 "*@author cunyu1943
     * @version1.0 * /
    AppointDto appoint(int bookId, int studentId);
}
Copy the code

BookServiceImpl.java

package com.cunyu.service.impl;

import com.cunyu.dao.AppointmentDao;
import com.cunyu.dao.BookDao;
import com.cunyu.dto.AppointDto;
import com.cunyu.pojo.Appointment;
import com.cunyu.pojo.Book;
import com.cunyu.service.BookService;
import com.cunyu.utils.AppointStateEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/ * * *@author : cunyu
 * @version : 1.0
 * @className : BookServiceImpl
 * @date: 2020/7/24 "*@description: Book Business interface implementation class */

@Service
public class BookServiceImpl implements BookService {
    // dependency injection
    @Autowired
    private BookDao bookDao;

    @Autowired
    private AppointmentDao appointmentDao;

    public Book getById(int bookId) {
        return bookDao.queryById(bookId);
    }

    public List<Book> getList(a) {
        return bookDao.queryAll(0.3);
    }

    public AppointDto appoint(int bookId, int studentId) {
        AppointDto appointDto = null;
        try {
            / / inventory reduction
            int update = bookDao.reduceNumber(bookId);
            if (update <= 0) {
                System.out.println(AppointStateEnum.FAILURE);
            } else {
                // Perform the reservation operation
                int insert = appointmentDao.insertAppointment(bookId, studentId);
                if (insert <= 0) {
                    System.out.println(AppointStateEnum.REPEAT);
                } else {
                    Appointment appointment = appointmentDao.queryByKeyWithBook(bookId, studentId);
                    appointDto = newAppointDto(bookId, AppointStateEnum.SUCCESS, appointment); }}}catch (Exception e) {
            e.printStackTrace();
        }
        returnappointDto; }}Copy the code

test

package com.cunyu.service.impl;

import com.cunyu.service.BookService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/ * * *@author : cunyu
 * @version : 1.0
 * @className : BookServiceImplTest
 * @date : 2020/7/24 11:53
 * @description: BookServiceImpl Test class */

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring/spring-*.xml")
public class BookServiceImplTest {
    @Autowired
    private BookService bookService;

    @Test
    public void testAppoint(a) {
        int bookId = 1;
        int studentId = 18301343; System.out.println(bookService.appoint(bookId, studentId)); }}Copy the code

The following figure shows the data in the database after our test, indicating that our service layer interface test was successful at this time.

Encapsulates the result

Now that our Service layer interfaces and implementation classes are written, we need to encapsulate the results in JSON format so that we can pass them to the Controller for interactive use.

package com.cunyu.dto;

import lombok.Data;
import lombok.NoArgsConstructor;

/ * * *@author : cunyu
 * @version : 1.0
 * @className : ResultDto
 * @dateAnd the cloud: 2020/7/24 *@descriptionThe encapsulation result is JSON */

@Data
@NoArgsConstructor
public class ResultDto<T> {
    // Check whether the reservation is successful
    private boolean success;
    // The returned data is successfully scheduled
    private T data;
    // Error message
    private String error;

    // The constructor was successfully reserved
    public ResultDto(boolean success, T data) {
        this.success = success;
        this.data = data;
    }

    // Failed to reserve the constructor
    public ResultDto(boolean success, String error) {
        this.success = success;
        this.error = error; }}Copy the code

The controller layer

With the Service layer written, we are left with the final Controller layer;

package com.cunyu.controller;

import com.cunyu.dto.AppointDto;
import com.cunyu.dto.ResultDto;
import com.cunyu.pojo.Book;
import com.cunyu.service.BookService;
import com.cunyu.utils.AppointStateEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/ * * *@author : cunyu
 * @version : 1.0
 * @className : BookController
 * @date : 2020/7/24 12:20
 * @description: Book Controller layer */

@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;

    / / url: IP: port: / book/list
    @GetMapping("/list")
    private String list(Model model) {
        List<Book> bookList = bookService.getList();
        model.addAttribute("bookList", bookList);
        return "list";
    }

    @GetMapping(value = "/{bookId}/detail")
    private String detail(@PathVariable("bookId") Integer bookId, Model model) {
        if (bookId == null) {
            return "redirect:/book/list";
        }

        Book book = bookService.getById(bookId);
        if (book == null) {
            return "forward:/book/list";
        }

        model.addAttribute("book", book);
        return "detail";
    }

    // Ajax passes JSON data to the front end
    @RequestMapping(value = "/{bookId}/appoint", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ResponseBody
    private ResultDto<AppointDto> appoint(@PathVariable("bookId") Integer bookId, @RequestParam("studentId") Integer studentId) {
        if (studentId == null || studentId.equals("")) {
            return new ResultDto<>(false."Student number cannot be empty.");
        }
        AppointDto appointDto = null;
        try {
            appointDto = bookService.appoint(bookId, studentId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResultDto<AppointDto>(true, appointDto); }}Copy the code

The front end

Well, our background is developed, and then we can write the front end of the page. Then start Tomcat and access the corresponding URL.

list.jsp

<%--
  Created by IntelliJ IDEA.
  User: cunyu
  Date: 2020/7/23
  Time: 9:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html; charset=UTF-8" language="java"% > < HTML > < head > < title > book list page < / title > < / head > < body > < h1 > ${bookList} < / h1 > < / body > < / HTML >Copy the code

detail.jsp

<%--
  Created by IntelliJ IDEA.
  User: cunyu
  Date: 2020/7/23
  Time: 10:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html; charset=UTF-8" language="java"% > < HTML > < head > < title > book details page < / title > < / head > < body > < h1 > ${book. The name} < / h1 > < h2 > ${book. BookId} < / h2 > <h2>${book.number}</h2> </body> </html>Copy the code

conclusion

At this point, all of our background services have been written, SSM framework integration configuration, and the application instance part has ended, the front-end part is simply written a data display page.

Interested partners can then go to achieve before oh ~