[Spring MVC]-간단 한 폼 제출 인 스 턴 스
다음은 비교적 간단 한 폼 제출 페이지 기능 입 니 다.
1、User model
package com.my.controller.bean;
import java.util.Date;
import java.util.List;
import javax.validation.constraints.Future;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
public class User {
private long id;
@Length(min=2, max=50, message="User name length range = 2-50")
private String name;
@Future(message=" ")
private Date createTime;
@NotEmpty(message="Customer ")
private List<Customer> customers;
@NotNull(message="Girl ")
private boolean girl;
private String[] cbx;
@NotNull(message="Age can NOT be Null")
@Min(value=18, message=" 18 ")
@Max(value=100, message=" 100 ")
private int age;
@Email(message="Email ")
private String email;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public List<Customer> getCustomers() {
return customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
public boolean isGirl() {
return girl;
}
public void setGirl(boolean girl) {
this.girl = girl;
}
public String[] getCbx() {
return cbx;
}
public void setCbx(String[] cbx) {
this.cbx = cbx;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
2、Controller
package com.my.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.my.controller.bean.Customer;
import com.my.controller.bean.User;
@Controller
@RequestMapping(value="/post")
public class TestPostController {
private static List<User> users = new ArrayList<User>();
{
//-----------------------------------------------
// Entity
// -----------------------------------------------
users.add(new User());
User user = users.get(0);
user.setId(1);
user.setName("Robin");
user.setCreateTime(new Date());
user.setGirl(true);
user.setCbx(new String[] {"1", "2", "3"});
user.setAge(18);
user.setEmail("[email protected]");
user.setCustomers(new ArrayList<Customer>());
Customer customer1 = new Customer();
customer1.setId(1);
customer1.setCompany("Company - 1");
customer1.setCreateTime(new Date());
customer1.setUser(user);
user.getCustomers().add(customer1);
Customer customer2 = new Customer();
customer2.setId(1);
customer2.setCompany("Company - 2");
customer2.setCreateTime(new Date());
customer2.setUser(user);
user.getCustomers().add(customer2);
}
@RequestMapping
public ModelAndView index() {
ModelAndView view = new ModelAndView("TestPost/index");
view.addObject("users", users);
return view;
}
@RequestMapping(value="/addUser", method=RequestMethod.POST)
public ModelAndView addUser(@ModelAttribute @Valid User user, BindingResult result) {
ModelAndView view = new ModelAndView("redirect:/post");
if(result.hasErrors()) {
List<FieldError> errors = result.getFieldErrors();
for(FieldError err : errors) {
System.out.println("ObjectName:" + err.getObjectName() + "\tFieldName:" + err.getField()
+ "\tFieldValue:" + err.getRejectedValue() + "\tMessage:" + err.getDefaultMessage());
}
view.addObject("users", users);
return view;
}
user.setId(users.size() + 1);
user.getCustomers().get(0).setId(1);
user.getCustomers().get(0).setUser(user);
users.add(user);
view.addObject("users", users);
return view;
}
}
3、View
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.my.controller.bean.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib prefix="st" uri="http://www.springframework.org/tags" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index</title>
</head>
<body>
<fmt:setLocale value="zh_cn" />
<form action="<st:url value="/post/addUser"></st:url>" method="post">
<c:forEach items="${users}" var="user">
User:${user.name}<br/>
Create time:<fmt:formatDate value="${user.createTime}"/><br/>
Is girl:
<c:choose>
<c:when test="${user.girl}">Yes</c:when>
<c:when test="${!user.girl}">No</c:when>
<c:otherwise>N/A</c:otherwise>
</c:choose>
<br/>
Checkboxs:
<c:forEach items="${user.cbx}" var="item">
${item},
</c:forEach>
<br/>
Age:${user.age}<br/>
E-mail:${user.email}<br/>
<hr/>
<table style="width:100%;border:1px solid #ccc;">
<thead>
<tr style="text-align:left; background-color:#eee;">
<th>Company name</th>
<th>User</th>
<th>Create time</th>
</tr>
</thead>
<tbody>
<c:forEach items="${user.customers}" var="item">
<tr>
<td>${item.company}</td>
<td>${item.user.name}</td>
<td><fmt:formatDate value="${item.createTime}" pattern="yyyy-MM-dd"/></td>
</tr>
</c:forEach>
</tbody>
</table>
<hr/>
</c:forEach>
User name:
<input type="text" name="name" id="name" /><br/>
Is girl:
<input type="radio" name="girl" id="isGirl" value="true" checked="checked" /><label for="isGirl">Yes</label>
<input type="radio" name="girl" id="noGirl" value="false" /><label for="noGirl">No</label><br/>
Checkboxs:
<input type="checkbox" name="cbx" id="cbx1" value="1" /><label for="cbx1">1</label>
<input type="checkbox" name="cbx" id="cbx2" value="2" /><label for="cbx2">2</label>
<input type="checkbox" name="cbx" id="cbx3" value="3" /><label for="cbx3">3</label>
<br/>
Age:<input type="text" name="age" id="age" /><br/>
E-mail:<input type="text" name="email" id="email" /><br/>
Create time:
<input type="text" name="createTime" id="createTime" /><br/>
Company:
<input type="text" name="customers[0].company" id="customers[0].company" /><br/>
<input type="submit" value="add" />
<sf:errors path="*"></sf:errors>
</form>
<hr/>
</body>
</html>
4.테스트 결과이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
springmvc application/octet-stream problemmistake: Source code: Solution: Summarize: application/octet-stream is the original binary stream method. If the convers...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.