Spring Boot starting from zero Part 2

Target

It will be implemented in multiple times.

  1. Get a rough idea of what Spring Boot is
  2. Display environment construction & Hello World!
  3. ** Pass parameters and objects ** ← What to do this time </ font>
  4. Try out other features

Preface

Last time I did the following two things to display Hello World.

--Display string with @RestController --Display index.html with @Controller

The project will continue to use the one created last time. Specifically, we will do the following. There are two main ways to achieve this. Let's start with @RequestParam.

Let's pass parameters (RequestParam edition)

Rewrite the <body> part of index.html as follows.

index.html


<body>
<form action="/hello" method="get">
name:
<input type="text" name="username">
<input type="submit" value="Send">
</form>
</body>
Click here for a description of various tags.
tag Element name Contents
form action Specify the URL to send the request.
method Select and specify the transmission method from GET and POST.
input type="text" Text field.
name The name given to the parameter. Used when getting on the java side.
type="submit" Button for submitting parameters.
value Specify the character string to be displayed in the content (text field, button, etc.).

Next, add the following code to DemoController.java.

DemoController.java


package com.example.demo;

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

@Controller
public class DemoController {
	
	//It is the same as the hello method created last time. (Change to index because the method name is covered)
	@RequestMapping(value="/",method=RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView mav=new ModelAndView();
		mav.setViewName("/index");
		return mav;
	}
	
	//This is the method to add this time.
	@GetMapping("/hello")
	public ModelAndView hello(@RequestParam String username,ModelAndView mav) {
		mav.addObject("username",username);
		mav.setViewName("/hello");
		return mav;
	}
}

For the function of ModelAndView, go to the previous article!

@RequestParam Described at the beginning of the argument. By adding this, the value of the request parameter is automatically stored in the variable. In addition, there are various ways to write, so I will introduce them all together. As an example, the name of the parameter sent is " username ".

  • @RequestParam String username
    This is the writing style used this time. The variable name (in red) and the name of the parameter you want to receive must be the same. An error will occur if the same parameter as the variable name does not exist.

Description example


@RequestParam String username //OK
@RequestParam String name //NG
  • @RequestParam("username") String username
    This is the safest way to write. On the annotation side, specify the name of the parameter you want to receive. If you specify a name that does not exist, an error will occur. At this time, the variable name can be any name.

Description example


@RequestParam("username") String username //OK
@RequestParam("username") String name //OK
@RequestParam("name") String username //NG
  • @RequestParam(value="username",required=false) String username
    It doesn't come out much. You can choose whether to require the name of the parameter with value and the existence of the parameter with required. The default is true.
    If set to false, no error will occur even if the specified parameter does not exist (although parameters cannot be passed, of course ...). Again, the variable name can be any name.

Description example


@RequestParam(value="username",required=false) String username //OK
@RequestParam(value="name",required=false) String name //OK but cannot be delivered
@RequestParam(value="name",required=true) String name //NG

Then create an HTML file that receives the parameters. Create an HTML file with the name hello.html in the same folder as index.html, and rewrite the contents as follows.

hello.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<span th:text="${username}"></span>, Hello World!
</body>
</html>
  • <html xmlns:th="http://www.thymeleaf.org">
    This description allows you to call Thymeleaf functions with tag names starting with th.
    What is Thymeleaf? For [previous article](https://qiita.com/hatopo/items/ecc16fdc757fc8cc8d55#%E4%BE%9D%E5%AD%98%E9%96%A2%E4%BF%82%E3%81 % AB% E3% 81% A4% E3% 81% 84% E3% 81% A6) and Official Documentation!
    -** th: text =" $ {parameter name} " **
    Gets the parameters stored in ModelAndView and displays them in the content. It is used for <div>, <td>, <p> tags, etc. -** th: value =" $ {parameter name} " **
    Same as th: text. This is used for <input type =" text "> etc.

Other tags will be explained each time they appear.


Now let's access http: // localhost: 8080. Enter an appropriate name and click the "Send" button. The name you entered can be displayed on the next page! The above is the passing of parameters by @RequestParam. The image is as follows. flow_param.png

Let's pass parameters (PathVariable edition)

Next is the parameter passing method that is possible only with the GET method. With this method, you can get the string contained in the URL as it is. (For example, when you access http: // localhost: 8080 / hello / xxx, you can get xxx as a parameter)

Rewrite the hello method of DemoController.java.

DemoController.java


@GetMapping("/hello/{username}")
public ModelAndView hello(@PathVariable String username,ModelAndView mav) {
	mav.addObject("username",username);
	mav.setViewName("/hello");
	return mav;
}

@GetMapping I did this last time, but the problem is the arguments. Enclose the part you want to get from the URL in {}, and put the name for calling with @PathVariable described later.

@PathVariable Described at the beginning of the argument. There are multiple ways to write this, but it is the same as @RequestParam, so I will omit it.

In addition, multiple parameters can be acquired. For example, if you want to get hatopo and 24 when you access http: // localhost: 8080 / hello / hatopo / 24, write as follows.

Description example


@GetMapping("/hello/{username}/{age}")
public ModelAndView hello(@PathVariable String username,@PathVariable int age,ModelAndView mav) {
	//The contents are omitted
	return mav;
}

Now let's access http: // localhost: 8080 / hello / xxx. (Enter any character string for xxx) I was able to display the parameters after / hello!

For those who don't feel like passing parameters ...
Although it is completely sloppy, parameters can be passed by writing javascript that attaches the value of the text field to the URL and makes the page transition. Rewrite the inside of `` of `index.html` as follows.

index.html


<body>
name:<input type="text" id="name">
<input type="submit" value="Send" onclick="send()">
<script>
function send(){
	var name = document.getElementById("name").value;
	if(name == "")name = "default_name";
	location.href = "http://localhost:8080/hello/" + name;
}
</script>
</body>

You can display the input value by accessing http: // localhost: 8080 /, entering the name and pressing the "Send" button!

The above is the passing of parameters. Let's continue to hand over the objects.

Passing objects

For those who don't know about objects, it's okay to understand it as a box (class) with parameters for now.

First, create a class with the name User in the same folder as DemoController and add the following code.

User.java


package com.example.demo;

public class User {
	private String name;
	private int age;
}

Next, add the methods called getter and setter that java needs to get / set parameters. You can write it manually, but if you want to add it automatically, place the cursor in an appropriate place in the User class and click source >> getter and setter generation. Click Select All >> Generate. It's OK if the whole code looks like this:

User.java


package com.example.demo;

public class User {
	private String name;
	private int age;
	//↓ Code added by automatic generation
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	//↑ Code added by automatic generation
}
  • If you use a plugin called Lombok, you do not need to write this code, but this article does not cover it.

Next, rewrite index.html as follows.

index.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/hello" method="get" th:object="${user}">
name:<input type="text" name="name"><br>
age:<input type="text" name="age"><br>
<input type="submit" value="Send">
</form>
</body>
</html>

-** th: object =" $ {object name} " **
The parameters in the tag that describes this can be collectively referred to by one object name. In this example, we put name and age in a box named user.


Let's also rewrite the hello method of DemoController.java.

DemoController.java


@GetMapping("/hello")
public ModelAndView hello(@ModelAttribute User user,ModelAndView mav) {
	mav.addObject("user",user);
	mav.setViewName("/hello");
	return mav;
}

@ModelAttribute Described at the beginning of the argument. Store the object sent from the form in a variable. At this time, Spring will do the following behind the scenes.

Internal processing


User user = new User();
user.setName(name);
user.setAge(age);

Therefore, it will not work properly if the field variable name is not defined in the User class or the setAge method is not defined.

You can also write this annotation in a method, but it's used quite differently, so I'll omit it in this article ...


Finally, let's rewrite hello.html as follows.

hello.html


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div th:object="${user}">
<span th:text="*{name}"></span>Is
<span th:text="*{age}"></span>I'm old!
</div>
</body>
</html>

-** th: text =" * {parameter name} " **
Abbreviation for th: text =" $ {object name.parameter name} ".
In the tag that describes th: object = {}, it can be abbreviated as above.


Now let's access http: // localhost: 8080. Enter your name and age and press the "Send" button ...

I was able to display my name and age!

review

--Passing parameters with @RequestParam --Get URL parameters with @PathVariable --Passing objects with @ModelAttribute

That's all for this time. Thank you for your hard work. From the next time, I will touch on more serious functions.

Recommended Posts