Spring mvc вызывает исключение - IllegalStateException: ни BindingResult, ни простой целевой объект для bean-компонента при использовании формы tld на странице jsp

Когда я использую обычный HTML на странице JSP, то приложение работает нормально, так как я добавляю тег формы в JSP, это дает исключение, я вставил свой код и исключение здесь, пожалуйста, помогите мне. Я не могу решить это и застрял с 3 дня сейчас. Что здесь не так

мой диспетчер-сервлет:

<?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        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.xsd
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context.xsd">

        <mvc:annotation-driven />
        <context:component-scan
            base-package="com.shweta.*" />
        <mvc:default-servlet-handler />

     <mvc:view-controller path="/" view-name="index"/>

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

    </beans>

мой web.xml:

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

  <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>/</url-pattern>
  </servlet-mapping>

</web-app>

мой класс контроллера:

 package com.shweta.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.shweta.model.Employee;
import com.shweta.model.Test;

@Controller
//@ControllerAdvice
@RequestMapping("/employee")
public class EmployeeController {

@RequestMapping(value="/submitForm", method=RequestMethod.POST)
public String formSubmission(@ModelAttribute("employee") Employee employee,BindingResult bindingResult)
        {
            System.out.println("entered in @RequestMapping");
            System.out.println("printing employee from modelattribute");
            System.out.println(employee.getEmail());
            System.out.println(employee.getFirstName());
            System.out.println(employee.getLastName());
            System.out.println(employee.getSalary());
            //modelMap.addAttribute("employee", employee);
            return "EmployeeWelcome";

        }

}

Страница моего сотрудника JSP:

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee page</title>
</head>
<body>
<h1>${msg}</h1>
<%-- <form:form action="employee/submitForm" method="post" > --%>

<form:form action="${pageContext.request.contextPath}/employee/submitForm" method="post" modelAttribute="employee">
  <!-- <div>
    First name:
    <input type="text" name="firstName">
  </div> -->
  <div>
    First name:
    <form:input path="firstName"/>
  </div>
  <div>
    Last name:
    <input type="text" name="lastName">
  </div>
  <div>
    E-mail:
    <input type="email" name="email">
  </div>
  <div>
   Salary:
    <input type="text" name="salary">
  </div>
  <div class="button">
  <button type="submit">Submit</button>
</div>
</form:form>

</body>
</html>

мой сотрудник модельный класс

package com.shweta.model;

public class Employee {

    String email;
    String firstName;
    String lastName;
    Address address;
    long salary;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    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 Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public long getSalary() {
        return salary;
    }

    public void setSalary(long salary) {
        this.salary = salary;
    }

}


HTTP Status 500 – Internal Server Error
Type Exception Report

Message An exception occurred processing JSP page /WEB-INF/jspPages/EmployeeForm.jsp at line 22

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jspPages/EmployeeForm.jsp at line 22

19:   </div> -->
20:   <div>
21:     First name:
22:     <form:input path="firstName"/>
23:   </div>
24:   <div>
25:     Last name:

Фрагмент исключения

Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:613)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:505)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370)
    org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'employee' available as request attribute
    org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:177)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:198)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:163)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:148)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:138)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:121)
    org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:459)
    org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:356)
    org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:86)
    org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:83)
    org.apache.jsp.WEB_002dINF.jspPages.EmployeeForm_jsp._jspx_meth_form_005finput_005f0(EmployeeForm_jsp.java:214)
    org.apache.jsp.WEB_002dINF.jspPages.EmployeeForm_jsp._jspx_meth_form_005fform_005f0(EmployeeForm_jsp.java:158)
    org.apache.jsp.WEB_002dINF.jspPages.EmployeeForm_jsp._jspService(EmployeeForm_jsp.java:104)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:472)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170)
    org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316)
    org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370)
    org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Note The full stack trace of the root cause is available in the server logs.

Apache Tomcat/7.0.94

Всего 2 ответа


Вы не поместили в модель бин с именем «сотрудник». Вы должны внедрить один перед рендерингом представления. Добавьте метод к своему контроллеру, чтобы сделать это.


Вы должны поместить bean в модель перед рендерингом jsp. Например, вам нужно объявить метод ниже в EmployeeController и получить доступ к jsp через метод.

  @RequestMapping("index")
  public String index(Model model) {
    model.addAttribute("employee", new Employee());
    return "EmployeeForm";
  }

Аналогичный вопрос: ни BindingResult, ни простой целевой объект для имени компонента не доступны в качестве атрибута запроса


Есть идеи?

10000