It will be implemented in multiple times.
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
.
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>
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 usernameDescription example
@RequestParam String username //OK
@RequestParam String name //NG
@RequestParam("username")
String usernameDescription example
@RequestParam("username") String username //OK
@RequestParam("username") String name //OK
@RequestParam("name") String username //NG
@RequestParam(value="username",required=false)
String usernamevalue
and the existence of the parameter with required
. The default is true. 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">
th
. th: text =" $ {parameter name} "
** ModelAndView
and displays them in the content. It is used for <div>
, <td>
, <p>
tags, etc.
-** th: value =" $ {parameter name} "
** 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.
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
!
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.
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
}
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!
--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