inflearn logo
강의

講義

知識共有

Spring MVC 1編 - バックエンドWeb開発の中核技術

HTTPリクエストパラメータ - @ModelAttribute

임포트가 되지않아요

274

작성자 없음

投稿した質問数 0

0

학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요.

1. 강의 내용과 관련된 질문을 남겨주세요.
2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요.
(자주 하는 질문 링크: https://bit.ly/3fX6ygx)
3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요.
(질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG)

질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요.
=========================================
[질문 템플릿]
1. 강의 내용과 관련된 질문인가요? (예/아니오)
2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오)
3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오)

[질문 내용]
HelloData 생성했는데도 import가 되지 않습니다.

package hello.springmvc.basic.request;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.Map;

@Slf4j
@Controller
public class RequestParamController {

    @RequestMapping("/request-param-v1")
    public void requestParamV1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        int age = Integer.parseInt(request.getParameter("age"));
        log.info("username={}, age={}", username, age);

        response.getWriter().write("ok");
    }

    /**
     * @RequestParam 사용
     * - 파라미터 이름으로 바인딩
     * @ResponseBody 추가 (RestController 와 같은 역할을 수행함)
     * - View 조회를 무시하고, HTTP message body에 직접 해당 내용 입력
     */
    @ResponseBody
    @RequestMapping("/request-param-v2")
    public String requestParamV2(
            @RequestParam("username") String memberName,
            @RequestParam("age") int memberAge) {
        log.info("username={}, age={}", memberName, memberAge);
        return "ok";
    }

    @ResponseBody
    @RequestMapping("/request-param-v3")
    public String requestParamV3(
            @RequestParam String username,
            @RequestParam int age) {
        log.info("username={}, age={}", username, age);
        return "ok";
    }

    /**
     * @RequestParam 사용
     * String, int 등의 단순 타입이면 @RequestParam 도 생략 가능
     */
    @ResponseBody
    @RequestMapping("/request-param-v4")
    public String requestParamV4(String username, int age) {
        log.info("username={}, age={}", username, age);
        return "ok";
    }

    /**
     *  Integer 은 객체이기 때문에 null 이 들어갈 수 있음
     *  int 는 기본형이 때문에 null이 들어올 수 없음
     */
    @ResponseBody
    @RequestMapping("/request-param-required")
    public String requestParamRequired(
            @RequestParam(required = true) String username,
            @RequestParam(required = false) Integer age) {
        log.info("username={}, age={}", username, age);
        return "ok";
    }

    @ResponseBody
    @RequestMapping("/request-param-default")
    public String requestParamDefault(
            @RequestParam(required = true, defaultValue = "guest") String username,
            @RequestParam(required = false, defaultValue = "-1") int age) {
        log.info("username={}, age={}", username, age);
        return "ok";
    }

    /**
     * @RequestParam Map, MultiValueMap
     * Map(key=value)
     * MultiValueMap(key=[value1, value2, ...]) ex) (key=userIds, value=[id1, id2])
     */
    @ResponseBody
    @RequestMapping("/request-param-map")
    public String requestParamMap(@RequestParam Map<String, Object> paramMap) {
        log.info("username={}, age={}", paramMap.get("username"),
                paramMap.get("age"));
        return "ok";
    }

    @ResponseBody
    @RequestMapping("/model-attribute-v1")
    public String modelAttributeV1(@RequestParam String username, @RequestParam int age) {
        HelloData helloData = new HelloData();

    }
}

 

spring mvc

回答 2

0

y2gcoder

안녕하세요. gmldnjs0402님, 공식 서포터즈 y2gcoder입니다.

스스로 잘 해결하셨습니다 :) 

강의 수강 중 강의 관련 궁금한 사항은 언제든 질문 남겨주세요^^

0

gmldnjs0402

HelloData 파일 새로 만들었더니 되었습니다. 처음에 잘못 만들어졌나봐요

servlet과 container에 대한 질문입니다

0

24

1

api를 어느 컨트롤러에 작성해야하는지는 어떤 기준으로 해야하나요?

0

62

1

jsp 의존성 수정 요청

0

77

2

요즘 웹 서버가 주로 사용되는 이유는 SPA 구조 때문일까요 ?

0

142

1

save() 메서드 문의

0

66

1

절대 경로로 templates/basic 하위 파일 열면 css 적용 안되는 현상

0

100

1

request-body-json

0

83

2

MVC 패턴의 적용 단위

0

95

1

RequestMapping을 이용한 핸들러, 어댑터

0

118

2

save 후 결과화면

0

88

2

jsp를 이용한 view

0

97

1

application.properties에 debug 추가해도 결과가 똑같습니다.

0

177

1

수업 코드 제공 관련 문의

0

97

2

RequestMappingHandlerAdapter의 Controller 호출 과정

0

99

3

파일 오픈 시

0

69

1

스프링 배치 관련

0

77

1

@RequestParam의 defaultValue가 blank 값도 처리하는 지 여부

0

112

1

postman으로 /request-body-json-v1 호출시 500 error

0

94

1

프론트엔드와 백엔드의 mvc, rest api에 대한 질문

0

78

1

모델의 역할과 계층 분리에 대한 이해 차이 + 추가질문

0

111

1

console log 출력 관련 질문입니다.

0

74

1

애플리케이션이 실행 되지 않습니다 ㅠㅠㅠ

0

139

1

html 변경하는 부분 적용 문제

0

103

1

한글 깨짐

0

76

2