在上一篇中,提交的表单都是简单的 数据类型。如果提交的表单中有其他对象怎么办?比如日期。
写道
package com.spring.mvn.domain;
import java.util.Date;
public class Reservation {
private String courtName;
private Date date;
private int hour;
private Player player;
private SportType sportType;
public String getCourtName() {
return courtName;
}
public void setCourtName(String courtName) {
this.courtName = courtName;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
public SportType getSportType() {
return sportType;
}
public void setSportType(SportType sportType) {
this.sportType = sportType;
}
public Reservation(String courtName, Date date, int hour, Player player,
SportType sportType) {
super();
this.courtName = courtName;
this.date = date;
this.hour = hour;
this.player = player;
this.sportType = sportType;
}
public Reservation() {
super();
}
@Override
public String toString() {
return "Reservation [courtName=" + courtName + ", date=" + date
+ ", hour=" + hour + ", player=" + player + ", sportType="
+ sportType + "]";
}
}
import java.util.Date;
public class Reservation {
private String courtName;
private Date date;
private int hour;
private Player player;
private SportType sportType;
public String getCourtName() {
return courtName;
}
public void setCourtName(String courtName) {
this.courtName = courtName;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
public SportType getSportType() {
return sportType;
}
public void setSportType(SportType sportType) {
this.sportType = sportType;
}
public Reservation(String courtName, Date date, int hour, Player player,
SportType sportType) {
super();
this.courtName = courtName;
this.date = date;
this.hour = hour;
this.player = player;
this.sportType = sportType;
}
public Reservation() {
super();
}
@Override
public String toString() {
return "Reservation [courtName=" + courtName + ", date=" + date
+ ", hour=" + hour + ", player=" + player + ", sportType="
+ sportType + "]";
}
}
写道
package com.spring.mvn.domain;
public class Player {
private String name;
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Player(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
@Override
public String toString() {
return "Player [name=" + name + ", phone=" + phone + "]";
}
}
public class Player {
private String name;
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Player(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
@Override
public String toString() {
return "Player [name=" + name + ", phone=" + phone + "]";
}
}
写道
package com.spring.mvn.domain;
public class SportType {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SportType(int id, String name) {
super();
this.id = id;
this.name = name;
}
public SportType() {
}
@Override
public String toString() {
return "SportType [id=" + id + ", name=" + name + "]";
}
}
public class SportType {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SportType(int id, String name) {
super();
this.id = id;
this.name = name;
}
public SportType() {
}
@Override
public String toString() {
return "SportType [id=" + id + ", name=" + name + "]";
}
}
如果提交的表单是 reservation这个对象时应该如何将页面上的输入数据绑定到匹配的属性中呢?
写道
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Reservation Form</title>
<style type="text/css">
.error {
color: #ff0000;
font-weight: bold;
}
</style>
</head>
<body>
<form:form method="post" modelAttribute="reservation">
<table>
<tr>
<td>Court Name</td>
<td><form:input path="courtName" /></td>
<td><form:errors path="courtName" cssClass="error" /></td>
</tr>
<tr>
<td>Date</td>
<td><form:input path="date" /></td>
<td><form:errors path="date" cssClass="error" /></td>
</tr>
<tr>
<td>Hour</td>
<td><form:input path="hour" /></td>
<td><form:errors path="hour" /></td>
</tr>
<tr>
<td>Player Name</td>
<td><form:input path="player.name" /></td>
<td><form:errors path="player.name" cssClass="error" /></td>
</tr>
<tr>
<td>Player Phone</td>
<td><form:input path="player.phone" /></td>
</tr>
<tr>
<td>Sport Type</td>
<td><form:select path="sportType" items="${sportTypes}"
itemValue="id" itemLabel="name" /></td>
<td><form:errors path="sportType" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Reservation Form</title>
<style type="text/css">
.error {
color: #ff0000;
font-weight: bold;
}
</style>
</head>
<body>
<form:form method="post" modelAttribute="reservation">
<table>
<tr>
<td>Court Name</td>
<td><form:input path="courtName" /></td>
<td><form:errors path="courtName" cssClass="error" /></td>
</tr>
<tr>
<td>Date</td>
<td><form:input path="date" /></td>
<td><form:errors path="date" cssClass="error" /></td>
</tr>
<tr>
<td>Hour</td>
<td><form:input path="hour" /></td>
<td><form:errors path="hour" /></td>
</tr>
<tr>
<td>Player Name</td>
<td><form:input path="player.name" /></td>
<td><form:errors path="player.name" cssClass="error" /></td>
</tr>
<tr>
<td>Player Phone</td>
<td><form:input path="player.phone" /></td>
</tr>
<tr>
<td>Sport Type</td>
<td><form:select path="sportType" items="${sportTypes}"
itemValue="id" itemLabel="name" /></td>
<td><form:errors path="sportType" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
此时你会发下在页面上如如 2012-12-12 时,reservation.date=null.这应该如何解决?
这就需要使用到@InitBinder
写道
package com.spring.mvn.controller;
import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
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.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import com.spring.mvn.domain.Player;
import com.spring.mvn.domain.Reservation;
import com.spring.mvn.domain.SportType;
import com.spring.mvn.service.ReservationService;
import com.spring.mvn.validator.ReservationValidator;
@Controller
@RequestMapping("reservationForm")
@SessionAttributes("reservation")
public class ReservationFormController {
@Autowired
private ReservationService reservationService;
@Autowired
private ReservationValidator reservationValidator;
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, true));
binder.registerCustomEditor(SportType.class,
new PropertyEditorSupport() {
@Override
public void setAsText(String text)
throws IllegalArgumentException {
int sportTypeId = Integer.parseInt(text);
SportType sportType = reservationService
.getSportType(sportTypeId);
setValue(sportType);
}
});
}
@ModelAttribute("sportTypes")
public List<SportType> populateSportTypes() {
System.out.println("sportTypes");
return reservationService.getAllSportType();
}
@RequestMapping(method = RequestMethod.GET)
public String setupForm(Model model,
@RequestParam("username") String username) {
Reservation reservation = new Reservation();
reservation.setPlayer(new Player(username, null));
model.addAttribute("reservation", reservation);
return "reservationForm";
}
@RequestMapping(method = RequestMethod.POST)
public String submintForm(
@ModelAttribute("reservation") Reservation reservation,
BindingResult result, SessionStatus status, ModelMap model) {
reservationValidator.validate(reservation, result);
if (result.hasErrors()) {
model.addAttribute("reservation", reservation);
return "reservationForm";
}
reservationService.make(reservation);
return "reservationSuccess";
}
}
import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
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.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import com.spring.mvn.domain.Player;
import com.spring.mvn.domain.Reservation;
import com.spring.mvn.domain.SportType;
import com.spring.mvn.service.ReservationService;
import com.spring.mvn.validator.ReservationValidator;
@Controller
@RequestMapping("reservationForm")
@SessionAttributes("reservation")
public class ReservationFormController {
@Autowired
private ReservationService reservationService;
@Autowired
private ReservationValidator reservationValidator;
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, true));
binder.registerCustomEditor(SportType.class,
new PropertyEditorSupport() {
@Override
public void setAsText(String text)
throws IllegalArgumentException {
int sportTypeId = Integer.parseInt(text);
SportType sportType = reservationService
.getSportType(sportTypeId);
setValue(sportType);
}
});
}
@ModelAttribute("sportTypes")
public List<SportType> populateSportTypes() {
System.out.println("sportTypes");
return reservationService.getAllSportType();
}
@RequestMapping(method = RequestMethod.GET)
public String setupForm(Model model,
@RequestParam("username") String username) {
Reservation reservation = new Reservation();
reservation.setPlayer(new Player(username, null));
model.addAttribute("reservation", reservation);
return "reservationForm";
}
@RequestMapping(method = RequestMethod.POST)
public String submintForm(
@ModelAttribute("reservation") Reservation reservation,
BindingResult result, SessionStatus status, ModelMap model) {
reservationValidator.validate(reservation, result);
if (result.hasErrors()) {
model.addAttribute("reservation", reservation);
return "reservationForm";
}
reservationService.make(reservation);
return "reservationSuccess";
}
}
相关推荐
【Spring的Web MVC构架模式】是Spring框架中的核心组件之一,主要负责处理Web应用程序的模型、视图和控制器的交互。Spring MVC以其高度模块化和可配置性,为开发者提供了一种优雅的方式来构建Web应用。 1. **构架...
- Spring MVC中的模型通常由命令对象、表单对象以及任意的参考数据组成,这与WebWork的Action对象有所不同。WebWork将控制器、命令对象和表单数据合并到一个对象中。 - 视图解析是Spring MVC中的另一个关键部分,...
- **Struts**:与Struts相比,Spring MVC更强调控制器的独立性,不需要ActionForm基类,可以不依赖Web表单,提供更灵活的数据绑定和校验机制。 - **WebWork(现在称为Struts2)**:Spring MVC与WebWork的主要区别...
4. **数据绑定与校验**:Spring的数据绑定机制非常灵活,可以将输入验证错误与系统错误分开处理,减少了业务对象与表单对象之间的重复。可以直接绑定业务对象,无需额外的转换或接口,与Struts要求的ActionForm不同...
Spring的数据绑定机制非常灵活,可以处理应用范围内的校验错误,而不涉及系统级别的错误。这意味着业务对象和表单对象之间的转换更为直观,可以直接绑定业务对象,而无需复制字符串属性。这种设计减少了与Struts中的...
相较于Struts,Spring的Web MVC更注重控制器的可扩展性,不强制使用Action和ActionForm,而是允许通过命令或表单对象直接操作业务对象。与WebWork比较,Spring提供了更直接的对象绑定和更灵活的控制结构,允许更...
此外,Spring的数据绑定机制允许在应用范围内处理校验错误,而不仅仅是系统错误。 3. **与WebWork的比较**: 虽然WebWork和Spring都支持MVC模式,但它们在对象角色上有区别。Spring支持控制器、命令对象和模型的...
Spring的数据绑定机制非常灵活,可以处理校验错误,而无需在表单对象中复制业务对象的属性。此外,Spring支持命令对象或表单对象,这与Struts要求的Action和ActionForm接口不同。 3. **区别于Struts和WebWork** 与...
模型-视图-控制器(MVC)模式在Spring MVC中得到了很好的体现,控制器处理请求,命令或表单对象用于操作数据,然后将结果传递给视图呈现。 4. **命令对象和数据绑定** Spring MVC中的命令对象可以是任意对象,不...
本篇文章将深入探讨一个简单的表单提交实例,帮助开发者理解如何在Spring MVC环境中处理表单数据。 首先,我们来看User模型类,它是表单数据的载体。在Java中,我们可以使用注解来实现数据校验,这在`User`类中得到...
在Spring MVC框架中,处理前端批量传递的数据是常见的需求,特别是在大数据操作或者批量更新、删除等场景下。本文将详细讲解两种实用的方法来接收并处理这些数据。 **方法一:数组或集合参数** 1. **JSON数组传递*...
`@ModelAttribute`在表单绑定、数据校验和分页等场景中都有着广泛的应用。通过它,我们可以实现模型和视图之间的数据共享,简化了数据处理的流程,提高了代码的可读性和可维护性。 总的来说,`@ModelAttribute`是...
在处理表单数据方面,Struts 2提供了强大的表单标签库,简化了表单验证和数据绑定。书中会展示如何利用这些标签来构建用户界面,并配合Struts 2的验证框架进行服务器端的数据校验。 此外,书中的章节还将涵盖国际化...
- **Create(创建)**: 用户提交表单数据,Struts2 Action接收到请求后,将数据绑定到Java对象,然后通过Spring的依赖注入找到Service层的方法,Service再调用DAO的插入方法,由iBatis执行SQL插入操作。 - **Read...
总结一下,"Spring Study Action" 主要关注的是如何在Spring MVC框架中理解和使用类似`ActionForm`的概念。通过创建和利用`@ModelAttribute`注解的命令对象,我们可以高效地处理用户输入,实现模型与视图之间的数据...
7. **整合验证框架**:Spring与Hibernate Validator的集成可以提供前端表单验证和后端数据校验,确保数据的正确性。 8. **异常处理**:通过配置全局异常处理器,可以统一处理应用中的异常,提高代码的健壮性。 9. ...
- **JSON处理**:使用HttpMessageConverter接口(如MappingJackson2HttpMessageConverter)可以轻松处理JSON数据的序列化和反序列化。 - **JSON绑定**:SpringMVC支持直接将JSON数据绑定到Java对象上,简化了前后端...