I followed a tutorial to handle form submission in Spring. I wanted to populate my TaskEntity
bean with the form and have this bean's values available in my controller's taskSubmit
method. However, all of the properties of task
in this method are null when I fill out the form and hit submit. The relevant code is as follows:
TaskEntity.java
public class TaskEntity {
private String title;
private String description;
private Date dueDate;
private TaskPriority priority;
public void setTitle(String title)
{
this.title = title;
}
public String getTitle()
{
return this.title;
}
public void setDescription(String description)
{
this.description = description;
}
public String getDescription()
{
return this.description;
}
public void setDueDate(Date dueDate)
{
this.dueDate = dueDate;
}
public Date getDueDate()
{
return this.dueDate;
}
public void setPriority(String priority)
{
this.priority = TaskPriority.valueOf(priority);
}
public TaskPriority getPriority()
{
return this.priority;
}
}
addTask.jsp
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>To Do List - Add Task</title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/stylesheet.css">
</head>
<body>
<form action="tasks" th:action="@{/tasks}" th:object="${taskEntity}" method="post">
<p>Title: <input type="text" th:field="*{title}" /></p>
<p>Description: <input type="text" th:field="*{description}" /></p>
<p>Due Date: <input type="text" th:field="*{dueDate}" /></p>
<p>Priority: <input type="text" th:field="*{priority}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
TaskController.java
@Controller
public class TaskController {
private static final String TASKS = "/tasks";
private static final String ADD_TASK = "/addTask";
@Autowired
private TaskEntityDao taskEntityDao;
ObjectMapper mapper = new ObjectMapper();
@RequestMapping(value = TASKS, method = RequestMethod.GET)
public ModelAndView readTasks()
{
return new ModelAndView("tasks");
}
@RequestMapping(value = ADD_TASK, method = RequestMethod.GET)
public String addTask(Model model)
{
model.addAttribute("taskEntity", new TaskEntity());
return "addTask";
}
@RequestMapping(value = TASKS, method = RequestMethod.POST)
public void taskSubmit(@ModelAttribute TaskEntity task)
{
// Fields for 'task' are all null!
taskEntityDao.createTask(task);
readTasks();
}
}
I expected the TaskEntity
passed to the view with model.addAttribute("taskEntity", new TaskEntity());
was going to have the form values mapped to it's fields, but I must have missed something.
Update:
I am adding the view resolver code from my Spring config:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>