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

Hello.

Let's continue to implement exception handling until the last time!

TODO application creation link collection

1: [Understanding the super basics] A brief description of MVC 2: [Prepare a template] I want to create a template with Spring Initializr and do Hello world 3: [Connection / Settings / Data display with MySQL] Save temporary data in MySQL-> Get all-> Display on top 4: [POST function] Implementation of posting function 5: [PATCH function] Switch TODO display 6: [Easy to use JpaRepository] Implementation of search function [7: [Common with Thymeleaf template fragment] Create Header] (https://qiita.com/nomad_kartman/items/8c33eca2880c43a06e40) [8: [PUT function] Implementation of editing function] (https://qiita.com/nomad_kartman/items/66578f3f91a422f9207d) [9: [Tweak] Sort TODO display in chronological order + Set due date default to today's date] (https://qiita.com/nomad_kartman/items/5ee2b13a701cf3eaeb15) 10: [Exception handling with spring] A brief summary of exception handling [11: [Exception handling in spring] Exception handling when accessing TODO with non-existent ID] (https://qiita.com/nomad_kartman/items/a486838153a563767169) 12: [Exception handling in spring] Processing when a request comes in with an unused HttpMethod-Processing when an error occurs in the server

A brief description of HttpMethod

What is an HTTP method? I think there are many people who think that, so this time it's a rough sketch, but I'll explain what it is like.

A light understanding of what it means to visit a website

First of all, I would like you to understand

Access the Internet site = Access the server on the Internet

about it.

HP is displayed and various functions (such as TODO function) are placed in this server, and if accessed, it should work as expected by the creator.

By the way, the TODO app we are currently creating is not published on the web, but since we are creating a temporary server on our local, we can access localhost: 8080 when we run the app. It is.

URL and HttpMethod

Well, I found out that you can use HP by accessing the server.

What do I need to access?

First of all, you need the address of that site!

If the site is like a house, the address will be the address!

If you just use HP normally, you only need to know the address, but when you actually make HP as a web creator, you have to understand another concept HttpMethod.

Actually, when accessing the site, we use something called HttpMethod to request access.

By requesting the site URL + HttpMethod at the same time, the site is determining which page the user wants to visit!

For example, take the following example.

com/example/todo/TodoController.java


@Controller
public class TodoController {

    @GetMapping("/top")
    public String top(Model model){
        return "top";
    }

This is the part that displays the top page of the TODO application, but what I want to pay attention to is

This is the part of @GetMapping ("/ top").

This annotation is for the user

The site URL / top has the role of clearly stating what you want to do when you make a request with the GET method.

So if the user makes such a request, the function top will run.

If your site is home and your address is an address, HttpMethod may be like a key.

It's like the key needed to enter the room that displays the top page of the house.

You can access the same URL by changing the HttpMethod.

For example, take the example below

com/example/todo/TodoController.java


@Controller
public class TodoController {

    @GetMapping("/top")
    public String top(Model model){
        return "top";
    }

    @PostMapping("/top")
    public String top(Model model){
        //Post processing
    }

I added the process when / top is accessed by POST method.

The URL itself to access is the same, but different processing can be realized by changing the HTTP method at the time of request.

Various HttpMethod

Well, there are various types of HttpMethod, but let's summarize the typical ones and their roles.

GET
Used when retrieving resources in the site (Example: Display TODO (resource) obtained from DB on the top page)
POST
Used when posting something (example: when posting TODO)
PUT
Replace the contents of the data (eg upload a file and change the whole contents)
PATCH
Update, modify and save part or all of the data (example: when editing TODO)

Exception handling when requested by an unused HttpMethod

com/example/todo/exception/TodoControllerAdvice.java


    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public String badMethod() {
        log.warn("Bad Request");
        return "error/405.html";
    }

templates/error/405.html


<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>405</title>
</head>
<body>
405!
</body>
</html>

Let's add the above two.

You can see how to write Controller Advice by looking at the previous article.

Here, 405.html is displayed when HttpRequestMethodNotSupportedException (an exception class that occurs when a request for HttpMethod that does not exist is thrown) occurs.

Let's use the Curl command to throw an HttpMethod that doesn't actually exist!

Launch the Todo app and in the terminal

$ curl -X POST "http://localhost:8080/top"

Type. This is making an access request with POST to / top, which originally implements processing only with GET.

Then the result is Screen Shot 0002-10-25 at 17.01.14.png

It should look like this! You can see that 405 is displayed as expected.

Next, set it when an error occurs in the server.

com/example/todo/exception/TodoControllerAdvice.java


    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public String otherErrors() {
        log.error("Something went wrong");
        return "error/500.html";
    }

templates/error/500.html


<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>500</title>
</head>
<body>
500!
</body>
</html>

By adding these, you can now display a page with a 500 error when the ʻException class occurs!

Recommended Posts

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
Let's create a TODO application in Java 11 Exception handling when accessing TODO with a non-existent ID
Let's create a TODO application in Java 5 Switch the display of TODO
Let's make a calculator application with Java ~ Create a display area in the window
When using a list in Java, java.awt.List comes out and an error occurs
Let's create a TODO application in Java 4 Implementation of posting function
Collecting client information when an error occurs in a web application
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 2 I want to create a template with Spring Initializr and make a Hello world
An error occurs when codedeploy-agent is installed in Ubuntu Server 20.04
Create a simple web server with the Java standard library com.sun.net.httpserver
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
Create a TODO app in Java 7 Create Header
A reminder when an aapt.exe error occurs
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
An error occurred when executing a function from MyBatis with the OUT parameter set to CURSOR in PostgreSQL.
Send an email when an ERROR level log occurs with the logback SMTP Appender
Let's create a timed process with Java Timer! !!
The story when the container does not start up with docker-compose up and an error occurs
Customize the display when an error such as 404 Not Found occurs in Spring Boot
Quickly implement a singleton with an enum in Java
What I learned when building a server in Java
Deploy a Java application developed locally with the Cloud Toolkit to an Alibaba Cloud ECS instance
[Unresolved] An exception occurs when an SSH connection is executed using JSch from a Java 6 application.
(Fixed) An error occurs when using Java 8 with the latest version (0.65.0) of Language Support for Java (TM) by Red Hat of VS Code.
Java learning_Behavior when there is a method with the same name as a field with the same name in two classes that have an inheritance relationship
Implementing a large-scale GraphQL server in Java with Netflix DGS
Resolve CreateProcess error = 206 when running Java in a Windows environment
Create a SlackBot with AWS lambda & API Gateway in Java
Create a method to return the tax rate in Java
Show detailed error in Logger when running Java on server
About the behavior when doing a file map with java
Create a simple DRUD application with Java + SpringBoot + Gradle + thymeleaf (1)
A memo of the update command when npm install causes an error in GitHub Action etc.
[Java] How to search for a value in an array (or list) with the contains method