티스토리 뷰

1. Spring MVC form tags

(1) Spring이 form tag를 제공한다. 

 - Spring MVC form tag들은 web page를 만드는 building block이다.

 - Form tag들은 configurable하며, web page에서 재사용이 가능하다.

 

(2)  Spring MVC form tag들은 data binding이라는 추가적인 지원을 제공한다.

 - Spring MVC form tag들이 이 data binding을 이용할 수 있다

 - 자동적으로 Java 객체 / bean으로 부터 data를 세팅하고 회수한다.

 

(3) Web Page Structure

 - JSP페이지에서 spring MVC form tag들을 사용할 수 있다. HTML 코드와 spring MVC form tag를 혼합하여 사용 가능하다.

 

(4) Spring MVC form tag를 참조하는 법

 - JSP 파일 앞에 spring namespace를 표기한다.

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>를 써주면 된다.

 

(5) Spring MVC form tag의 종류

Spring MVC Form Tags

2. Text field

(1) 개요

 - 큰 그림으로 보자면, 앞으로 생성할 student-form.jsp 폼 페이지에서 정보를 submit하면 studentController로 student data를 넘기게 되고, controller에서 다시 submit한 student-confirmation.jsp페이지로 student data를 넘긴다.

Spring container에서, form을 보여주기 전에 반드시 model attribute를 추가해 주어야 한다. 이것이 data binding을 위해 data를 잡아줄 bean이다. 

 

(2) 개발 과정

1) Student class생성
2) Student controller class 생성
3) HTML form 생성
4) form processing code 생성
5) confirmation page 생성

 

(3) 코드 예시

1) Student class생성

package com.luv2code.springdemo.mvc;

public class Student {
	
	private String firstName;
	private String lastName;
	
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
}

2) Student controller class 생성, 4) form processing code 생성

package com.luv2code.springdemo.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/student")
public class StudentController {
	
		@RequestMapping("/showForm")
		public String showForm(Model theModel) {
			
			// create a student object
			Student theStudent = new Student();
			
			// add student object to the model
			theModel.addAttribute("student", theStudent);
			// name : student, value : theStudent
			
			return "student-form";
		}
		
		@RequestMapping("/processForm")
		public String processForm(@ModelAttribute("student") Student theStudent) {
			
			// log the input data
			System.out.println("theStudent : " + theStudent.getFirstName()
			+ " "+ theStudent.getLastName());
			return "student-confirmation";
		}
}

3) HTML form 생성

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
	<title>Student Registration Form</title>
</head>
<body>
	<form:form action="processForm" modelAttribute="student">
	
	First name : <form:input path="firstName"/>
	<br><br>
	Last name : <form:input path="lastName"/>
	<br><br>
	<input type="submit" value="Submit"/>
	
	</form:form>

</body>
</html>

5) confirmation page 생성

<!DOCTYPE html>
<html>
<head>
	<title>Student Confirmation</title>
</head>
<body>

The student is confirmed : ${student.firstName} ${student.lastName}

</body>

</html>

(4) 진행 원리 :

 1) Student 객체, class를 만들어서, /showform으로 form을 보여줄 때, model에 'student'라는 이름으로, Student객체를 반환한다. Student객체를 담은 model을 view template인 student-form.jsp로 보내는것이다.

student-form.jsp 폼 페이지에서 modelAttribute로 추가하는 이름과 동일해야한다. (model 이름으로 찾아 오는 것)

 

 2) Spring에서 제공하는 폼 테그의 path="firstName", path="lastName"으로 설정해주면, form field를 bean의 property와 binding시켜준다.

form이 loaded 되면 getter 메소드를 부른다. 여기서는 spring MVC가 Student.getFirstName()을 부른다. 여기서 위의 model attribute를 사용하는것이다. model attribute를 통해서 동일한 이름을 가진 model의 객체를 가지고 오는 것이다.

만약 null이라면 빈값을 반환하게 되는것이고 getter를 설정함으로서 값을 변화해 줄 수 있다.

form이 submit될때에는 setter 메소드를 호출해 입력된 값을 넘긴다. 여기서는 Student.setFirstName(...)을 호출하여 값을 넘긴다.

 

3) Controller에서 실제로 form 데이터를 어떻게 읽는가

->spring annotation인 @ModelAttribute를 통해서 model을 가지고 올 수 있다.

폼 작성후 submit을 통해 /processForm에 browser가 request를 보내면 controller의 @ModelAttribute를 통해서 student-form.jsp인 폼 페이지, view template에서 오는 정보를 받을 수 있다.

Model 객체를 다시 돌려 받는것이다. 그리고 그 정보를 controller에서 사용할 수 있고, 다시 view template인 confirmation페이지로 보내서 ${}를 통해서 읽을 수도 있다.

**위의 코드를 보면, @ModelAttribute로 설정한 student의 폼을 를 Student객체의 theStudent에 data binding시켜서 Controller에서 form에 대한 data에 접근이 가능하게 된다. getter와 setter method를 부름으로서 접근 할 수 있기때문에 request.getParameter로 하나하나 필드 접근 할 필요가 없어진다.(Data binding의 개념)**

 

4) confirmation page에서 ${student.firstName}과 같이 model attribute name을 사용해서 getter를 통해 property에 접근한다.

* ${student.firstName}, ${student.lastName} : student.getFirstName(), student.getLastName()을 부른다.

 

3. Drop-down List

(1) 개요

 - drop-down list는 <fom:select>와 <form:option>로 표현된다. <form:options>로 list를 받아 올 수도 있다.

<form:select path="country">처럼 binding할 path를 설정해 준다. 그리고 option을 통해서 value와 lable을 준다.(lable은 user가 스크린을 통해 보는것, value는 submit시 넘겨주는 실제코드)

 

(2) 개발 과정

1) Update HTML form
2) Update Student class -add getter/setter for new property
3)
Update confirmation page

 

(3) 코드 예시

1) Update HTML form

Country : 
	
	<form:select path="country">
		<!--<form:option value="Brazil" label="Brazil"/>
		<form:option value="France" label="France"/>
		<form:option value="Germany" label="Germany"/>
		<form:option value="India" label="India"/> -->
		<form:options items="${student.countryOptions}"/>
		
	</form:select>

2) Update Student class -add getter/setter for new property

private String country;


public String getCountry() {
		return country;
	}
	public void setCountry(String country) {
		this.country = country;
	}
	public LinkedHashMap<String, String> getCountryOptions() {
		return countryOptions;
	}
	// when form is loaded, Spring will call student.getCountryOptions()
    
private LinkedHashMap<String, String> countryOptions;
	public Student() {
			// populate country options : used ISO country code
		countryOptions = new LinkedHashMap<>();
		
		countryOptions.put("BR", "Brazil");
		countryOptions.put("FR", "France");
		countryOptions.put("DE", "Germany");
		countryOptions.put("IN", "India");
		countryOptions.put("US", "United States of America");
		countryOptions.put("KR", "Republic of Korea");
	}

3) Update confirmation page

Country : ${student.country}

* Country list를 Java 클래스로 부터 받아야 한다면 어떻게 해야할까

 1) Country option을 정의한다 -> LinkedHashMap으로. 그리고 getter를 만든다 (setter는 사용할 필요가 없음)

 2) <form:options items="${student.countryOptions}"/>를 통해서 getCountryOptions를 부른다. 

 

3. Radio Buttion과 Check Box

기본 원리는 모두 동일하고, radio button은 

<form:radiobutton path="favoriteLanguage" value="Java"/>과 같이 사용하면 되며

checkbox는  <form:checkbox path="operatingSystems" value="Linux"/>처럼 사용하면 되는데, 

checkbox는 여러개를 선택할 수 있기 때문에 String[] 배열로 받아 confirmation page에서 출력할 때 JSTL을 이용하여 forEach를 통해 개수만큼 반환해 주면 된다.

 

* 위 <form:options>를 통해서 Student 자바 객체에서 값을 가져오도록 radio를 만들어 주고 싶다면, <form:radiobuttons>를 이용하여 동일한 방법으로 설정 가능하다.

 

모든 예시는 다음과 같다.

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
	<title>Student Registration Form</title>
</head>
<body>
	<form:form action="processForm" modelAttribute="student">
	
	First name : <form:input path="firstName"/>
	
	<br><br>
	
	Last name : <form:input path="lastName"/>
	
	<br><br>
	
	Country : 
	
	<form:select path="country">
		<!--<form:option value="Brazil" label="Brazil"/>
		<form:option value="France" label="France"/>
		<form:option value="Germany" label="Germany"/>
		<form:option value="India" label="India"/> -->
		<form:options items="${student.countryOptions}"/>
		
	</form:select>
	
	<br><br>
	Favorite Language : 
	
	Java <form:radiobutton path="favoriteLanguage" value="Java"/>
	C# <form:radiobutton path="favoriteLanguage" value="C#"/>
	PHP <form:radiobutton path="favoriteLanguage" value="PHP"/>
	Ruby <form:radiobutton path="favoriteLanguage" value="Ruby"/>
	
	<br><br>
	
	Operating Systems : 
	Linux <form:checkbox path="operatingSystems" value="Linux"/>
	Mac OS <form:checkbox path="operatingSystems" value="Mac OS"/>
	Window <form:checkbox path="operatingSystems" value="Window"/>
	
	<br><br>
	
	<input type="submit" value="Submit"/>
	
	</form:form>

</body>
</html>
package com.luv2code.springdemo.mvc;

import java.util.LinkedHashMap;

public class Student {
	
	private String firstName;
	private String lastName;
	
	private String country;
	
	private String favoriteLanguage;
	
	private String[] operatingSystems;
	// 중요한점 : multiple선택을 할 수 있기때문에 collection이 필요하다.
	
	
	private LinkedHashMap<String, String> countryOptions;
	
	public Student() {
			// populate country options : used ISO country code
		countryOptions = new LinkedHashMap<>();
		
		countryOptions.put("BR", "Brazil");
		countryOptions.put("FR", "France");
		countryOptions.put("DE", "Germany");
		countryOptions.put("IN", "India");
		countryOptions.put("US", "United States of America");
		countryOptions.put("KR", "Republic of Korea");
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getCountry() {
		return country;
	}
	public void setCountry(String country) {
		this.country = country;
	}
	public LinkedHashMap<String, String> getCountryOptions() {
		return countryOptions;
	}
	// when form is loaded, Spring will call student.getCountryOptions()
	//get만 만들어도 된다.
	public String getFavoriteLanguage() {
		return favoriteLanguage;
	}
	public void setFavoriteLanguage(String favoriteLanguage) {
		this.favoriteLanguage = favoriteLanguage;
	}
	public String[] getOperatingSystems() {
		return operatingSystems;
	}
	public void setOperatingSystems(String[] operatingSystems) {
		this.operatingSystems = operatingSystems;
	}
}
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
	<title>Student Confirmation</title>
</head>
<body>

The student is confirmed : ${student.firstName} ${student.lastName}

<br><br>

Country : ${student.country}

<br><br>

Favorite Language : ${student.favoriteLanguage}

<br><br>

<ul>
	<c:forEach var="temp" items="${student.operatingSystems}">
	
	<li> ${temp} </li>
	
	</c:forEach>
</ul>

</body>

</html>
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday