Spring Boot starting from zero Part 1

Target

It will be implemented in multiple times.

  1. Roughly know what Spring Boot is ← I will do it this time </ font>
  2. Build environment & display Hello World! ← I will do this time </ font>
  3. Pass parameters and objects
  4. Try out other features

References

What is Spring Boot?

It makes it easier to write spring, which is a kind of Java framework. By using annotations (description method with @ like @Override), it is not necessary to describe complicated XML configuration file, and it is very easy to attach.

Environment

We use a development environment called STS (Spring Tool Suite4). Based on Eclipse, which is famous as a Java development environment, it has functions to make development in Spring more convenient.

    1. Download and execute STS at the following site. (Unzip in case of zip)

STS (Spring Tool Suite) SpringBoot_2.png It is OK if a folder named sts-4.X.X.RELEASE is created.

  1. Download the STS Japanese patch from the following site. (Because the default is English) ・ Pleiades Japanese localization plug-in
  • It is not "Pleia des All in One Download" at the top of the page, but one below it. SpringBoot_4.png
    1. Execute the setup file in the downloaded pleiades-win. SpringBoot_5.png The following screen will start. Specify SpringToolSuite4.exe in the sts-4.X.X.RELEASE folder in "Application to Japaneseize" and click "Japaneseize". Start STS and if it is in Japanese, you're done!

Project creation

After starting STS, select [File]-[New]-[Spring Starter Project]. Click [Next] without any operation on this screen.

  • Maven or Gradle can be selected in [Type], but Maven will be used on this page. In [New Spring Starter Project Dependencies] -[Development Tools]-[Spring Boot DevTools] -[Template engine]-[Thymeleaf] ・ [Web]-[Spring Web] Check the three items and click [Next]. Dependencies will be explained later. </ font> Click [Finish] without any operation on this screen. Once you have a project like the one below, you're done!

About dependencies

I checked Spring Boot DevTools, Thymeleaf, and Spring Web earlier, and the following code is automatically written in pom.xml.

pom.xml


<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-devtools</artifactId>
	<scope>runtime</scope>
	<optional>true</optional>
</dependency>
name Explanation
Thymeleaf Java template engine for web pages. Spring recommends Thymeleaf instead of jsp. Write like jstl or EL expression.
Spring Web A library required for Spring Boot web applications.
Spring Boot DevTools If you update the java file, you will be able to use convenient functions such as automatically restarting the application.

Therefore, when using the Spirng Boot function, you need to either check the dependencies when creating a project or manually describe them in pom.xml.

Roughly, but also supplement pom.xml.

name Explanation
Maven Java project management tool. pom.Make it easy to build and deploy your application by referring to xml.
pom.xml pom is an abbreviation for Project Object Model. Describe the library group and version information required for the project.

Hello World! (RestController)

When you create a project, one java file will be automatically generated under src / main / java / com / example / demo. This class is recognized as a SpringBoot application startup class by the @SpringBootApplication annotation. There is no need to add code manually.

RestController class creation

Now create a class in the same folder. Right-click on the com.example.demo icon and select [New]-[Class]. Enter DemoRestController in [Name] and click [Finish]. Add the following code to the created class. (For those who have never operated Eclipse ... Ctrl + S can save the file, Ctrl + Shift + O can automatically import it!)

DemoRestController.java


package com.example.demo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoRestController {

	@RequestMapping(value="/rest",method=RequestMethod.GET)
	public String hello() {
		return "Hello World!";
	}
}

@RestController Described in the class. It is a controller class for outputting the return value of the method to the page as it is without transitioning to View (HTML file etc.).

What is a controller? (Folded to derail a little) Spring and Spring Boot have the concept of `MVC model`, which is
`Model` ・ ・ ・ Responsible for processing logic such as search and calculation. `View` ・ ・ ・ Display the processing result of Model on the client side. `Controller` ・ ・ ・ Pass the information received from View to Model. (And vice versa)
It comes from the acronym of the program that has the role of.
`@RequestMapping` Described in the method. This is a function for mapping requests and methods from clients. Arguments are specified, but the following two are typical. `value =" / URL "` ・ ・ ・ Receives a request from the specified URL. `method = RequestMethod.GET (or POST)` ・ ・ ・ Receives a request from the specified transmission method.

by this, Access http: // localhost: 8080 / rest ↓ The URL will be / rest and the sending method will be GET (when you enter the URL and display the page, it will automatically be the GET method. Why? [This question in teratail](https: //) teratail.com/questions/103203) is easy to understand.) ↓ The hello method that matches this information is called ↓ The return value " Hello World! " Is output to the page. The flow is completed.


In addition, @RequestMapping has annotations with transmission methods as shown below. I will use this from the next time because it can be written concisely. @GetMapping("/URL") Same as @RequestMapping (value =" / URL ", method = RequestMethod.GET). @PostMapping("/URL") Same as @RequestMapping (value =" / URL ", method = RequestMethod.POST).


Now let's run the Spring application. First, click [Window]-[View View]-[Console] to display the console. Right-click on the project and click Run-Spring Boot Application. After confirming that Spring Boot has started on the console, ... Go to http: // localhost: 8080 / rest in your browser. Hello World! Is displayed!

Hello World! (Controller)

In the RestController edition, Hello World was displayed by the return value of the method, so let's display it as an HTML file this time.

HTML file creation

Right-click on src / main / resources / templates and select New-Other. Select [web]-[HTML file] and click [Next].

  • If you enter html in [Wizard], it will appear immediately as shown in the image below. Enter ʻindexin [File name] and click [Next]. <img src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/624514/75ee1fce-2703-87dd-bd77-2deef1cea052.png " width="75%"> Select [Template]-[New HTML File (5)](I think it is selected by default) and click [Finish]. <img src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/624514/b5f3ab69-626a-2506-9d3b-bba9d896457c.png " width="75%"> AddHello World!to the` part.

index.html


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Hello World!
</body>
</html>

Controller class creation

Next, create a DemoController class on src / main / java / com / example / demo and add the following code. (The creation method is the same as [Create RestController class](Create #RestController class))

DemoController.java


package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class DemoController {
	
	@RequestMapping(value="/",method=RequestMethod.GET)
	public ModelAndView hello() {
		ModelAndView mav=new ModelAndView();
		mav.setViewName("/index");
		return mav;
	}
}

@Controller Described in the class. Unlike @ RestController, it is a controller class that can transition to View. If you want to define a method that displays the return value on the page without transitioning to View in the class that specifies this, you can write @ResponseBody in the method as shown below.

@Response Body description example


@RequestMapping(value="/body",method=RequestMethod.GET)
@ResponseBody
public String body() {
	return "Hello World?";
}

ModelAndView This class has both Model (object management) and View (web page information) functions. There are these single classes, but the one we basically use is ModelAndView. The main methods are as follows.

Method How to use
setViewName("/File Path") Specify the path of the HTML file to be displayed. The path to the templates folder does not need to be described.
addObject("Parameter name",Parameters) Webページに渡すParametersを[name,value]Store as a set of. (I will use it next time

Now let's access http: // localhost: 8080. Hello World! Is displayed! Since it's HTML, "Insert title here (default title)" is displayed in the title of the page.

review

--SpringBoot makes Spring easier to use --Easy development with Spring Tool Suite --Linking URL and method with @RequestMapping --Display the return value of the method on the page with @ RestController --Display HTML file on page with @Controller

That's all for this time. Thank you for your hard work. From the next time, we will start passing parameters!

Recommended Posts