Я пробовал много комбинаций много и больше, чем многие - попробуйте использовать ModelAndView и вернуть mav, попробуйте model.addAttribute и вернуть String, и напишите на странице jsp - автоматический выбор и customerGet и попробуйте customerPost, но ни одна комбинация не поможетя вообще.
Как я могу исправить код? Мне нужен только один РАБОЧИЙ пример, чтобы понять, как отправить код из контроллера в jsp, я не могу найти ни одного работающего примера об этом - потому что они не работают с моим mvc + jsp
@Getter
@Setter
@Entity
@Table(name = "customer")
@NoArgsConstructor
@EqualsAndHashCode
public class Customer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "address_id")
private Address address;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "user_id")
private User user;
@Getter
@Setter
@Entity
@Table(name = "address")
@NoArgsConstructor
@EqualsAndHashCode
public class Address implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String country;
private String city;
private String street;
private String flat;
@OneToOne(mappedBy = "address")
private Customer customer;
@Getter
@Setter
@Entity
@Table(name = "users")
@NoArgsConstructor
@EqualsAndHashCode(of = "email")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String email;
private String password;
private boolean enable;
@OneToOne(mappedBy = "user")
private Customer customer;
мой плохой код
@Controller
@RequestMapping(value = "index")
public class HomeController {
@Autowired
private CustomerService customerService;
// @RequestMapping(method = RequestMethod.GET)
// public ModelAndView getRegistrationForm() {
// Customer customer = new Customer();
// User user = new User();
// Address address = new Address();
// customer.setAddress(address);
// customer.setUser(user);
// ModelAndView modelAndView = new ModelAndView();
// modelAndView.addObject("customer", customer);
//// model.addAttribute("customer", new Customer());
// modelAndView.setViewName("customer");
// return modelAndView;
//// return new ModelAndView("register", "customer", customer);
//// return "index";
// }
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String customer(Model model) {
// ModelAndView modelAndView = new ModelAndView();
// Customer customer = new Customer();
// User user = new User();
// Address address = new Address();
// customer.setAddress(address);
// customer.setUser(user);
// model.addAttribute(user);
// model.addAttribute(address);
// model.addAttribute("customer", customer);
model.addAttribute("customerGet", new Customer());
return "index";
}
// return new ModelAndView("customer", "command", customer);
// }
@RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
public String registerCustomer(@Valid @ModelAttribute(value = "customerPost") Customer customer, Model model,
BindingResult result) {
if (result.hasErrors())
return "index";
customerService.createCustomer(customer);
model.addAttribute("registrationSuccess", "Registered Successfully.");
return "index";
}
// @RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
// public String registerCustomer
// (@ModelAttribute("customer") Customer customer, Model model,
// BindingResult result) {
// if (result.hasErrors()) return "register";
// customerService.createCustomer(customer);
// model.addAttribute("registrationSuccess", "Registered Successfully.");
// return "redirect:/index";
// }
// @RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
// public String addStudent(@ModelAttribute("customer")Customer customer,
// ModelMap model) {
// model.addAttribute("firstName", customer.getFirstName());
// model.addAttribute("lastName", customer.getLastName());
// model.addAttribute("country", customer.getAddress().getCountry());
// model.addAttribute("city", customer.getAddress().getCity());
// model.addAttribute("street", customer.getAddress().getStreet());
// model.addAttribute("flat", customer.getAddress().getFlat());
// model.addAttribute("email", customer.getUser().getEmail());
// model.addAttribute("password", customer.getUser().getPassword());
// customerService.createCustomer(customer);
// return "index";
// }
}
my application.properties spring-boot
spring.mvc.view.prefix = / WEB-INF / pages / spring.mvc.view.suffix = .jsp
mybad jsp
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
<c:url var="addAction" value="/index/addCustomer" ></c:url>
<spring:form action="${addAction}" modelAttribute="customerGet">
<table>
<thead>
<tr>
<th>Create Student</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<%-- <spring:input path="id" readonly="true" size="8" disabled="true" />--%>
<spring:hidden path="id" />
</td>
</tr>
<tr>
<td>first name</td>
<td><spring:input path="firstName"/></td>
</tr>
<tr>
<td>last name</td>
<td><spring:input path="lastName"/></td>
</tr>
<tr>
<td>country</td>
<td><spring:input path="address.country"/></td>
</tr>
<tr>
<td>city</td>
<td><spring:input path="address.city"/></td>
</tr>
<tr>
<td>street</td>
<td><spring:input path="address.street"/></td>
</tr>
<tr>
<td>flat</td>
<td><spring:input path="address.flat"/></td>
</tr>
<tr>
<td>email</td>
<td><spring:input path="user.email"/></td>
</tr>
<tr>
<td>password</td>
<td><spring:input path="user.password"/></td>
</tr>
</tbody>
</table>
<spring:button>add customer</spring:button>
</spring:form>
</body>
</html>
я нахожу страницу в http://localhost:8081/index/index и снова имею ошибку после полной формы и нажимаю кнопку i, я автоматически перенаправляю на страницу в http://localhost:8081/index/addCustomer
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Oct 24 16:14:59 UTC 2019
There was an unexpected error (type=Internal Server Error, status=500).
Neither BindingResult nor plain target object for bean name 'customerGet' available as request attribute
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'customerGet' available as request attribute
такжекогда я вижу базу mysql - я нахожу свою сущность - и у меня возникает второй вопрос = как исправить создание нового клиента - только нового в get gett controller или в method нужно написать так эту строку? использовать hibernate-jpa - хранилище crud
Customer customer = new Customer();
User user = new User();
Address address = new Address();
customer.setAddress(address);
customer.setUser(user);