プロジェクト作成
https://start.spring.io/ で Gradle Project を生成します。
- Project: Gradle Project
- Language: Java
- Spring Boot: 2.6.1
- Project Metadata
- Group: com.example
- Artifact: demo
- Name: demo
- Description: Demo project for Spring Boot
- Package name: com.example.demo
- Packaging: War
- Java: 11
- Dependencies:
- Spring Web
- Thymeleaf
- Lombok
構成
- controller ディレクトリを作成します。
- Controller クラスをここに作成します。
- form ディレクトリを作成します。
- Form クラスをここに作成します。
.
├── HELP.md
├── build
├── build.gradle
├── gradle
│ └── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
├── main
│ ├── java
│ │ └── com
│ │ └── example
│ │ └── demo
│ │ ├── DemoApplication.java
│ │ ├── ServletInitializer.java
│ │ ├── controller
│ │ │ └── IndexController.java
│ │ └── form
│ │ └── SampleForm.java
│ └── resources
│ ├── application.properties
│ ├── static
│ └── templates
└── test
└── java
└── com
└── example
└── demo
└── DemoApplicationTests.java
build.gradle
Gradle のビルド設定ファイル
plugins {
id 'org.springframework.boot' version '2.5.6'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id 'war'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
ソースコード
IndexController
- / でリクエストを受け付けます。
- リクエストを SampleForm で受け取リます。
- SampleForm#userIds に格納された userId を取り出しコンソールに表示します。
package com.example.demo.controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import com.example.demo.form.SampleForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RestController
public class IndexController {
@CrossOrigin
@PostMapping("/")
public String index(@Validated SampleForm sampleForm) {
for(String userId : sampleForm.getUserIds()){
System.out.println(userId);
}
return "success";
}
}
SampleForm
- String の配列をフィールドとして持たせます。
package com.example.demo.form;
import lombok.Data;
@Data
public class SampleForm {
private String[] userIds;
}
Spring Boot 起動
> gradle bootrun
> Task :bootRun
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.1)
2021-12-03 09:10:28.925 INFO 13648 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication using Java 11.0.11 on user-win with PID 13648 (D:\tmp\stringlistsample\build\classes\java\main started by user in D:\project\nexs\enurse\wiki\research\springmvc\src\stringlistsample)
2021-12-03 09:10:28.925 INFO 13648 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2021-12-03 09:10:29.798 INFO 13648 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-12-03 09:10:29.806 INFO 13648 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-12-03 09:10:29.806 INFO 13648 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.55]
2021-12-03 09:10:29.843 INFO 13648 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-12-03 09:10:29.843 INFO 13648 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 875 ms
2021-12-03 09:10:30.041 INFO 13648 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-12-03 09:10:30.058 INFO 13648 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 1.393 seconds (JVM running for 1.677)
2021-12-03 09:10:31.998 INFO 13648 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-12-03 09:10:31.999 INFO 13648 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-12-03 09:10:31.999 INFO 13648 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 0 ms
<==========---> 80% EXECUTING [2m 15s]
> :bootRun
ajax で String 配列を渡す
index.html
- Spring MVC 側で SampleForm#userIds を String[] で定義しているので { ‘userIds’: [ ‘a’, ‘b’, ‘c’ ] } のように ajax で送ります。
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$.ajax({
url: 'http://localhost:8080',
type: 'POST',
data: {
'userIds': [
'6743DAC2-CBF8-4652-A355-70A843215FEC',
'07B58F19-1876-4A09-9048-B361E8BFC47C',
'70DF334F-B058-4954-A509-F11A35B07174',
'9E814088-9994-4875-A668-3B418AF9BF1A',
'FD6A40B3-746A-4851-8675-525D78077DC7',
'A301EA10-E4D2-49B0-9163-D0E789C1A072',
'0F25AA62-3144-4965-9A59-94226EC59213',
'8F7A41D0-2FA0-457A-90A9-297A03AB6775',
'3D7A242B-0E8A-4539-AEFE-9081955C27E2',
'2163362D-FD4E-4CCB-865E-68B7B0E62464'
]
}
}).done(function(data){
$('#target').text(data);
});
</script>
</head>
<body>
<span id="target"></span>
</body>
</html>
動作確認
index.html を Web ブラウザで表示します。と画面に success と表示されます。
Spring MVC を起動しているコンソールには userId が表示されます。
6743DAC2-CBF8-4652-A355-70A843215FEC
07B58F19-1876-4A09-9048-B361E8BFC47C
70DF334F-B058-4954-A509-F11A35B07174
9E814088-9994-4875-A668-3B418AF9BF1A
FD6A40B3-746A-4851-8675-525D78077DC7
A301EA10-E4D2-49B0-9163-D0E789C1A072
0F25AA62-3144-4965-9A59-94226EC59213
8F7A41D0-2FA0-457A-90A9-297A03AB6775
3D7A242B-0E8A-4539-AEFE-9081955C27E2
2163362D-FD4E-4CCB-865E-68B7B0E62464