복붙노트

[SPRING] java.lang.IllegalStateException : 요청 속성으로 BindingResult 또는 'category'bean name의 일반 대상 객체를 사용할 수 없습니다.

SPRING

java.lang.IllegalStateException : 요청 속성으로 BindingResult 또는 'category'bean name의 일반 대상 객체를 사용할 수 없습니다.

거의 모든 답변을 웹에서이 문제와 관련되어 보였지만 내 코드의 문제를 파악할 수 없었습니다.

다음은 JSP 페이지입니다.

<form:form method="POST" commandName="category" modelAttribute="category" action="search_category">
    <form:input path="category_name" /> 
    <input type="submit" value="Submit">  
</form:form>

삭제할 때

<form:input path="category_name" /> 

그것은 잘 작동합니다. 내 컨트롤러와 통신 할 수 있습니다. 문제는이 줄과 관련이 있습니다.

@Controller
public class SearchCategory {

    @Autowired      
    private CategoryService categoryService;

    @RequestMapping(value = "/search_category",  method = RequestMethod.POST)
    public @ResponseBody String searchCategoryFromDatabase(@ModelAttribute("category") Category category, BindingResult result){        

        return "something";
    }
}

여기 내 web.xml입니다.

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

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

     <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>/WEB-INF/applicationContext.xml</param-value>  
    </context-param>  

    <filter>  
        <filter-name>hibernateFilter</filter-name>  
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>  
    </filter>  
    <filter-mapping>  
        <filter-name>hibernateFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>      

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

</web-app>

이것은 내 servlet-context.xml입니다.

<!--  Set the default page as index.jsp -->
<mvc:view-controller path="/" view-name="index"/>

<!-- Map resources --> 
<mvc:resources mapping="/resources/**" location="/, classpath:/META-INF/web-resources/" /> 

<!-- Map simple view name such as "test" into /WEB-INF/views/test.jsp -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/" />
    <property name="suffix" value=".jsp" />
</bean>

그리고 내 applicationContext.xml

<!-- Enable @Controller annotation support -->
    <mvc:annotation-driven />

    <context:annotation-config/>    

    <!--  Set the default page as index.jsp -->
    <mvc:view-controller path="/" view-name="index"/>

     <!-- Map resources --> 
    <mvc:resources mapping="/resources/**" location="/, classpath:/META-INF/web-resources/" /> 

    <!-- Map simple view name such as "test" into /WEB-INF/views/test.jsp -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- Scan classpath for annotations (eg: @Service, @Repository etc) -->
    <context:component-scan base-package="com.XXXX"/>

    <!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with 
         username root and blank password. Change below if it's not the case -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/XXXX"/>
        <property name="username" value="XXXX"/>
        <property name="password" value="XXXX"/>
        <property name="validationQuery" value="SELECT 1"/>
    </bean>

    <!-- Hibernate Session Factory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="packagesToScan">
            <array>
                <value>com.XXXX</value>
            </array>
        </property>
        <property name="hibernateProperties">
            <value>
                hibernate.dialect=org.hibernate.dialect.MySQLDialect
            </value>
        </property>     
    </bean>

    <!-- Hibernate Transaction Manager -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <!-- Activates annotation based transaction management -->
    <tx:annotation-driven transaction-manager="transactionManager"/>  

나는 아마 XML 파일에서 뭔가 잘못하고있다. 나는이 봄을 위해 새롭다 - 최대 절전 모드 직원들이 당신의 도움을 기다리고있다. 감사..

이것은 던져진 예외입니다.

Stacktrace:] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'category' 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:168)
    at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
    at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:154)
    at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:141)
    at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:132)
    at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:116)
    at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:422)
    at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:142)
    at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
    at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
    at org.apache.jsp.index_jsp._jspx_meth_form_005finput_005f0(index_jsp.java:208)
    at org.apache.jsp.index_jsp._jspx_meth_form_005fform_005f0(index_jsp.java:168)
    at org.apache.jsp.index_jsp._jspService(index_jsp.java:100)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.orm.hibernate4.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:149)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)

해결법

  1. ==============================

    1.http : // localhost : 8080 / yourapp와 같은 것을 통해 index.jsp를 얻는다면, 이 있다고 가정합니다.

    http : // localhost : 8080 / yourapp와 같은 것을 통해 index.jsp를 얻는다면, 이 있다고 가정합니다.

    즉, index.jsp는 Spring의 사전 처리없이 HTML을 생성합니다. 이걸 렌더링하려고합니다.

    <form:form method="POST" commandName="category" modelAttribute="category" action="search_category">
        <form:input path="category_name" /> 
        <input type="submit" value="Submit">  
    </form:form>
    

    여기서

    은 Spring의 태그 라이브러리에서 온 것이다. 먼저 commandName과 modelAttribute를 모두 사용한다는 점에 유의하십시오. 이것은 불필요합니다. 둘 중 하나만 사용하십시오. 둘째, 이들 중 하나를 지정할 때 태그 구현은 지정된 이름으로 HttpServletRequest 속성을 찾습니다. 귀하의 경우에는 HttpServletRequest 특성에 이러한 특성이 추가되지 않았습니다. 서블릿 컨테이너가 index.jsp로 직접 전달 되었기 때문입니다.

    그 대신에 모델에 속성을 추가하고 index.jsp 뷰로 전달할 새로운 @Controller 핸들러 메소드를 작성하십시오.

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String welcomePage(Model model) {
        model.addAttribute("category", new Category()); // the Category object is used as a template to generate the form
        return "index";
    }
    

    너는 이것을 제거 할 수있다.

    <!--  Set the default page as index.jsp -->
    <mvc:view-controller path="/" view-name="index"/>
    

    또한 mvc 구성을 applicationContext.xml 파일에서 servlet-context.xml 파일로 이동하십시오. 그것은 그것이 속한 곳입니다. 이유가 여기 있습니다.

  2. ==============================

    2.이 오류는 일반적으로 양식 입력 ID가 적절하게 바인드되지 않은 경우 발생하여 bean과 다른 양식 태그에 사용 된 이름 / ID를 의미합니다.

    이 오류는 일반적으로 양식 입력 ID가 적절하게 바인드되지 않은 경우 발생하여 bean과 다른 양식 태그에 사용 된 이름 / ID를 의미합니다.

  3. ==============================

    3.이것은 나를 위해 작동합니다!

    이것은 나를 위해 작동합니다!

    <form method="POST" action="employee.do">
        <table>
            <tr>
                <td>Name</td>
                <td><input type="text" name="name" /></td> 
            </tr>
            <tr>
                <td>Age</td>
                <td><input type="text" name="age" /></td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="submit" value="Add Employee"/>
                </td>
            </tr>
        </table>    
    </form>
    

    제어 장치

    @RequestMapping(value = "/employee", method = RequestMethod.POST)
        private ModelAndView addemployee(Employee emp, ModelAndView model, 
                @RequestParam String name, 
                @RequestParam String age) {
    
            emp.setAge(age);
            emp.setName(name);
            employeeService.persistEmployee(emp);
    
            return new ModelAndView("redirect:/employee.do");
    
        }
    
  4. from https://stackoverflow.com/questions/21790656/java-lang-illegalstateexception-neither-bindingresult-nor-plain-target-object-f by cc-by-sa and MIT license