Spring MVC에서 @ModelAttribute는 무엇입니까?
@ModelAttribute
Spring MVC 의 목적과 사용법은 무엇입니까 ?
@ModelAttribute
Model 객체의 속성 (MVC의 M)을 참조하므로 "Person"이라는 폼 백업 객체를 가진 폼이 있다고 가정 해 봅시다. 그러면 스프링 MVC가 @ModelAttribute
어노테이션 을 사용하여 Controller 메소드에이 객체를 제공하도록 할 수 있습니다 :
public String processForm(@ModelAttribute("person") Person person){
person.getStuff();
}
반면에 주석은 모델의 일부 여야하는 객체를 정의하는 데 사용됩니다. 따라서 모델에서 Person 객체를 참조하려면 다음 방법을 사용할 수 있습니다.
@ModelAttribute("person")
public Person getPerson(){
return new Person();
}
이 주석이 달린 메소드는 Spring의 Models에 자동으로 추가되므로 View의 Person 객체에 액세스 할 수 있습니다.
"@ModelAttribute 사용"을 참조하십시오 .
나는 이것이 오래된 실이라는 것을 알고 있지만, 반지에 모자를 던지고 물을 조금 더 흐릴 수 있는지 알았습니다. :)
처음 이해해야 할 어려움 @ModelAttribute
은 Spring이 여러 주석을 하나로 결합하기로 한 결정의 결과 라는 것을 알았 습니다. 여러 개의 작은 주석으로 나누면 더 명확 해졌습니다.
매개 변수 어노테이션의 @ModelAttribute
경우와 동등한 것으로 생각 하십시오. @Autowired + @Qualifier
즉, 스프링 관리 모델에서 지정된 이름의 Bean을 검색하려고 시도합니다. 명명 된 Bean을 찾을 수 없으면 오류를 던지거나을 리턴하는 대신 null
내재적 @Bean
으로 기본 생성자를 사용하여 새 인스턴스를 작성하고 모델에 Bean을 추가하는 역할을 수행 합니다.
메소드 어노테이션의 @ModelAttribute
경우와 동등한 것으로 생각 하십시오 @Bean + @Before
. 즉, 사용자 코드로 구성된 Bean을 모델에 넣고 항상 요청 처리 메소드 전에 호출됩니다.
비 유적으로, 나는 @ModelAttribute
다음과 같이 본다 (말 그대로 받아들이지 마라 !!) :
@Bean("person")
@Before
public Person createPerson(){
return new Person();
}
@RequestMapping(...)
public xxx handlePersonRequest( (@Autowired @Qualifier("person") | @Bean("person")) Person person, xxx){
...
}
보시다시피 Spring은 @ModelAttribute
포괄적 인 주석 을 만들기 위해 올바른 결정을 내 렸습니다 . 아무도 주석 smorgasbord를보고 싶지 않습니다.
내 스타일의 경우 항상 @ModelAttribute를 사용하여 스프링 형식 jsp에서 객체를 잡습니다. 예를 들어 jsp 페이지에서 양식을 디자인하면 해당 양식이 commandName과 함께 존재합니다.
<form:form commandName="Book" action="" methon="post">
<form:input type="text" path="title"></form:input>
</form:form>
다음 코드를 사용하여 컨트롤러에서 객체를 잡습니다.
public String controllerPost(@ModelAttribute("Book") Book book)
책의 모든 필드 이름은 양식의 하위 요소에있는 경로와 일치해야합니다.
그래서 더 간단한 방법으로 설명하려고 노력할 것입니다. 하자 :
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
Spring MVC 문서에 설명 된 것처럼 @ModelAttribute 주석은 메소드 또는 메소드 인수 에서 사용할 수 있습니다 . 물론 하나의 컨트롤러에서 동시에 두 가지를 모두 사용할 수 있습니다.
1. 방법 주석
@ModelAttribute(“cities”)
public List<String> checkOptions(){
return new Arrays.asList(new[]{“Sofia”,”Pleven","Ruse”});//and so on
}
이러한 방법의 목적은 모델에 속성을 추가하는 것입니다. 따라서 우리의 경우 도시 키는 목록 new Arras.asList(new[]{“Sofia”,”Pleven","Ruse”})
을 모델의 값으로 가질 것입니다 (모델을 map (key : value)로 생각할 수 있습니다). 컨트롤러의 @ModelAttribute 메서드 는 동일한 컨트롤러 내에서 @RequestMapping 메서드 보다 먼저 호출됩니다 .
여기서는 사용자에게 표시하기 위해 양식에 사용될 공통 정보를 모델에 추가하려고합니다. 예를 들어 HTML 선택을 채우는 데 사용할 수 있습니다.
2. 방법론
public String findPerson(@ModelAttriute(value="person") Person person) {
//..Some logic with person
return "person.jsp";
}
메소드 인수의 @ModelAttribute는 모델에서 인수를 검색해야 함을 나타냅니다. 따라서이 경우 Model person 객체에 키가 있고 값을 가져 와서 Person 인수 메서드 인수에 넣기를 원합니다 . 그러한 것이 존재하지 않거나 (때로는 (value = "persson")의 철자를 틀리면) Spring은 모델에서 그것을 찾지 못하고 기본값을 사용하여 빈 Person 객체를 만듭니다. 그런 다음 요청 매개 변수를 사용하여 이름을 사용하여 Person 개체에서 데이터 바인딩을 시도합니다.
name="Dmitrij"&countries=Lesoto&sponsor.organization="SilkRoad"&authorizedFunds=&authorizedHours=&
따라서 이름이 있으며 setName (String name)을 사용하여 Person.name에 바인딩됩니다. 그래서
//..Some logic with person
값이 "Dimitrij"인이 채워진 이름에 액세스 할 수 있습니다.
물론 Spring은 Lists, Maps, List of Maps 등과 같은 더 복잡한 객체를 바인딩 할 수 있지만 장면 뒤에서 데이터 바인딩을 마술로 만듭니다.
인수에 @ModelAttribute를 사용하여 모델 어노테이션이있는 메소드 및 요청 메소드 핸들러를 동시에 가질 수 있습니다. 그런 다음 규칙을 통합해야합니다.
물론 우리는 다양한 상황을 가지고 있습니다-@ModelAttribute 메소드는 @ControllerAdvice 등에서도 정의 될 수 있습니다 ...
나는 파티에 늦었다는 것을 알고 있지만, "더 나은 것보다 늦지 말라"라고 말하는 것처럼 인용 할 것이다. 모든 사람들이 설명 할 수있는 방법이 있습니다. 예를 들어 몇 단계 만 거치면 간단하게 정리해 보겠습니다. 간단한 형식 form.jsp가 있다고 가정하십시오.
<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>
path = "firstName"path = "lastName"이들은 폼이 호출되는 호출자 (getter)가 호출되었지만 일단 제출 된 설정자가 호출되고 해당 값이 modelAttribute에 표시된 Bean에 설정 될 때 StudentClass의 필드 / 속성입니다. 양식 태그에서 "학생".
우리는 다음 메소드를 포함하는 StudentController를 가지고 있습니다;
@RequestMapping("/showForm")
public String showForm(Model theModel){ //Model is used to pass data between
//controllers and views
theModel.addAttribute("student", new Student()); //attribute name, value
return "form";
}
@RequestMapping("/processForm")
public String processForm(@ModelAttribute("student") Student theStudent){
System.out.println("theStudent :"+ theStudent.getLastName());
return "form-details";
}
//@ModelAttribute("student") Student theStudent
//Spring automatically populates the object data with form data all behind the
//scenes
이제 마지막으로 form-details.jsp가 있습니다.
<b>Student Information</b>
${student.firstName}
${student.lastName}
Spring MVC에서 @ModelAttribute는 무엇입니까? 당신의 소스에서 샘플 정의는 http://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation @ModelAttribute는 주석입니다 명명 된 모델 속성에 바인딩하는 방법 매개 변수 또는 메서드 반환 값 그런 다음 웹보기에 노출시킵니다.
실제로 발생하는 것은 양식에서 제출 한 양식의 모든 값을 가져 와서 객체에 바인딩하거나 할당 할 수 있도록 유지하는 것입니다. 매개 변수 만 가져 와서 일부 필드에 값을 할당하는 @RequestParameter 와 동일하게 작동 합니다. 차이점은 @ModelAttribute 는 단일 매개 변수가 아닌 모든 양식 데이터를 보유한다는 것입니다. 나중에 개발자가 사용할 양식 제출 데이터를 보유하는 Bean을 작성합니다.
모든 것을 요약합니다. 1 단계 : 요청이 전송되고 메소드 showForm이 실행되고 모델이 생성되며, 임시 bean은 student라는 이름으로 설정되어 양식으로 전달됩니다. theModel.addAttribute ( "student", new Student ());
2 단계 : 양식 제출 모델의 modelAttribute = "student" 가 학생을 변경하고 이제 양식의 모든 매개 변수를 보유합니다.
3 단계 : @ModelAttribute ( "student") Student theStudent @ModelAttribute 가 보유한 값을 가져 와서 전체 Bean / 객체를 Student에 지정합니다.
4 단계 : 그런 다음 페이지에 표시 한 것처럼 입찰에 따라 사용합니다.
나는 그것이 당신이 개념을 이해하는 데 도움이되기를 바랍니다. 감사
Gmail, Facebook 또는 Instagram 또는 기타 웹 응용 프로그램이든 웹 응용 프로그램을 사용하십시오. 최종 사용자와 응용 프로그램 또는 UI와 백 엔드 응용 프로그램간에 데이터 또는 정보를 교환하는 것입니다. Spring MVC 세계에서도 데이터를 교환하는 두 가지 방법이 있습니다.
- 컨트롤러에서 UI로
- UI에서 컨트롤러로.
여기서 관심이있는 것은 UI에서 컨트롤러로 데이터를 전달하는 방법입니다. 이 작업은 두 가지 방법으로 수행 할 수도 있습니다.
- HTML 양식 사용
- 쿼리 매개 변수 사용
HTML 양식 사용 : 아래 시나리오를 고려하십시오.
웹 브라우저에서 양식 데이터를 제출하면 Controller 클래스의 해당 데이터에 객체로 액세스 할 수 있습니다. HTML 양식을 제출하면 스프링 컨테이너는 4 가지를 수행합니다. 그것은
- 먼저 request.getParameter 메소드를 사용하여 요청에 제공된 제출 된 모든 데이터를 읽습니다 .
- 일단 읽고 나면 integer.parseInt , double.parseDouble 및 데이터의 데이터 유형에 따라 사용 가능한 다른 모든 구문 분석 메소드를 사용하여 적절한 Java 유형으로 변환합니다 .
- 구문 분석되면 생성 한 모델 클래스의 객체가 생성됩니다. 예를 들어,이 시나리오에서는 제출되는 사용자 정보이며 User라는 클래스를 작성합니다.이 클래스는 컨테이너가 오브젝트를 작성하고 해당 오브젝트에 자동으로 들어오는 모든 값을 설정합니다.
- 그런 다음 값을 Controller로 설정하여 해당 객체를 핸드 오버합니다.
이 모든 것이 작동하게하려면 특정 단계를 따라야합니다.
We first need to define a model class, like User, in which the number of fields should exactly match the number of fields in the HTML form. Also, the names that we use in the HTML form should match the names that we have in the Java class. These two are very important. Names should match, the number of fields in the form should match the number of fields in the class that we create. Once we do that, the Container will automatically read the data that comes in, creates an object of this model, sets the values and it hands it over to the Controller. To read those values inside the Controller, we use the @ModelAttribute annotation on the method parameters. When we create methods in the Controller, we are going to use the @ModelAttribute and add a parameter to it which will automatically have this object given by the Container.
Here is an example code for registering an user:
@RequestMapping(value = "registerUser", method = RequestMethod.POST)
public String registerUser(@ModelAttribute("user") User user, ModelMap model) {
model.addAttribute("user", user);
return "regResult";
}
Hope this diagrammatic explanation helped!
This is used for data binding purposes in Spring MVC
. Let you have a jsp having a form element in it e.g
on
JSP
<form:form action="test-example" method="POST" commandName="testModelAttribute"> </form:form>
(Spring Form method, Simple form element can also be used)
On Controller Side
@RequestMapping(value = "/test-example", method = RequestMethod.POST)
public ModelAndView testExample(@ModelAttribute("testModelAttribute") TestModel testModel, Map<String, Object> map,...) {
}
Now when you will submit the form the form fields values will be available to you.
Annotation that binds a method parameter or method return value to a named model attribute, exposed to a web view.
public String add(@ModelAttribute("specified") Model model) {
...
}
@ModelAttribute can be used as the method arguments / parameter or before the method declaration. The primary objective of this annotation to bind the request parameters or form fields to an model object
Ref. http://www.javabeat.net/modelattribute-spring-mvc/
@ModelAttribute
will create a attribute with the name specified by you (@ModelAttribute("Testing") Test test) as Testing
in the given example ,Test being the bean test being the reference to the bean and Testing will be available in model so that you can further use it on jsp pages for retrieval of values that you stored in you ModelAttribute
.
@ModelAttribute simply binds the value from jsp fields to Pojo calss to perform our logic in controller class. If you are familiar with struts, then this is like populating the formbean object upon submission.
The ModelAttribute annotation is used as part of a Spring MVC Web application and can be used in two scenarios.
First of all, it can be used to inject data into a pre-JSP load model. This is especially useful in ensuring that a JSP is required to display all the data itself. An injection is obtained by connecting one method to the model.
둘째, 기존 모델에서 데이터를 읽고 코치 방법의 파라미터에 할당하는 데 사용할 수 있습니다.
굴절 https://dzone.com/articles/using-spring-mvc%E2%80%99s
참고 URL : https://stackoverflow.com/questions/3423262/what-is-modelattribute-in-spring-mvc
'Programing' 카테고리의 다른 글
A4 용지 크기 페이지에서 HTML 페이지를 만드는 방법은 무엇입니까? (0) | 2020.03.01 |
---|---|
C ++ 템플릿 typedef (0) | 2020.03.01 |
MongoDB 컬렉션의 객체 배열에서 쿼리 된 요소 만 검색 (0) | 2020.03.01 |
메소드를 정적으로 만들 수는 있지만 그렇게해야합니까? (0) | 2020.03.01 |
\ r \ n, \ r 및 \ n 그들 사이의 차이점은 무엇입니까? (0) | 2020.03.01 |