개발자 끄적끄적
Spring WebForm 본문
<Request Parameters>
- The qurey string(in GET Method)
- ex)
GET /helloWeb/docreate?name=Alice&email=alice.hansung.ac.kr
Host: myserver.com
User-Agent: ...
Accept-Encoding: ...
- The HTTP entitiy body(in POST Method)
- ex)
POST /helloWeb/docreate HTTP/1.1
Host: myserver.com
User-Agent: ...
Accept-Encoding:
name=Alice&email=alice@hansung.ac.kr
<Problem>
- How to move from the 'request prarmeters' to corresponding 'object'
1) Naive solution
- The '@RequestParam' annotation binds request parameters to method parameters
- ex)
@RequestMapping("/docreate")
public String doCreate(@RequestParam("name") String name,
@RequestParam("email") String email,
Model model) {
// we manually populate the Offer object with
// the data coming from the user
Offer offer = new Offer();
offer.setName(name);
offer.setEmail(email);
...
}
2) Spring Data Binding
- ex)
@RequestMapping(value="/docreate", method=RequestMethod.POST)
public String doCreate(Offer offer) {
// offer object will be automatically populated
// with request parameters
}
- The following sequence of operations occurs
- A new form bean is 'instantiated'
- The form bean is 'populated' from the request parameters
- The form bean is 'added' to the model
- The ‘offer’ form bean will be 'automatically added' to the model
- Form bean is a model attribute
- HTTP request -> DispatcherServlet -> OffersController(controller)
- ex) View
<html>
<head>
<title>Thanks</title>
</head>
<body> Hi, ${offer.name}.
You have successfully registered. <br/>
</body>
</html>
<Hibernate Validator>
- 검증 애노테이션 API를 이용하여 실제로 검증해주는 역할
- ex)
public class Offer {
private int id;
@Size(min=5, max=100)
@Pattern(regexp="^[A-Z]{1}[a-z]+$")
private String name;
@NotEmpty
@Email
private String email;
...
}
<Message Interpolation>
- ex)
public class Offer {
private int id;
@Size(min=5, max=100, message="Name must be between 5 and 100 characters")
private String name;
@Email(message="please provide a valid email address")
@NotEmpty(message="the email address cannot be empty")
private String email;
@Size(min=5, max=100, message="Text must be between 5 and 100 characters")
private String text;
}
<Validationg Object>
- @Valid 어노테이션 사용
- ex)
@RequestMapping(...)
public String doCreate(@Valid Offer offer { ... }
- The handler method may ask for a 'BindingResult' object,
which represent the result of the validation process
- ex)
@RequestMapping(...)
public String doCreate(@Valid Offer offer, BindingResult result )
{ ... }
- We can then inspect the BindingResult object for possible validation errors
- ex)
@RequestMapping(...)
public String doCreate(@Valid Offer offer, BindingResult result) {
if(result.hasErrors()) {
List<ObjectError> errors = result.getAllErrors();
for(ObjectError error:errors) {
System.out.println(error.getDefaultMessage());
}
return "createoffer";
}
...
}
<Spring form tags>
- The <sf:input>, <sf:password> and <sf:checkbox> tags are 'data-binding' versions of the corresponding HTML elements
- <sf:form> (Spring form tag lib) -> <form> (HTML)
<sf:input> -> <input type="text">
<sf:password> -> <input type="password">
<sf:checkbox> -> <input type="checkbox">
<Revised JSP(createoffer.jsp)>
- ex)
<%@ taglib prefix=”sf" uri="http://www.springframework.org/tags/form"%>
...
<body>
<sf:form method="post"
action="${pageContext.request.contextPath}/docreate" modelAttribute="offer"> //modelAttribute -> object
<table class="formtable">
<tr>
<td class="label">Name:</td>
<td><sf:input class="control" path="name"/></td> //path="name" -> Object Property
</tr>
...
</sf:form>
</table>
<Revised Controller>
1. Initial Web FOrm
- ex)
@RequestMapping("/createoffer")
public String createOffer(Model model) {
model.addAttribute("offer", new Offer());
return "createoffer";
}
2. Web Form on Error
- BindResult : 검증 오류를 보관하는 객체이다
- 사용자가 정수형 필드에 문자를 넣는 경우를 생각해보면 된다.
객체에 타입 오류 등으로 바인딩이 실패하면 스프링이 FieldError를 생성해서 BindingResult에 넣어준다
- ex)
@RequestMapping(value="/docreate", method=RequestMethod.POST)
public String doCreate(@Valid Offer offer, BindingResult result) {
if(result.hasErrors()) {
return "createoffer"; }
...
}
</body>
</html>
<Error Messages>
- the 'BindingResult' object is 'automatically inserted' into the model and sent back to the view
- Offers Controller(controller) -> OfferBindingResult(model) -> DispatcherServelt -> OfferBindingResult(model) -> View
- Spring MVC provides the '<sf:errors>' tag as part of the Spring’s form tag library
- The <sf:errors> tag renders in HTML error messages taken from the BindingResult object
- ex) <sf:errors path="name"/>
- ex)
<sf:form modelAttribute="offer">
Name: <sf:input path="name" />
<sf:errors path="name” />
Email: <sf:input path="email" />
<sf:errors path="email” />
…
</sf:form>
------------------------------------------------
- ex)
public class Offer {
private int id;
@Size(min=5, max=100, message="Name must be between 5 and 100 characters")
private String name;
@Email(message="please provide a valid email address")
@NotEmpty(message="the email address cannot be empty")
private String email;
@Size(min=5, max=100, message="Text must be between 5 and 100 characters")
private String text;
}
<Summary>
- Form beans are versatile(변하기 쉬운) objects, as they play 'different roles' at the same time
- Data binder
- Data balidator
- Data buffer
'웹프레임워크' 카테고리의 다른 글
Spring Security (0) | 2024.04.23 |
---|---|
Spring MVC (0) | 2024.04.23 |
DI(Dependency Injection) (0) | 2024.04.23 |