Chcę utworzyć witrynę internetową, która wyświetla formularz. Pola formularza zależą od parametru żądania (a także od komponentu bean formularza). To jest mój kontroler, który powoduje, że różne formy:Jak wysłać ogólne obiekty do kontrolera Spring?
@Controller
public class TestController {
@Autowired
private MyBeanRegistry registry;
@RequestMapping("/add/{name}")
public String showForm(@PathVariable String name, Model model) {
model.addAttribute("name", name);
model.addAttribute("bean", registry.lookup(name));
return "add";
}
}
Odpowiedni widok wygląda następująco:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<form method="post" th:action="@{|/add/${name}|}" th:object="${bean}">
<th:block th:replace="|${name}::fields|"></th:block>
<button type="submit">Submit</button>
</form>
</body>
</html>
Poniżej przykładowy fragment, który wyświetla pól formularza:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<th:block th:fragment="fields">
<label for="firstName">First name</label><br />
<input type="text" id="firstName" th:field="*{firstName}" /><br />
<label for="lastName">Last name</label><br />
<input type="text" id="lastName" th:field="*{lastName}" />
</th:block>
</body>
</html>
Podlegająca fasola wyglądałaby tak:
public class MyExampleBean {
private String firstName;
private String lastName;
// Getters & setters
}
Formularz jest renderowany poprawnie, ale jak mogę otrzymać formularz z powrotem w kontrolerze? A jak mogę sprawdzić poprawność przesłanego komponentu? Próbowałem następującą metodę, ale oczywiście nie może pracować:
@RequestMapping(value = "/add/{name}", method = RequestMethod.POST)
public String processForm(@PathVariable String name, @Valid Object bean) {
System.out.println(bean);
return "redirect:/add/" + name;
}
Wiosna tworzy nową instancję Object
ale przedstawione wartości są tracone. Jak mogę wykonać to zadanie?
To wygląda na problem zakresu, istnieje parametr powiedzieć chcesz zakresu sesji dla tej postaci? –
Nie ustawiłem zakresu na formularzu. – stevecross