【问题标题】:Java Spring - IllegalStateException when retrieving data from jsp formJava Spring - 从jsp表单中检索数据时出现IllegalStateException
【发布时间】:2016-06-30 18:23:18
【问题描述】:

我在 Maven Web 应用程序方面遇到了一个非常令人讨厌和令人沮丧的问题,这让我在一段时间内停滞不前。 显然,从我之前的谷歌搜索来看,这是一个常见的 Spring MVC 错误,但我无法在互联网上提供的解决方案中找到我需要的解决方案。请注意,我是 Spring 和 MVC 概念的初学者。

我有一个 Web 应用程序,它应该用于管理建筑管理(居民、租金计算等)。我使用 Spring MVC、Hibernate、Java 1.8、Tomcat 8 服务器容器和 SQL Server 2014。 首先,这是我给正在建设的居民的POJO,一种叫做Inhabitant:

@Entity
@Table (name = "INHABITANT")
public class Inhabitant {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "ID")
    private long id;

    @Column(name = "FIRSTNAME")
    private String firstName;

    @Column(name = "LASTNAME")
    private String lastName;

    @Column(name = "APARTAMENT_NUMBER")
    private String apartamentNumber;

    @Column(name = "APARTAMENT_OWNER")
    private String apartamentOwner;

    @Column(name = "TELEPHONE_NUMBER")
    private String telephoneNumber;

    @Column(name = "EMAIL_ADDRESS")
    private String emailAddress;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getApartamentNumber() {
        return apartamentNumber;
    }

    public void setApartamentNumber(String apartamentNumber) {
        this.apartamentNumber = apartamentNumber;
    }

    public String getApartamentOwner() {
        return apartamentOwner;
    }

    public void setApartamentOwner(String apartamentOwner) {
        this.apartamentOwner = apartamentOwner;
    }

    public String getTelephoneNumber() {
        return telephoneNumber;
    }

    public void setTelephoneNumber(String telephoneNumber) {
        this.telephoneNumber = telephoneNumber;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }
}

这是我的 dispatcher-servlet.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
   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.xsd">

    <context:component-scan base-package="laura.bachelordegree.controller" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

这是我的 web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"> <!-- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 
        version="3.1" -->
    <display-name>BuildingAdministration</display-name>
    <welcome-file-list>
        <welcome-file>login/index.jsp</welcome-file>
    </welcome-file-list>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
</web-app>

这是我的jsp注册表,应该映射到Inhabitant对象:

<!DOCTYPE html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@page session="false" %>
<html>
<head>
    <meta charset="utf-8" />
    <title>Registration</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="stylesheet" type="text/css" href="login/bootstrap/css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="login/font-awesome/css/font-awesome.min.css" />

    <script type="text/javascript" src="login/js/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="login/bootstrap/js/bootstrap.min.js"></script>
</head>
<body> 

<!-- Registration form - START -->
<div class="container">
    <div class="row">
       <%--  <form role="form"> --%>
        <form:form method="post" modelAttribute="inhabitant" role="form" action="BuildingAdministration/src/main/webapp/login/result">
            <div class="col-lg-6">
                <div class="well well-sm"><strong><span class="glyphicon glyphicon-asterisk"></span>Required Field</strong></div>
               <div class="form-group">
                    <label for="InputFirstName">Enter First Name</label>
                    <div class="input-group">
                        <form:input path="firstName" type="text" cssClass="form-control" id="InputFirstName" />
                        <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
                    </div>
                </div> 
                <div class="form-group">
                    <label for="InputLastName">Enter Last Name</label>
                    <div class="input-group">
                        <form:input path="lastName" type="text" cssClass="form-control" id="InputLastName" />
                        <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
                    </div>
                </div>
                <div class="form-group">
                    <label for="InputApartmentNumber">Enter Apartment Number</label>
                    <div class="input-group">
                        <form:input path="apartmentNumber" type="text" cssClass="form-control" id="InputApartmentNumber" />
                        <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
                    </div>
                </div>
                <div class="form-group">
                    <label for="InputApartmentOwner">Enter Apartment Owner</label>
                    <div class="input-group">
                        <form:input path="apartmentOwner" type="text" cssClass="form-control" id="InputApartmentOwner" />
                        <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
                    </div>
                </div>
                <div class="form-group">
                    <label for="InputTelephoneNumber">Enter Telephone Number</label>
                    <div class="input-group">
                        <form:input path="telephoneNumber" type="text" cssClass="form-control" id="InputTelephoneNumber" />
                        <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
                    </div>
                </div>
                <div class="form-group">
                    <label for="InputEmail">Enter Email</label>
                    <div class="input-group">
                        <form:input path="emailAddress" type="email" cssClass="form-control" id="InputEmailFirst" />
                        <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
                    </div>
                </div>
                <div class="form-group">
                    <label for="InputEmail">Confirm Email</label>
                    <div class="input-group">
                        <form:input path="emailAddress" type="email" cssClass="form-control" id="InputEmailSecond" />
                        <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>
                    </div>
                </div>
                <input type="submit" name="submit" id="submit" value="Submit" class="btn btn-info pull-right">
            </div>
          </form:form>
        <%-- </form> --%>
        <div class="col-lg-5 col-md-push-1">
            <div class="col-md-12">
                <div class="alert alert-success">
                    <strong><span class="glyphicon glyphicon-ok"></span> Success! Message sent.</strong>
                </div>
                <div class="alert alert-danger">
                    <span class="glyphicon glyphicon-remove"></span><strong> Error! Please check all page inputs.</strong>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Registration form - END -->

</body>
</html>

最后是控制器类,它应该有效地将 jsp 表单中的数据与 java 实体 Inhabitant 进行映射:

@RequestMapping(value = "/index", method = RequestMethod.GET)
public String loadInhabitant(@ModelAttribute("inhabitant")Inhabitant inhabitant, 
           ModelMap model) {
      model.addAttribute("firstName", inhabitant.getFirstName());
      model.addAttribute("lastName", inhabitant.getLastName());
      model.addAttribute("apartmentNumber", inhabitant.getApartamentNumber());
      model.addAttribute("apartmentOwner", inhabitant.getApartamentOwner());
      model.addAttribute("apartmentNumber", inhabitant.getApartamentNumber());
      model.addAttribute("telephoneNumber", inhabitant.getTelephoneNumber());
      model.addAttribute("emailAddress", inhabitant.getEmailAddress());
    return "result";
}

现在,这是我尝试在服务器上运行我的应用程序时遇到的错误:

消息 java.lang.IllegalStateException: Bean 名称“inhabitant”的 BindingResult 和普通目标对象都不能用作请求属性

描述服务器遇到了一个内部错误,导致它无法完成这个请求。

异常 org.apache.jasper.JasperException: java.lang.IllegalStateException:既不是 BindingResult 也不是普通的 可根据要求提供 bean 名称“inhabitant”的目标对象 属性 org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:555) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:471) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

根本原因 java.lang.IllegalStateException:既不是 BindingResult 也不是 bean 名称“inhabitant”的普通目标对象可根据要求提供 属性 org.springframework.web.servlet.support.BindStatus.(BindStatus.java:144) org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168) org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188) org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:154) org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:117) org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:422) org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:142) org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84) org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80) org.apache.jsp.login.index_jsp._jspx_meth_form_005finput_005f0(index_jsp.java:322) org.apache.jsp.login.index_jsp._jspx_meth_form_005fform_005f0(index_jsp.java:216) org.apache.jsp.login.index_jsp._jspService(index_jsp.java:148) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

我已经尝试了一千件事,但我就是无法让它发挥作用。所以,拜托,有人能指出我做错了什么吗?如何根据 jsp 表单中的信息正确构建 java 对象?

提前致谢!

【问题讨论】:

    标签: java spring jsp model-view-controller


    【解决方案1】:

    看来你需要了解更多关于spring mvc的知识。

    您将表单请求映射到视图。您必须将表单请求映射到控制器方法而不是视图,您的表单应如下所示:

    <form:form action="${pageContext.request.contextPath}/inhabitant/create" method="post" modelAttribute="inhabitant" >
       ....
       // have a look at spring form validation 
       // have a look at spring form elements eg. how error messages are displayed
    </form:form>
    

    您需要在控制器中使用两种方法来创建和保存居民,一种用于显示表单,另一种用于将表单数据保存到数据库中。现在你的控制器应该是这样的:

    @Controller
    @RequestMapping(value="/inhabitant")
    public class PostController {
    
    @Autowired
    private InhabitantService inhabitantService;
    
    //Method that displays the form page
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String createForm(Model model ) {
    
        model.addAttribute("inhabitant", new Inhabitant()); // identifier should be same as modelattribute in your form "inhabitant"
        return "formpage"; // your form page name
    
    }
    
    // Method which will have the submitted data
    // Validation is also done in this method
    @RequestMapping(value="/create", method=RequestMethod.POST)
    public String saveForm( @ModelAttribute("inhabitant") @Valid Inhabitant inhabitant, //@valid is used for validation use it If you are doing validation
            BindingResult result // use only if you are doing validation)
    {
           // use only If you are doing validation
           // If validation fails users must return to the same form view
           if (result.hasErrors()){
               return "formpage";
           }
    
           //and save the submitted form data
           inahabitantService.saveInhabitant(inhabitant);
    enter code here
           return "success"; // success.jsp is a success page that you will see after creating a inhabitant
    }
    

    不要在 web.xml 中使用 '/login' 作为 url 模式不要这样做。

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/login</url-pattern> //Just Use '/' instead of '/login'
    </servlet-mapping>
    

    我怀疑你是否正确配置了 hibernate 发布你的 hibernateConfiguration.xml 文件和 persistence.xml 文件。

    您必须学习并理解以下内容:慢慢来。

    • Spring 模型控制器视图及其实际工作原理
    • Spring 表单元素,Spring 表单验证
    • Jpa/hibernate 基础/hibernate 中的关联
    • Jsp 标签库/JSP 内的 JSP/Apache Tiles

    【讨论】:

      【解决方案2】:

      别这样

        model.addAttribute("firstName", inhabitant.getFirstName());
        model.addAttribute("lastName", inhabitant.getLastName());
        model.addAttribute("apartmentNumber", inhabitant.getApartamentNumber());
        model.addAttribute("apartmentOwner", inhabitant.getApartamentOwner());
        model.addAttribute("apartmentNumber", inhabitant.getApartamentNumber());
        model.addAttribute("telephoneNumber", inhabitant.getTelephoneNumber());
        model.addAttribute("emailAddress", inhabitant.getEmailAddress());
      

      改为这样做

      model.addAttribute("inhabitant", inhabitant);
      

      【讨论】:

      • 我也试过了,还是出现同样的错误。是不是jsp文件有问题?
      • 如果有帮助,即使我注释掉控制器方法,我也会得到同样的错误。这就是为什么我猜这个jsp有问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 2016-05-17
      • 2014-09-29
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多