Spring MVC에서 만든 API에 스트링 정렬 전달

14023 단어 spring-mvc
프로젝트 작성
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 클래스 만들기
  • 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
    
    aax를 통한 전송 스트링 정렬
    index.html
  • Spring MVC 측에서 String[]에서 SampleForm#userIds를 정의했기 때문에'a','b','c'}처럼 aax로 발송
  • <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이 표시되면 화면이 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
    

    좋은 웹페이지 즐겨찾기