ITEEDU

使用 PropertyEditor

对 于 BaseCommandController 及其子类别来说,它的 Command 物件并不一定要接受基本型态或 是 String 型态,您可以撰写一个实作 java.beans.PropertyEditor 的类别,在当中进行转换, 例如将接收到的字串转换为 User 类别的实例。

举个实例来说,假设您的 Command 物件如下设计:

•      SomeForm.java
package onlyfun.caterpillar;
public class SomeForm {
	private User user;
	public void setUser(User user) {
		this.user = user;
	}
	public User getUser() {
		return user;
	}
}

SomeForm 为网页表单的物件代表,而其中出现的 User 类别如下设计:

•      User.java
package onlyfun.caterpillar;
public class User {
	private String firstName;
	private String lastName;
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getFirstName() {
		return firstName;
	}
	public String getLastName() {
		return lastName;
	}
}

您的 Command 物件将接收一个自订型态的 User 实例,然而从 HTTP 接收到的参数值是 String 型 态,您可以撰写一个 UserPropertyEditor 类别做转换,通常直接继承 java.beans.PropertyEditorSupport 并重新定义它的 getAsText()及 setAsText()方法,例如:

•      UserPropertyEditor.java
package onlyfun.caterpillar;
import java.beans.PropertyEditorSupport;
public class UserPropertyEditor extends PropertyEditorSupport {
	public String getAsText() { 
		Object o = this.getValue();
		if(o == null || !(o instanceof User)) {
			return null;
		}
		User user = (User) o;
		String name = user.getFirstName()+ "," + user.getLastName();
		return name;
	}
	public void setAsText(String text) { 
		String[] tokens = text.split(",");
		User user = new User(); 
		user.setFirstName(tokens[0]); 
		user.setLastName(tokens[1]);
		setValue(user);
	}
}

当必须从指定的物件转换为字串时,会呼叫 getAsText()方法,而接收到参数要将之转换为指定 的物件时,会呼叫 setAsText()方法,接着来撰写一个测试的 Controller:

•      SomeFormController.java
package onlyfun.caterpillar;
import org.springframework.web.servlet. mvc.SimpleFormController;
import org.springframework.web.servlet.*;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web. bind.ServletRequestDataBinder;
public class SomeFormController extends SimpleFormController {
	public SomeFormController() {
		setCommandClass(SomeForm.class);
	}
	protected ModelAndView onSubmit( Object command)
				throws Exception {
		SomeForm form = (SomeForm) command;
		Map model = new HashMap();
		model.put("firstName", form.getUser().getFirstName());
		model.put("lastName", form.getUser().getLastName());
		return new ModelAndView(this.getSuccessView(), model);
	}
	protected void initBinder(HttpServletRequest request, 
			ServletRequestDataBinder binder)
			throws Exception {
		super.initBinder(request, binder);
		binder.registerCustomEditor(User.class, new UserPropertyEditor());
	}
}

注意到这边重新定义了 initBinder()方法,并在当中使用 ServletRequestDataBinder 的 registerCustomEditor()方法注册了自订的 PropertyEditor,来看看定义档的内容:

•      mvc-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<bean id="urlMapping" class="org.springframework.web.servlet.
		→ handler.SimpleUrlHandlerMapping">
		<property name="mappings">
			<props>
				<prop	key="/index.do">
					indexController
				</prop>
				<prop key="/someForm.do">
					someFormController
				</prop>
			</props>
		</property>
	</bean>
	<bean id="viewResolver"
		class="org.springframework.web.servlet.
		→ view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/jsp/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
	<bean id="indexController" class="org.springframework.web.servlet.
		→ mvc.ParameterizableViewController">
		<property name="viewName">
			<value>index</value>
		</property>
	</bean>
	<bean id="someFormController" class="onlyfun.caterpillar.SomeFormController">
		<property name="successView">
			<value>hello</value>
		</property>
	</bean>
</beans>

现在假设撰写有一个测试网页:

•      index.jsp
<%@page contentType="text/html"%>
<%@page?pageEncoding="UTF-8"%>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>Form</title>
	</head>
	<body>
		<form name="someForm"
			action="/PropertyEditorDemo/someForm.do" method="POST">
			 问题一 <input type="text" name="user"/><br>
			<input type="submit" value="Submit"/>
		</form>
	</body>
</html>

在输入栏位中,指定由 user 属性来接受输入,当资料送出后,会经由 PropertyEditor 的转换, 假设呈现处理结果的 hello.jsp 网页是如下撰写的:

•      hello.jsp
<%@page contentType="text/html"%>
<%@page?pageEncoding="UTF-8"%>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>User Info</title>
	</head>
	<body>
		<h1>${firstName} - ${lastName}</h1>
	</body>
</html>

如果您在 index.jsp 填入"Justin,Lin",则结果会显示"Justin-Lin"。