Front-end

Form 태그 톺아보기!

xeunnie 2024. 7. 29. 01:44
728x90
반응형

1. HTML Form 태그란?

웹 개발에서 사용자와의 상호작용을 가능하게 하는 핵심 요소 중 하나는 바로 HTML form 태그다!
form 태그는 사용자가 웹 페이지에서 데이터를 입력하고, 이를 서버로 전송하기 위한 HTML 요소로 로그인, 회원가입, 검색, 데이터 입력 등 다양한 작업에서 사용된다.

2. 기본 구조

<form action="submit_form.php" method="post">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required>

    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required>

    <input type="submit" value="Submit">
</form>
  • action: 폼 데이터를 처리할 서버의 URL
  • method: 데이터를 전송하는 HTTP 메서드(GET 또는 POST)

3. Form 속성

  • action: 폼 데이터를 처리할 서버의 URL을 지정한다.
  • <form action="process.php" method="post">
  • method: 데이터를 전송하는 방법을 지정한다. GETPOST가 있으며, GET은 데이터를 URL에 붙여서 전송하고, POST는 데이터를 HTTP 본문에 담아서 전송한다.
  • <form action="process.php" method="post"> <form action="process.php" method="get">
  • enctype: 폼 데이터의 인코딩 방식을 지정한다. 파일 업로드 시 multipart/form-data를 사용한다.
  • <form action="upload.php" method="post" enctype="multipart/form-data">

4. Form 요소

  • input: 사용자가 데이터를 입력할 수 있는 요소가 된다.
      <input type="text" name="username" required>
      <input type="password" name="password" required>
  • label: 입력 요소에 대한 설명을 제공한다.
      <label for="username">Username:</label>
  • textarea: 여러 줄의 텍스트를 입력할 수 있는 요소가 된다.
      <textarea name="message"></textarea>
  • select: 드롭다운 목록을 생성한다.
      <select name="options">
          <option value="option1">Option 1</option>
          <option value="option2">Option 2</option>
      </select>
  • button: 버튼을 생성합니다. type 속성으로 동작을 정의한다.
      <button type="submit">Submit</button>
      <button type="reset">Reset</button>

5. 고급 사용법

5.1. JavaScript와의 연동

JavaScript를 사용하여 폼의 제출을 제어하거나 데이터를 검증할 수 있다.

<form id="myForm" action="process.php" method="post" onsubmit="return validateForm()">
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>
    <input type="submit" value="Submit">
</form>

<script>
function validateForm() {
    var email = document.getElementById('email').value;
    if (email == "") {
        alert("Email must be filled out");
        return false;
    }
    return true;
}
</script>
5.2. AJAX를 통한 비동기 전송

AJAX를 사용하면 페이지를 새로 고치지 않고도 폼 데이터를 서버로 전송할 수 있다.

Axios를 사용한 예시

axios는 비동기 HTTP 요청을 처리하기 위한 인기 있는 JavaScript 라이브러리다.

<!DOCTYPE html>
<html>
<head>
    <title>Form with Axios</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
    <form id="axiosForm">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <input type="submit" value="Submit">
    </form>

    <script>
        document.getElementById('axiosForm').addEventListener('submit', function(event) {
            event.preventDefault(); // 기본적으로 제출하는 폼 동작을 막는다!

            var name = document.getElementById('name').value;

            axios.post('/submit-form', {
                name: name
            })
            .then(function(response) {
                console.log(response.data);
                alert('Form submitted successfully!');
            })
            .catch(function(error) {
                console.error('Error submitting form:', error);
            });
        });
    </script>
</body>
</html>
Fetch API를 사용한 예시

fetch는 JavaScript 내장 API로, 비동기 HTTP 요청을 처리하는 데 사용한다.

<!DOCTYPE html>
<html>
<head>
    <title>Form with Fetch</title>
</head>
<body>
    <form id="fetchForm">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <input type="submit" value="Submit">
    </form>

    <script>
        document.getElementById('fetchForm').addEventListener('submit', function(event) {
            event.preventDefault();

            var name = document.getElementById('name').value;

            fetch('/submit-form', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ name: name })
            })
            .then(response => response.json())
            .then(data => {
                console.log(data);
                alert('Form submitted successfully!');
            })
            .catch(error => {
                console.error('Error submitting form:', error);
            });
        });
    </script>
</body>
</html>
5.3. 파일 업로드

파일 업로드를 지원하려면 enctype 속성을 multipart/form-data로 설정해야 한다.

<form action="upload.php" method="post" enctype="multipart/form-data">
    <label for="file">Choose file:</label>
    <input type="file" id="file" name="file">
    <input type="submit" value="Upload">
</form>

서버 측에서는 파일 데이터를 처리할 수 있는 코드를 작성해야 한다. 예를 들어, Spring Boot에서는 다음과 같이 처리할 수 있다!

@RestController
public class FileUploadController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @PostMapping("/upload")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("No file uploaded or file upload error.");
        }

        try {
            // 파일 저장 경로 설정
            byte[] bytes = file.getBytes();
            Path path = Paths.get(uploadDir + file.getOriginalFilename());
            Files.write(path, bytes);

            return ResponseEntity.ok("File is valid, and was successfully uploaded.");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Possible file upload attack!");
        }
    }
}

6. 보안 고려사항

  1. CSRF 방지: 폼 제출 시 CSRF 토큰을 포함하여 서버에서 검증해야 한다.
  2. 입력 데이터 검증: 서버 측에서 모든 입력 데이터를 철저히 검증하고 필터링하여 SQL 인젝션 및 XSS 공격을 방지해야 한다.
  3. HTTPS 사용: 폼 데이터를 안전하게 전송하기 위해 HTTPS를 사용해야 한다.
728x90
반응형