Oto form.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Student</title>
</head>
<body>
<form:form action="addStudent" commandName="addStudent" method="post">
<table>
<tr>
<td><form:label path="name">Name:</form:label></td> <td><form:input path="name"/></td>
</tr>
<tr>
<td><form:label path="email">Email:</form:label></td> <td><form:input path="email"/></td>
</tr>
<tr>
<td><form:label path="age">Age:</form:label></td> <td><form:input path="age"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"></td>
</tr>
</table>
</form:form>
</body>
</html>
Oto metoda kontrolera
@RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String addStudent(@ModelAttribute("addStudent") Student student) {
System.out.println("Saving Info...");
System.out.println("Name: "+student.getName());
System.out.println("Email: "+student.getEmail());
System.out.println("Age: "+student.getAge());
return "form";
}
Oto model studenta
public class Student {
private String name;
private String email;
private int age;
private int id;
public Student() {
super();
}
}
Wydaje mi się, że nie ma potrzeby korzystania z sieci.xml lub dispatcher-servlet.xml. Każda rzecz jest poprawnie powiązana, mam na myśli polecenie commandName w jsp. ModelAttribute jest poprawny w kontrolerze, więc dlaczego kontroler nie dociera do kontrolera? :(
Proszę pomóż. Zmarnowałem już na to pół dnia. PS: Jestem nowy w Spring i flowoverflow.
EDYTOWAĆ:
po sugestiach mój kod wygląda następująco:
metoda kontrolera:
public String addStudent(@ModelAttribute("student") Student student, BindingResult result) {
formularz jsp:
<form:form action="addStudent" commandName="student" method="post">
EDYTOWAĆ:
sam to rozwiązałem dodano tę metodę dla modelattibute
@ModelAttribute("student")
public Student getForm() {
return new Student();
}
Odpowiedzi:
0 dla odpowiedzi № 1Tak długo, jak ciąg CommandName i modelAttribute są takie same, jak w porządku.
podobnie jestem nowicjuszem w Spring i tak dalej ... ale zgaduję, że nie mogę znaleźć poprawnego mapowania żądań, ponieważ masz / addStudent w mapowaniu żądań i po prostu addStudent w akcji formularza. to dobrze, jeśli formularz jest w katalogu kontekstowym. mógłbyś to sprawdzić?
Dodaj również obiekt BindingResult do listy arg public String addStudent (@ModelAttribute („addStudent”) Student uczeń, wynik BindingResult)