如果您提供Person
参考,Department
那将很容易。在您的应用程序中,如果此人在某个部门工作,那么Has-A
在您的 Person 类中创建这样的关系是合乎逻辑的:
@Component
@Scope("prototype")
public class Person {
private String firstName;
private Department department;
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
您可以创建一个从 Context 获取Person
bean 并呈现视图的控制器。
@Controller
public class TestController implements ApplicationContextAware{
private ApplicationContext appContext;
@RequestMapping(value="/handleGet",method=RequestMethod.GET)
public String handleGet(ModelMap map){
map.addAttribute("person", appContext.getBean("person"));
return "test";
}
@RequestMapping(value="/handlePost",method=RequestMethod.POST)
public @ResponseBody String handlePost(@ModelAttribute("person") Person person){
return person.getDepartment().getDepartmentName();
}
@Override
public void setApplicationContext(ApplicationContext appContext)
throws BeansException {
this.appContext=appContext;
}
}
然后在您的 JSP 视图中,您可以编写如下内容:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!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=ISO-8859-1">
<title>Test</title>
</head>
<body>
<sf:form commandName="person" action="/appname/handlePost.html" method="post">
<sf:input path="firstName"/>
<sf:input path="department.departmentName"/>
<sf:button name="Submit">Submit</sf:button>
</sf:form>
</body>
</html>