복붙노트

[SPRING] BindingResult도 일반 대상 객체도 아닙니다 ... 예외

SPRING

BindingResult도 일반 대상 객체도 아닙니다 ... 예외

예, 읽는 것이 꽤 흔한 문제입니다.하지만 그 글을 읽는 것은 정말 도움이되지 않았습니다.

짧은 이야기는 showAllComments.jsp에 양식을 제출하고 싶습니다.

<form:form method="post" action="postNewComment.html">
        <table>
            <tr>
                <td><form:label path="comment">
                        COMMENT
                    </form:label></td>
                <td><form:input path="comment" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit"
                    value="WRITE" /></td>
            </tr>
        </table>
    </form:form>

다음은 컨트롤러입니다.

@Controller
@SessionAttributes
public class CommentController {


    @Autowired
    private CommentService commentService;


    @RequestMapping(value = "/postNewComment", method = RequestMethod.POST)
    public ModelAndView showAllUsers(@ModelAttribute("command") Comment comment, BindingResult result) {


        System.out.println(comment.getComment());

        Map<String, Object> model = new HashMap<String, Object>();
        model.put("COMMENTS", commentService.getComments());

        return new ModelAndView("showAllComments", model);
    }
}

결과는 다음과 같습니다. java.lang.IllegalStateException : 요청 속성으로 BindingResult 나 bean 이름 'command'에 대한 일반 대상 객체를 사용할 수 없습니다.

그러나 아마도 처음부터 전체 이야기를 볼 필요가 있습니다. 사용자는를 클릭하여 index.jsp에서 응용 프로그램을 시작합니다.

<a href="toLoginPage.html">Log in</a> 

이 링크는 그를 LoginController로 데려 간다.

@RequestMapping("/toLoginPage")
    public ModelAndView goToLoginPage() {
        return new ModelAndView("login", "command", new User());
}

그런 다음 login.jsp로 이동하여 사용자 이름과 비밀번호를 제공합니다.

<form:form method="post" action="log_in.html">

        <input type="text" name="uName" />
        <input type="password" name="pW" />

        <input type="submit" value="Log IN">
    </form:form> 

그는 양식을 제출하고 LoginController로 다시 가져옵니다.

@RequestMapping(value = "/log_in", method = RequestMethod.POST)
    public ModelAndView tryToLogin(@RequestParam("uName") String uName, @RequestParam("pW") String pW, HttpServletResponse response, HttpServletRequest request) {
        ModelAndView ret = new ModelAndView("login", "command", new User());
        User user = userService.existingUser(uName, pW);
        loggedInUser = new User();
        if (user != null) {
            Map<String, Object> model = new HashMap<String, Object>();
                model.put("COMMENTS", allComments);
                model.put("LOGGED_IN_USER", loggedInUser);
            ret = ModelAndView("showAllComments", model);
        }
        return ret;
    }

로그인 성공 후 그는 showAllComments 페이지에 모든 의견을 볼 수 있으며 자신의 의견을 추가 할 수 있어야하지만 위에서 언급 한 양식을 제출하면 위에서 언급 한 예외가 발생합니다. 뭔가 빠진 것 같지만 그게 뭔지 알 수는 없습니다. 단지 기록을 위해 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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    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>Spring3MVC</display-name>

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

와 spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <context:property-placeholder location="classpath:jdbc.properties" />
    <context:component-scan base-package="net" />

    <tx:annotation-driven transaction-manager="hibernateTransactionManager" />

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

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${database.driver}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.user}" />
        <property name="password" value="${database.password}" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>net.model.User</value>
                <value>net.model.Comment</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            </props>
        </property>
    </bean>

    <bean id="hibernateTransactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

    <bean id="localeChangeInterceptor"
        class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="lang" />
    </bean>

    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="defaultLocale" value="en" />
    </bean>

    <bean id="handlerMapping"
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="interceptors">
            <ref bean="localeChangeInterceptor" />
        </property>
    </bean>

</beans>

해결법

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

    1.logincontroller에 showAllComments.jsp를 표시 할 때 양식 빈 클래스 즉, 주석을 모델의 속성으로 추가해야합니다.

    logincontroller에 showAllComments.jsp를 표시 할 때 양식 빈 클래스 즉, 주석을 모델의 속성으로 추가해야합니다.

    @RequestMapping(value = "/log_in", method = RequestMethod.POST)
    public ModelAndView tryToLogin(@RequestParam("uName") String uName, @RequestParam("pW") String pW,      HttpServletResponse response, HttpServletRequest request) {
        ModelAndView ret = new ModelAndView("login", "command", new User());
        User user = userService.existingUser(uName, pW);
        loggedInUser = new User();
        model.addAttribute("command", new Comment());
        if (user != null) {
            Map<String, Object> model = new HashMap<String, Object>();
                model.put("COMMENTS", allComments);
                model.put("LOGGED_IN_USER", loggedInUser);
            ret = ModelAndView("showAllComments", model);
        }
        return ret;
    }
    

    이 잘 작동합니다.

    최신 정보

    그리고 'command'를 명령 객체 이름으로 사용하는 것은 좋지 않습니다. 클래스 주석에 대해서는 '주석'또는 이와 유사한 것을 사용할 수 있습니다. 그렇게하면 다음 코드로 양식을 업데이트하십시오.

    <form:form method="post" action="postNewComment.html" commandName="comment">
        <table>
            <tr>
                <td><form:label path="comment">
                        COMMENT
                    </form:label></td>
                <td><form:input path="comment" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit"
                    value="WRITE" /></td>
            </tr>
        </table>
    </form:form>
    

    다른 모든 곳에서 똑같은 변화를가하십시오.

    model.addAttribute("comment", new Comment());
    

    @ModelAttribute("comment")
    

    업데이트 2

        @RequestMapping(value="userRegistration", method = RequestMethod.GET)
    public ModelAndView showUserRegistrationForm(Model model){
        model.addAttribute("user", new AccountDetailsForm());
        return new ModelAndView("userRegistration");
    }
    
  2. from https://stackoverflow.com/questions/12025888/neither-bindingresult-nor-plain-target-object-exception by cc-by-sa and MIT license