【发布时间】:2018-02-17 16:01:33
【问题描述】:
我正在开发一个 Spring MVC 项目,我正在从 UI 表单中获取一些数据。我有一个包含私有成员的 DTO 类。当我提交表单数据时,由于@RequestMapping 注释,FrontController(Dispatcher Servlet) 会调用 Controller 类的方法。在此方法中,我将 DTO 类的引用作为参数传递,并通过调用 getter 方法在控制台上打印 DTO 类的成员变量的值。
但我不明白 DTO 类的对象是如何自动创建的,并且表单数据是如何绑定到 DTO 类的成员变量的。请告诉我它是如何工作的?
控制器类
package com.soni.web.controller;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.soni.web.dto.StudentRecordsDTO;
@Component
@RequestMapping("/")
public class StudentRecords {
public StudentRecords() {
System.out.println(getClass().getName());
}
@RequestMapping(value="/signup", method = RequestMethod.POST)
public String signup(StudentRecordsDTO studentRecordsDTO) {
System.out.println(studentRecordsDTO.getId());
System.out.println(studentRecordsDTO.getName());
return "/registration_success.html";
}
}
DTO 类
package com.soni.web.dto;
public class StudentRecordsDTO {
private int id;
private String name;
public StudentRecordsDTO(int id, String name) {
this.id = id;
this.name = 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;
}
}
HTML 表单
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="signup" method ="post">
<input type = "num" name="id">
<input type = "text" name="name">
<input type = "password" name="pwd">
<input type = "num" name = "nm">
<input type = "submit" value="press">
</form>
</body>
</html>
【问题讨论】:
标签: spring spring-mvc