Let's create a TODO application in Java 4 Implementation of posting function

Hello. This time I would like to do the posting function part of the TODO application in Java.

By the way, I didn't touch on validation this time, but I will introduce the method only for normal processing because it will appear in a later article.

TODO application creation link collection

1: Brief description of MVC 2: I want to make a template with Spring Initializr and make a Hello world 3: Save temporary data in MySQL-> Get all-> Display on top 4: Implementation of posting function (here and now)

Create a TodoForm class

First of all, I would like to prepare a container for data when the user registers TODO. This time I would like to implement it in the TodoForm class.

I think that the hierarchy for creating classes should be the same as TodoContoroller.

java/com/example/todo/TodoForm.java


@Data
public class TodoForm {
    private long Id;

    @NotNull
    @Size(min = 1, max =30)
    private String title;

    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate deadline;

    private boolean status;
}

↑ It should be like this.

If you cannot use annotations ...

It seems that the specifications have changed from Spring 2.3, so you need to add it manually in order to use validation annotations.

build.gradle



dependencies {
  	compile group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'
}

If you add the above to dependencies, you can use @Size and so on!

Add logic to save TODO to TodoService

Next is the editing of Service.

java/com/example/todo/TodoService.java


@Service
@RequiredArgsConstructor
public class TodoService {
    private final TodoRepository todoRepository;

    //~ Abbreviation ~
    public void setTodo(TodoForm formData) {
        TodoEntity todo = new TodoEntity();
        todo.setTitle(formData.getTitle());
        todo.setDeadline(formData.getDeadline());
        todoRepository.save(todo);
    }
}

Since we only register this time, the return value is void.

Set the TodoForm type formData passed as an argument to the newly created TodoEntity and save it. Since set ~~ and get ~~ are attached with @Data in each class, LomBok can automatically create and use setters and getters.

It may be difficult to understand this area suddenly when using Lombok, so if you want to understand more deeply, you should investigate the concept of getter setter.

Finally, save it with the function save of the Repository class and save it in the DB!

Call a Service class function from TodoContoroller

Now that the Service class has been implemented, let's call it from the controller!

python


@Controller
@RequiredArgsConstructor
public class TodoController {

    // ~Abbreviation~
    @PostMapping("/register")
    public String register(@ModelAttribute TodoForm formData) {
        todoService.setTodo(formData);
        return "redirect:/top";
    }
}

What I would like to pay attention to here is the @ModelAttribute annotation!

This annotation has different uses depending on whether it is used as an argument or immediately before a method!

The usage this time is to make the data sent from the front side into TodoForm type so that it can be used in the function.

Please refer to the here site for easy-to-understand explanations.

Register TODO in DB by sending formData to setTodo created earlier.

Also, when the processing is finished, it will transition to / top.

Editing the TOP page

Finally, let's edit the front side!

python


~Abbreviation
<body>
    <!--Post form-->
    <div class=" w-75 h-auto my-1 mx-auto pt-5">
        <p class="pl-5">Create a new task</p>
        <form th:action="@{/register}" th:object="${ToDoForm}" method="POST" class="container d-flex w-auto my-0 mx-auto">
            <div class="w-100">
                <label class="row">
                    <span class="col-2 text-center">ToDo name</span>
                    <input type="text" name="title" placeholder="Enter ToDo within 30 characters" class="col-9">
                </label>
                <label class="row my-0">
                    <span class="col-2 text-center">Deadline</span>
                    <input type="date" id="date" name="deadline" class="col-9 my-0">
                </label>
            </div>
            <button class="btn btn-primary w-25 col-2 mr-3" type="submit">Add ToDo</button>
        </form>
    </div>
</body>

I am trying to skip the registration contents to the function of the controller mapped to / register with th: action.

Also, since method = "POST", detailed specifications such as POST and / register functions are specified.

This idea is very important for understanding the nature of HTTP methods, so you may want to refer to the here site.

th: object is used to specify a container for the transmitted data.

The submitted data is inserted into the TodoForm object created at the very beginning of this article.

When the registration button is pressed

 <input type="text" name="title" placeholder="Enter ToDo within 30 characters" class="col-9">

The content entered in name = "title" is stored in the variable with the same name (of course, title) of the FormData class.

A brief summary

How was it? To summarize briefly ...

  1. The front desk sends the necessary data to TODO
  2. The destination is specified by th: action ~~ and mesod = ~~. The transmitted data is stored in a specific object (named FormData this time)
  3. The object is sent from the controller to the service class that describes the business logic.
  4. Create an Enitty (data container) for TODO registration in the service class and fill it with the contents of the object that came from the controller.
  5. Save it with a Repository function.

It is like this!

I think you could gradually understand the flow of MVC.

Next time, I would like to touch on the edit page. See you again!

Recommended Posts

Let's create a TODO application in Java 4 Implementation of posting function
Let's create a TODO application in Java 6 Implementation of search function
Let's create a TODO application in Java 8 Implementation of editing function
Let's create a TODO application in Java 1 Brief explanation of MVC
Let's create a TODO application in Java 5 Switch the display of TODO
Implementation of like function in Java
Let's create a TODO application in Java 11 Exception handling when accessing TODO with a non-existent ID
Create a TODO app in Java 7 Create Header
Let's create a super-simple web framework in Java
[Rails] Implementation of retweet function in SNS application
Let's create a TODO application in Java 13 TODO form validation 1: Character limit ・ Gradle update to use @Validated
Let's create a TODO application in Java 3 Save temporary data in MySQL-> Get all-> Display on top
Let's make a calculator application with Java ~ Create a display area in the window
Implementation of gzip in java
Implementation of tri-tree in Java
Let's create a TODO application in Java 9 Create TODO display Sort by date and time + Set due date default to today's date
Let's create a TODO application in Java 2 I want to create a template with Spring Initializr and make a Hello world
Let's make a calculator application in Java ~ Display the application window
Let's create a TODO application in Java 12 Processing when a request comes in with an unused HttpMethod ・ Processing when an error occurs in the server
[Implementation procedure] Create a user authentication function using sorcery in Rails
Implementation of DBlayer in Java (RDB, MySQL)
Let's create a Java development environment (updating)
Role of JSP in Web application [Java]
Volume of trying to create a Java Web application on Windows Server 2016
Create authentication function in Rails application using devise
Create a CSR with extended information in Java
Do you need a memory-aware implementation of Java?
Let's create a timed process with Java Timer! !!
Measure the size of a folder in Java
Try to create a bulletin board in Java
Let's create a custom tab view in SwiftUI 2.0
[Java] Let's create a mod for Minecraft 1.14.4 [Introduction]
[JQuery] Implementation procedure of AutoComplete function [Java / Spring]
[Java] Let's create a mod for Minecraft 1.16.1 [Introduction]
A quick review of Java learned in class
[Java] Let's create a mod for Minecraft 1.14.4 [99. Mod output]
Create a native extension of Ruby in Rust
Let's create a versatile file storage (?) Operation library by abstracting file storage / acquisition in Java
[Java] Let's create a mod for Minecraft 1.14.4 [0. Basic file]
Interpreter implementation in Java
[Java] Let's create a mod for Minecraft 1.14.4 [4. Add tools]
How to create a Java environment in just 3 seconds
A quick review of Java learned in class part4
[Java] Create a filter
[Java] Let's create a mod for Minecraft 1.14.4 [5. Add armor]
Let's write a Qiita article in org-mode of Emacs !!
[Java] Let's create a mod for Minecraft 1.14.4 [Extra edition]
[Java] Let's create a mod for Minecraft 1.14.4 [7. Add progress]
[Java] Let's create a mod for Minecraft 1.14.4 [6. Add recipe]
[Java] Let's create a mod for Minecraft 1.16.1 [Add item]
Implementation of search function
[Java] Let's create a mod for Minecraft 1.16.1 [Basic file]
I tried to create a Clova skill in Java
[Java] Let's create a mod for Minecraft 1.14.4 [1. Add items]
How to create a data URI (base64) in Java
Boyer-Moore implementation in Java
Let's make a robot! "A simple demo of Java AWT Robot"
I tried to make a login function in Java
Heapsort implementation (in java)
A quick review of Java learned in class part3
Implementation of pagination function