【问题标题】:Neither BindingResult nor plain target object for bean既不是 BindingResult 也不是 bean 的普通目标对象
【发布时间】:2020-02-21 00:25:09
【问题描述】:

我尝试了很多很多组合 - 尝试使用 ModelAndView 并返回 mav 并尝试 model.addAttribute 并返回 String,并在 jsp 页面中编写 - 自动选择和 customerGet 并尝试 customerPost,但没有任何一种组合帮助我。

如何更正代码?我只需要一个 WORKING 示例来了解如何将代码从控制器发送到 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";
    //    }
        }

我的 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 找到页面 并在完成表单并选择按钮后再次出现错误 我自动重定向到页面 在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 base 时——我找到了我的实体——我有第二个问题 = 如何更正创建新客户——只有 getmethot 控制器或methot 中的新客户需要这样写?使用 hibernate-jpa - crud 存储库

   Customer customer = new Customer();
   User user = new User();
   Address address = new Address();
   customer.setAddress(address);
   customer.setUser(user);

【问题讨论】:

  • 当您尝试加载页面时会发生什么?您要访问哪个 URL?你在控制器中映射customer 方法的方式是/index/index,这就是你要打的吗?
  • ooo...我看到localhost:8081/index/index中的表格
  • 但我想在 localhost:8081/index 中看到它,添加对象后不要离开页面,页面必须重新加载
  • 在我完成后出现错误,把它放在我的主要帖子的末尾
  • 我再次遇到错误 - 在每个 url 中,例如 localhost:8081/index/index localhost:8081/index localhost:8081/index/addCustomer 有什么问题??????

标签: java spring-boot spring-mvc jsp model-view-controller


【解决方案1】:

当您期望视图中有一个对象但未将其添加到模型中时,会引发 BindingResult 错误。 (在您的情况下:“customerGet”) 对您的代码进行简短分析,您有:

<spring:form action="${addAction}" modelAttribute="customerGet">

=> 您必须在返回此视图的所有控制器方法中具有 model.addAttribute("customerGet", new Customer())。 返回索引视图分两种情况:

  1. GET /index/index => 在这里,一切顺利

  2. POST /index/addCustomer => 你没有这里有它,它会绑定结果失败。

【讨论】:

  • 但我需要这个吗?在get方法中
  • 客户 customer = new Customer();用户用户 = 新用户();地址地址=新地址();客户.setAddress(地址); customer.setUser(user);
  • 是的,您需要在 GET 和 POST 方法中都有 model.addAttribute("customerGet",.. )。由于双向关系,通常在视图中您永远不会直接返回实体。
  • 如果你有 user.email => 客户必须有一个非空的用户对象否则会失败,所以你必须添加一个非空用户的客户对象,地址对象。
  • 我看到了这段代码并尝试去做。我该怎么做? @RequestMapping(value = "/customer/registration") public ModelAndView getRegistrationForm() { Customer customer = new Customer();用户用户 = 新用户(); BillingAddress ba = new BillingAddress(); ShippingAddress sa = new ShippingAddress();客户.setShippingAddress(sa);客户.setBillingAddress(ba);客户.setUsers(用户); return new ModelAndView("register", "customer", customer); }
【解决方案2】:

您收到BindingResult 错误是因为您没有返回您放置在模型和视图中的CustomerGet 对象,只需返回字符串“index”您只是将用户发送到index.jsp 而没有填充表单的模型属性。您的客户方法需要从您的customer 方法返回一个ModelAndView 对象。如果您将 customer 方法更改为如下所示,它应该可以工作:

@RequestMapping(value = "/", method = RequestMethod.GET)
  public ModelAndView customer(Model model) {
    ModelAndView modelAndView = new ModelAndView("index");
    Customer customer = new Customer();
    customer.setAddress(new Address());
    customer.setUser(new User());
    model.addAttribute("customerGet", customer);

    return modelAndView;
}

这会创建一个ModelAndView 对象,指定“index”作为视图的jsp 页面,然后用用户和地址填充一个新的客户对象,并将其放在模型和视图上。要实际查看填充了值的 for,您显然必须在 Customer 对象的属性上为 firstName、lastName 等设置值。请注意,我将方法上的 @RequestMapping 更改为“/”,以便页面将可以在localhost:8081/index 而不是localhost:8081/index/index 获得。

【讨论】:

    猜你喜欢
    • 2020-11-16
    • 1970-01-01
    • 2013-05-23
    • 2016-07-22
    • 1970-01-01
    • 2014-04-05
    • 2016-07-18
    • 2020-08-27
    • 1970-01-01
    相关资源
    最近更新 更多