If you give Person
a reference of Department
then it will be easy. In your app, if the person works in a department it will be logical to create a Has-A
relationship in your Person class like this:
@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;
}
}
You can create a Controller that gets a Person
bean from the Context and renders a view.
@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;
}
}
Then inside your JSP view you can write something like this:
<%@ 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>