如何修复" java.lang.IllegalStateException:无论BindingResult也不是为bean名称“客户”可以作为请求属性平原目标对象"? [英] How to fix "java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'customer' available as request attribute"?

查看:206
本文介绍了如何修复" java.lang.IllegalStateException:无论BindingResult也不是为bean名称“客户”可以作为请求属性平原目标对象"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用Spring验证用的注解,我不断遇到相同的异常:

  java.lang.IllegalStateException:无论BindingResult也不是为bean名称客户可以作为请求属性平原目标对象
在org.springframework.web.servlet.support.BindStatus<&初始化GT;(BindStatus.java:141)
在org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:178)
在org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:198)
在org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
在org.springframework.web.servlet.tags.form.LabelTag.resolveFor​​(LabelTag.java:119)
截断。查看日志完整堆栈跟踪文件

我已经看了几个教程和双重检查一切我能想到的。我不知道在哪里我的问题。唯一的例外发生任何时候,网页被加载。任何帮助将是AP preciated。

弹簧MVC-servlet.xml中

 <?XML版本=1.0编码=UTF-8&GT?;
<豆的xmlns =htt​​p://www.springframework.org/schema/beans
        的xmlns:AOP =htt​​p://www.springframework.org/schema/aop的xmlns:上下文=htt​​p://www.springframework.org/schema/context
        的xmlns:JEE =htt​​p://www.springframework.org/schema/jee的xmlns:TX =htt​​p://www.springframework.org/schema/tx
        XMLNS:XSI =htt​​p://www.w3.org/2001/XMLSchema-instance
        的xmlns:MVC =htt​​p://www.springframework.org/schema/mvc
        XSI:的schemaLocation =htt​​p://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema /豆http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/弹簧上下文3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org /模式/ TX http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/ MVC /弹簧MVC-3.0.xsd>
    <背景:组件扫描基包=控制器/>
    < MVC:注解驱动/>
    < bean类=org.springframework.web.servlet.view.InternalResourceViewResolver>        <属性值=/NAME =preFIX>< /性>
    < /豆>
< /豆>

addCustomer.jsp

 <%@页语言=Java的的contentType =text / html的;字符集= ISO-8859-1
    的pageEncoding =ISO-8859-1%GT;
<%@标签库的URI =htt​​p://www.springframework.org/tags/formpreFIX =形式%GT;
!< D​​OCTYPE HTML PUBLIC - // W3C // DTD HTML 4.01过渡// ENhttp://www.w3.org/TR/html4/loose.dtd\">
< HTML和GT;
< HEAD>
< META HTTP-EQUIV =Content-Type的CONTENT =text / html的;字符集= ISO-8859-1>
<标题>添加客户< /标题>< /头>
<身体GT;
<形式:形式行动=addCustForm方法=POST的CommandName =客户的ModelAttribute =客户>
    <表边框=2>
        < TR>< TD><形式:标签路径=FNAME>用户至上名称:LT; /表:标签>< / TD>< TD><形式:输入路径=FNAME ID =FNAME/><形式:错误路径=FNAME的CssClass =错误/> < / TD>< / TR>
        < TR>< TD><形式:标签路径=lname的>客户姓氏:其中; /表:标签>< / TD>< TD><形式:输入路径=LNAME ID =LNAME/><形式:错误路径=L-NAME的CssClass =错误/> < / TD>< / TR>
        < TR>< TD><形式:标签路径=手机>客户电话号码:其中; /表:标签>< / TD>< TD><形式:输入路径=手机 ID =手机/><形式:错误路径=手机的CssClass =错误/> < / TD>< / TR>
        < TR>< TD><形式:标签路径=地址>客户地址:< /表:标签>< / TD>< TD><形式:输入路径=地址ID =地址/><形式:错误路径=地址的CssClass =错误/> < / TD>< / TR>
        < TR>< TD><形式:标签路径=电子邮件>客户的电子邮件:LT; /表:标签>< / TD>< TD><形式:输入路径=电子邮件ID =电子邮件/><形式:错误路径=电子邮件的CssClass =错误/> < / TD>< / TR>
    < /表>
    <输入类型=提交值=提交客户信息/>
< / form:表单>
< /身体GT;
< / HTML>

AddCustomerController.java

 封装控制器;进口javax.servlet.http.HttpServletRequest;
进口javax.validation.Valid;进口org.springframework.stereotype.Controller;
进口org.springframework.ui.ModelMap;
进口org.springframework.validation.BindingResult;
进口org.springframework.web.bind.annotation.RequestMapping;
进口org.springframework.web.bind.annotation.RequestMethod;进口dao.Customer;@Controller
@RequestMapping(/ addCustForm)
公共类AddCustomerController {    @RequestMapping(方法= RequestMethod.POST)
    公共字符串addCustomer(@Valid客户的客户,BindingResult结果,ModelMap地图,HttpServletRequest的要求)抛出异常{
        如果(result.hasErrors()){
            返回addCustomer.jsp
        }        map.addAttribute(消息,customer.getFname());
        返回Menu.jsp
    }
}

Customer.java

 包道;进口javax.persistence.Column;
进口javax.persistence.Entity;
进口javax.persistence.GeneratedValue;
进口javax.persistence.GenerationType;
进口javax.persistence.Id;
进口javax.validation.constraints.NotNull;
进口javax.validation.constraints.Pattern;
进口javax.validation.constraints.Size;
进口javax.xml.ws.BindingType;进口org.hibernate.validator.constraints.Email;
进口org.hibernate.validator.constraints.NotEmpty;
进口org.springframework.stereotype.Component;@零件
@实体
公共类客户{
    @ID
    @GeneratedValue(策略= GenerationType.AUTO)
    INT CUSTID;
    @柱
    @NotEmpty / *(消息=第一名称是必需)* /
    / * @模式(正则表达式={A-ZA-Z}消息=第一名称必须全部字母)* /
    串FNAME;
    @NotEmpty / *(消息=姓氏为必填)* /
    / * @模式(正则表达式={A-ZA-Z}消息=姓氏必须全部字母)* /
    字符串LNAME;
    @NotEmpty / *(消息=地址是必需)* /
    / * @模式(正则表达式={A-ZA-Z0-9}消息=地址必须是只包含字母和数字)* /
    字符串的地址;
    @NotEmpty / *(消息=电子邮件是必填)* /
    / * @电子邮件(消息=无效的电子邮件地址)* /
    字符串电子邮件;
    @NotEmpty / *(消息=电话号码是必填)* /
    / * @尺寸(分= 10,最大= 10)
    @Pattern(正则表达式={} 0-9,邮件=电话号码必须是所有的数字(不' - 或()')* /
    手机串;// getter和setter

的web.xml

 <?XML版本=1.0编码=UTF-8&GT?;
< web应用程序的xmlns:XSI =htt​​p://www.w3.org/2001/XMLSchema-instance的xmlns:网络=htt​​p://xmlns.jcp.org/xml/ns/javaeeXSI:的schemaLocation =htt​​p://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd\">  <显示-名称>库存管理 - 系统和LT; /显示-名称>  <欢迎-文件列表>
    <欢迎-文件>&Menu.jsp LT; /欢迎-文件>
  < /欢迎-文件列表>  <的context-param>
    <参数-名称>&contextConfigLocation的LT; /参数 - 名称>
    &LT;参数值&GT; /WEB-INF/spring-mvc-servlet.xml< /参数值&GT;
  &LT; /的context-param&GT;  &LT;听者GT;
    &LT;监听级&GT; org.springframework.web.context.ContextLoaderListener&LT; /监听级&GT;
  &LT; /听者GT;  &LT;&servlet的GT;
    &LT; servlet的名称&gt;弹簧MVC&LT; / servlet的名称&gt;
    &LT;的servlet类&GT; org.springframework.web.servlet.DispatcherServlet&LT; / servlet的类&GT;
  &LT; / servlet的&GT;   &LT; Servlet映射&GT;
        &LT; servlet的名称&gt;弹簧MVC&LT; / servlet的名称&gt;
        &LT; URL模式&GT; /&LT; / URL模式&GT;
   &LT; / Servlet映射&GT;&LT; / web-app的&GT;


解决方案

从你的意见,好像您发送您最初的要求

 本地主机:7001 / InventoryManagementProject / addCustomer.jsp

我要承担这意味着JSP中的问题是在生成的WAR的根。因此,您可以直接访问它,而无需通过弹簧 @Controller 去。 然而,这是问题。

您的JSP中包含

 &LT;形式:形式行动=addCustForm方法=POST的CommandName =客户的ModelAttribute =客户&GT;

&LT;形式:形式&GT; 距离Spring 格式标签库的标签。当它被处理时,它会查找名为请求属性无论是在的CommandName 的ModelAttribute (注意,同时指定特定是多余的,只使用其中的一个)。在这种情况下,它会寻找客户命名一个请求属性,但是由于您没有设置这样的请求属性,处理这个标签会失败。

一个解决办法,就是必须通过 @Controller 处理方法渲染JSP之前,你的要求去。首先,将你的JSP到 WEB-INF中并解决您的使用InternalResourceViewResolver 有一个相应的 preFIX 后缀。然后添加一个处理像

  @RequestMapping(值=/添加客户,方法= RequestMethod.GET)
公共字符串getAddCustomerForm(型号模型){
    model.addAttribute(客户,新客户());
    返回addCustomer
}

这样做是添加一个新的客户模型对象属性(它最终会被添加为请求属性),因此它可以作为一个模板,在创建形式。

I'm trying to use Spring Validation with annotations and i keep encountering the same exception:

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'customer' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:178)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:198)
at org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:129)
at org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:119)
Truncated. see log file for complete stacktrace

I've looked at several tutorials and double checked everything i can think of to. I'm not sure where my problem is. The exception happens anytime the webpage is loaded. Any help would be appreciated.

spring-mvc-servlet.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
        xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd   http://www.springframework.org/schema/jee  http://www.springframework.org/schema/jee/spring-jee-3.0.xsd   http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  http://www.springframework.org/schema/mvc  http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">


    <context:component-scan base-package="controllers"/>


    <mvc:annotation-driven/>


    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <property value="/" name="prefix"></property>
    </bean>
</beans>

addCustomer.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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Customer</title>

</head>
<body>
<form:form action="addCustForm"  method="POST" commandName="customer" modelAttribute="customer">
    <table border="2">
        <tr><td><form:label path="fname">Customer First Name: </form:label></td><td><form:input path="fname" id="fname"/><form:errors path="fname" cssClass="error"/> </td></tr>
        <tr><td><form:label path="lname">Customer Last Name: </form:label></td><td><form:input path="lname" id="lname"/><form:errors path="lname" cssClass="error"/> </td></tr>
        <tr><td><form:label path="phone">Customer Phone Number: </form:label></td><td><form:input path="phone" id="phone"/><form:errors path="phone" cssClass="error"/> </td></tr>
        <tr><td><form:label path="address">Customer Address: </form:label></td><td><form:input path="address" id="address"/><form:errors path="address" cssClass="error"/> </td></tr>
        <tr><td><form:label path="email">Customer E-Mail: </form:label></td><td><form:input path="email" id="email"/><form:errors path="email" cssClass="error"/> </td></tr>
    </table>
    <input type="submit" value="Submit Customer Info"/>
</form:form>
</body>
</html>

AddCustomerController.java

package controllers;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import dao.Customer;

@Controller
@RequestMapping("/addCustForm")
public class AddCustomerController {



    @RequestMapping(method=RequestMethod.POST)
    public String addCustomer(@Valid Customer customer, BindingResult result, ModelMap map, HttpServletRequest request) throws Exception{
        if(result.hasErrors()){
            return "addCustomer.jsp";
        }

        map.addAttribute("message",customer.getFname());
        return "Menu.jsp";
    }
}

Customer.java

package dao;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import javax.xml.ws.BindingType;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.stereotype.Component;

@Component
@Entity
public class Customer {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    int custid;
    @Column
    @NotEmpty/*(message="First Name Is Required")*/
    /*@Pattern(regexp="{a-zA-Z}", message="First Name must be all letters")*/
    String fname;
    @NotEmpty/*(message="Last Name Is Required")*/
    /*@Pattern(regexp="{a-zA-Z}", message="Last Name must be all letters")*/
    String lname;
    @NotEmpty/*(message="Address Is Required")*/
    /*@Pattern(regexp="{a-zA-Z0-9}", message="Address must be contain only letters and numbers")*/
    String address;
    @NotEmpty/*(message="Email is Required")*/
    /*@Email(message="Invalid Email Address")*/
    String email;
    @NotEmpty/*(message="Phone Number is Required")*/
    /*@Size(min=10,max=10)
    @Pattern(regexp="{0-9}", message="Phone Number must be all Numbers(no '- or ()'")*/
    String phone;

//Getters and Setters

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

  <display-name>Inventory-Management-System</display-name>

  <welcome-file-list>
    <welcome-file>Menu.jsp</welcome-file>
  </welcome-file-list>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-mvc-servlet.xml</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <servlet>
    <servlet-name >spring-mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>

   <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>/</url-pattern>
   </servlet-mapping>



</web-app>

解决方案

From you comments, it seems like you are sending your initial request to

localhost:7001/InventoryManagementProject/addCustomer.jsp

I'm going to assume this means that the JSP in question is at the root of the generated WAR. You can therefore access it directly without going through a Spring @Controller. That, however, is the issue.

Your JSP contains

 <form:form action="addCustForm"  method="POST" commandName="customer" modelAttribute="customer">

<form:form> is a tag from the Spring form tag library. When it is processed, it looks for request attribute named whatever is specified in the commandName or modelAttribute (note that specifying both is redundant, use only one of those). In this case, it will look for a request attribute named customer, but since you haven't set such a request attribute, processing this tag will fail.

One solution, is to have your request go through a @Controller handler method before rendering the JSP. First, move your JSP to within WEB-INF and fix your InternalResourceViewResolver to have an appropriate prefix and suffix. Then add a handler like

@RequestMapping(value = "/add-customer", method = RequestMethod.GET)
public String getAddCustomerForm(Model model) {
    model.addAttribute("customer", new Customer());
    return "addCustomer";
}

What this does is add a new Customer object in the model attributes (which end up being added as request attributes) so that it serves as a template while creating the form.

这篇关于如何修复&QUOT; java.lang.IllegalStateException:无论BindingResult也不是为bean名称“客户”可以作为请求属性平原目标对象&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆