Тег Spring <form: select>, вызывающий ошибку в приложении Spring mvc + Hibernate

0

Прежде всего, я хотел бы сказать, что я искал решение по всему Интернету и так, но не нашел решения для этой конкретной ситуации. Я просто изучаю Java-программирование. Я делаю простое приложение mvc для добавления учителей в базу данных MySQL. БД имеет только 3 таблицы: "учитель", "заголовок" и таблица соединений "teacher_title". 'title' - это таблица поиска, имеющая значения 'title_id'/'title_description'. На моей странице jsp у меня есть раскрывающийся список для выбора названия преподавателя (например, PhD, MSc и т.д.), 2 поля ввода для ввода имени и фамилии учителя и кнопки отправки/сохранения.

Это мой контроллер:

    /**
     * Handles and retrieves the add teacher page
     */
    @RequestMapping(value="/add", method = RequestMethod.GET)
    public String getAddTeacher(Model model) {

        logger.debug("Received request to show add teacher page");

        // Add to model
        model.addAttribute("teacherAttribute", new Teacher());
        model.addAttribute("titleList", titleService.getAll());

        return "addTeacher";
    }

    /**
     * Adds a new teacher by delegating the processing to TeacherService.
     * Displays a confirmation JSP page
     */
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public String postAddTeacher(@RequestParam(value = "id") Integer titleId, 
                                @ModelAttribute("teacherAttribute") Teacher teacher) {

        logger.debug("Received request to add new teacher");

        // Call TeacherService to do the actual adding
        teacherService.add(titleId, teacher);

        return "addTeacherSuccess";
    }

Это важная часть страницы addTeacher.jsp:

<c:url var="saveUrl" value="/essays/main/teacher/add?id=titleId" />
<form:form modelAttribute="teacherAttribute" method="POST" action="${saveUrl}">
        <form:label path="title">Title:</form:label>
        <form:select path="title" id="titleSelect">
            <form:option value="0" label="Select" />
            <form:options items="${titleList}" itemValue="titleId" itemLabel="titleDescription" />              
        </form:select>
...

Это учитель:

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "TEACHER_ID")
    private Integer techerId;

    @Column(name = "FIRST_NAME", length = 50)
    private String firstName;

    @Column(name = "LAST_NAME", length = 50)
    private String lastName;

    @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.EAGER)
        @JoinTable(name="teacher_title",
        joinColumns = @JoinColumn(name="TEACHER_ID"),
        inverseJoinColumns = @JoinColumn(name="TITLE_ID")
                )
    private Title title;
// getters and setters
}

Это элемент Title:

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "TITLE_ID")
    private Integer titleId;

    @Column(name = "TITLE_DESCRIPTION", length = 10)
    private String titleDescription;
// getters and setters
}

И на всякий случай, это услуги Учителя и Тита, соответственно:

    /**
     * Adds new teacher
     */
    public void add(Integer titleId, Teacher teacher) {

        logger.debug("Adding new teacher");

        Session session = sessionFactory.getCurrentSession();

        // Retrieve existing title via id
        Title existingTitle = (Title) session.get(Title.class, titleId);

        // Add title to teacher
        teacher.setTitle(existingTitle);

        // Persists to db
    session.save(teacher);
    }

,

    /**
     * Retrieves a list of titles
     */
    public List<Title> getAll() {

        logger.debug("Retrieving all titles");

        Session session = sessionFactory.getCurrentSession();

        Query query = session.createQuery("FROM Title");

        List<Title> titleList = castList(Title.class, query.list());

        return titleList;
    }

    public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {
        List<T> r = new ArrayList<T>(c.size());
        for(Object o: c)
          r.add(clazz.cast(o));
        return r;
    }

    /**
     * Retrieves a single title
     */
    public Title get(Integer titleId) {

        logger.debug("Retrieving single title");

        Session session = sessionFactory.getCurrentSession();

        // Retrieve existing title
        Title title = (Title) session.get(Title.class, titleId);

        return title;
    }

До сих пор я понял, что проблема связана с тегом select в моем jsp. Когда я комментирую select tag и eneter параметр вручную (например, URL? Id = 1), сохранение в БД работает просто отлично. В противном случае я получаю следующую ошибку: "HTTP Status 400 - запрос, отправленный клиентом, был синтаксически неправильным". Я тоже искал в Интернете эту ошибку, но не нашел подходящих решений.

Только мое скромное знание определяет, где я делаю ошибку. Заранее спасибо.

Обновление: это новый метод контроллера для добавления нового учителя, где @RequestParam value @RequestParam был изменен с id на title:

@RequestMapping(value="/add", method = RequestMethod.POST)
public String postAddTeacher(@RequestParam(value = "title") Integer titleId, 
@ModelAttribute("teacherAttribute") Teacher teacher) {

logger.debug("Received request to add new teacher");

// Call TeacherService to do the actual adding
teacherService.add(titleId, teacher);

// This will resolve to /WEB-INF/jsp/addTeacherSuccess.jsp
return "addTeacherSuccess";

}

И это новый addTeacher.jsp, где ?id=titleId был удален из URL:

<c:url var="saveUrl" value="/essays/main/teacher/add" />
<form:form modelAttribute="teacherAttribute" method="POST" action="${saveUrl}">
        <form:label path="title">Title:</form:label>
        <form:select path="title" id="titleSelect">
            <form:option value="0" label="Select" />
            <form:options items="${titleList}" itemValue="titleId" itemLabel="titleDescription" />              
        </form:select>
...

По-прежнему возникает такая же ошибка, как и раньше.

Вот ошибка, которую я получаю (и я не понимаю):

[TRACE] [http-bio-8080-exec-7 11:10:38] (InvocableHandlerMethod.java:getMethodArgumentValues:166) Error resolving argument [1] [type=com.jovana.domain.Teacher]
HandlerMethod details: 
Controller [com.jovana.controller.MainController]
Method [public java.lang.String com.jovana.controller.MainController.postAddTeacher(java.lang.Integer,com.jovana.domain.Teacher)]

org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'teacherAttribute' on field 'title': rejected value [4]; codes [typeMismatch.teacherAttribute.title,typeMismatch.title,typeMismatch.com.jovana.domain.Title,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [teacherAttribute.title,title]; arguments []; default message [title]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.jovana.domain.Title' for property 'title'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.jovana.domain.Title] for property 'title': no matching editors or conversion strategy found]
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:110)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:77)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:123)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    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.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:744)
[TRACE] [http-bio-8080-exec-7 11:10:38] (InvocableHandlerMethod.java:getMethodArgumentValues:166) Error resolving argument [1] [type=com.jovana.domain.Teacher]
HandlerMethod details: 
Controller [com.jovana.controller.MainController]
Method [public java.lang.String com.jovana.controller.MainController.postAddTeacher(java.lang.Integer,com.jovana.domain.Teacher)]

org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'teacherAttribute' on field 'title': rejected value [4]; codes [typeMismatch.teacherAttribute.title,typeMismatch.title,typeMismatch.com.jovana.domain.Title,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [teacherAttribute.title,title]; arguments []; default message [title]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.jovana.domain.Title' for property 'title'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.jovana.domain.Title] for property 'title': no matching editors or conversion strategy found]
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:110)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:77)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:123)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
    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.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:744)
[DEBUG] [http-bio-8080-exec-7 11:10:38] (AbstractHandlerExceptionResolver.java:resolveException:132) Resolving exception from handler [public java.lang.String com.jovana.controller.MainController.postAddTeacher(java.lang.Integer,com.jovana.domain.Teacher)]: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'teacherAttribute' on field 'title': rejected value [4]; codes [typeMismatch.teacherAttribute.title,typeMismatch.title,typeMismatch.com.jovana.domain.Title,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [teacherAttribute.title,title]; arguments []; default message [title]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.jovana.domain.Title' for property 'title'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.jovana.domain.Title] for property 'title': no matching editors or conversion strategy found]
[DEBUG] [http-bio-8080-exec-7 11:10:38] (AbstractHandlerExceptionResolver.java:resolveException:132) Resolving exception from handler [public java.lang.String com.jovana.controller.MainController.postAddTeacher(java.lang.Integer,com.jovana.domain.Teacher)]: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'teacherAttribute' on field 'title': rejected value [4]; codes [typeMismatch.teacherAttribute.title,typeMismatch.title,typeMismatch.com.jovana.domain.Title,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [teacherAttribute.title,title]; arguments []; default message [title]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.jovana.domain.Title' for property 'title'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.jovana.domain.Title] for property 'title': no matching editors or conversion strategy found]
[DEBUG] [http-bio-8080-exec-7 11:10:38] (AbstractHandlerExceptionResolver.java:resolveException:132) Resolving exception from handler [public java.lang.String com.jovana.controller.MainController.postAddTeacher(java.lang.Integer,com.jovana.domain.Teacher)]: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'teacherAttribute' on field 'title': rejected value [4]; codes [typeMismatch.teacherAttribute.title,typeMismatch.title,typeMismatch.com.jovana.domain.Title,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [teacherAttribute.title,title]; arguments []; default message [title]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.jovana.domain.Title' for property 'title'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.jovana.domain.Title] for property 'title': no matching editors or conversion strategy found]
[DEBUG] [http-bio-8080-exec-7 11:10:38] (AbstractHandlerExceptionResolver.java:resolveException:132) Resolving exception from handler [public java.lang.String com.jovana.controller.MainController.postAddTeacher(java.lang.Integer,com.jovana.domain.Teacher)]: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'teacherAttribute' on field 'title': rejected value [4]; codes [typeMismatch.teacherAttribute.title,typeMismatch.title,typeMismatch.com.jovana.domain.Title,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [teacherAttribute.title,title]; arguments []; default message [title]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.jovana.domain.Title' for property 'title'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.jovana.domain.Title] for property 'title': no matching editors or conversion strategy found]
[DEBUG] [http-bio-8080-exec-7 11:10:38] (AbstractHandlerExceptionResolver.java:resolveException:132) Resolving exception from handler [public java.lang.String com.jovana.controller.MainController.postAddTeacher(java.lang.Integer,com.jovana.domain.Teacher)]: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'teacherAttribute' on field 'title': rejected value [4]; codes [typeMismatch.teacherAttribute.title,typeMismatch.title,typeMismatch.com.jovana.domain.Title,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [teacherAttribute.title,title]; arguments []; default message [title]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.jovana.domain.Title' for property 'title'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.jovana.domain.Title] for property 'title': no matching editors or conversion strategy found]
[DEBUG] [http-bio-8080-exec-7 11:10:38] (AbstractHandlerExceptionResolver.java:resolveException:132) Resolving exception from handler [public java.lang.String com.jovana.controller.MainController.postAddTeacher(java.lang.Integer,com.jovana.domain.Teacher)]: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'teacherAttribute' on field 'title': rejected value [4]; codes [typeMismatch.teacherAttribute.title,typeMismatch.title,typeMismatch.com.jovana.domain.Title,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [teacherAttribute.title,title]; arguments []; default message [title]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.jovana.domain.Title' for property 'title'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.jovana.domain.Title] for property 'title': no matching editors or conversion strategy found]
[DEBUG] [http-bio-8080-exec-7 11:10:38] (DispatcherServlet.java:processDispatchResult:999) Null ModelAndView returned to DispatcherServlet with name 'spring': assuming HandlerAdapter completed request handling
[DEBUG] [http-bio-8080-exec-7 11:10:38] (DispatcherServlet.java:processDispatchResult:999) Null ModelAndView returned to DispatcherServlet with name 'spring': assuming HandlerAdapter completed request handling
[TRACE] [http-bio-8080-exec-7 11:10:38] (FrameworkServlet.java:resetContextHolders:1028) Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@5f57b190
[TRACE] [http-bio-8080-exec-7 11:10:38] (FrameworkServlet.java:resetContextHolders:1028) Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@5f57b190
[DEBUG] [http-bio-8080-exec-7 11:10:38] (FrameworkServlet.java:processRequest:966) Successfully completed request
[DEBUG] [http-bio-8080-exec-7 11:10:38] (FrameworkServlet.java:processRequest:966) Successfully completed request
[TRACE] [http-bio-8080-exec-7 11:10:38] (AbstractApplicationContext.java:publishEvent:332) Publishing event in WebApplicationContext for namespace 'spring-servlet': ServletRequestHandledEvent: url=[/testLookupTable/essays/main/teacher/add]; client=[0:0:0:0:0:0:0:1]; method=[POST]; servlet=[spring]; session=[72089007DB0E4468BA90CDA44FCA8CC0]; user=[null]; time=[144ms]; status=[OK]
[TRACE] [http-bio-8080-exec-7 11:10:38] (AbstractApplicationContext.java:publishEvent:332) Publishing event in WebApplicationContext for namespace 'spring-servlet': ServletRequestHandledEvent: url=[/testLookupTable/essays/main/teacher/add]; client=[0:0:0:0:0:0:0:1]; method=[POST]; servlet=[spring]; session=[72089007DB0E4468BA90CDA44FCA8CC0]; user=[null]; time=[144ms]; status=[OK]
[TRACE] [http-bio-8080-exec-7 11:10:38] (AbstractApplicationContext.java:publishEvent:332) Publishing event in Root WebApplicationContext: ServletRequestHandledEvent: url=[/testLookupTable/essays/main/teacher/add]; client=[0:0:0:0:0:0:0:1]; method=[POST]; servlet=[spring]; session=[72089007DB0E4468BA90CDA44FCA8CC0]; user=[null]; time=[144ms]; status=[OK]
[TRACE] [http-bio-8080-exec-7 11:10:38] (AbstractApplicationContext.java:publishEvent:332) Publishing event in Root WebApplicationContext: ServletRequestHandledEvent: url=[/testLookupTable/essays/main/teacher/add]; client=[0:0:0:0:0:0:0:1]; method=[POST]; servlet=[spring]; session=[72089007DB0E4468BA90CDA44FCA8CC0]; user=[null]; time=[144ms]; status=[OK]

Решение (спасибо storm_buster) добавляет это к контроллеру:

@InitBinder
public void initBinder(WebDataBinder binder, WebRequest request) {

        binder.registerCustomEditor(Title.class, "title", new PropertyEditorSupport() {
         @Override
         public void setAsText(String text) {
            setValue((text.equals(""))?null:titleService.getTitle(Integer.parseInt((String)text)));
         }
     });
}

Конец!

  • 1
    Вы должны оставлять меньше подробных вопросов, это действительно трудно понять. Вы можете начать с удаления ненужных геттеров и сеттеров ...
  • 0
    Я предполагаю, что add?id=titleId должен быть add?id=${titleId} ?
Показать ещё 2 комментария
Теги:
jsp
spring
hibernate

2 ответа

2
Лучший ответ

вы получаете эту ошибку, потому что используете

@ModelAttribute ("teacherAttribute") Учитель-учитель)

Spring не может преобразовать ваш заголовок requestParam (который является строкой) в класс Title, принадлежащий подчиненному объекту.

У вас есть два решения: 1- добавьте это в свой контроллер

@InitBinder
public void initBinder(WebDataBinder binder, WebRequest request) {

        binder.registerCustomEditor(Title.class, "title", new PropertyEditorSupport() {
         @Override
         public void setAsText(String text) {
            setValue((text.equals(""))?null:titleService.getTitle(Integer.parseInt((String)text)));
         }
     });
}   

2- Измените запрос:

@RequestMapping(value="/add", method = RequestMethod.POST)
public String postAddTeacher(@RequestParam(value = "title") Integer titleId, 
@RequestParam("teacherAttribute") Integer teacherId) {

И добавьте новый интерфейс:

teacherService.add(titleId, teacherId);
  • 0
    '@storm_buster' Это не позволит мне отметить вас в моем комментарии, поэтому мне пришлось добавить кавычки, чтобы показать ваше имя пользователя. Кроме того, спасибо за объяснение ... Могу ли я что-то сделать для вашей репутации, кроме как принять ваш ответ? У меня нет разрешения голосовать за ответ ...: /
  • 0
    @just_a_girl Я думаю, что все в порядке. Просто рад, что это сработало. Не стесняйтесь спрашивать что-нибудь.
0

<c:url var="saveUrl" value="/essays/main/teacher/add?id=titleId"/>

Вам не нужно писать параметры как ?id=titleId вручную, он будет добавлен автоматически. В этом случае в теле запроса (потому что это запрос POST).

Также атрибут path в теге формы и value @RequestParam в атрибутах контроллера должны быть одинаковыми. Так пишите, например @RequestParam(value = "title") Integer titleId

  • 0
    Хорошо, если я потеряю? Id = titleId в jsp и @RequestParam (value = "id") Integer titleId в методе-обработчике, как мне получить доступ к titleId в контроллере (потому что мне нужно передать его в teacherService)? Извините, что задали такой вопрос для начинающих ...
  • 0
    Когда вы будете давать одинаковые имена <form:select path="title" .. и @RequestParam(value = "title") .. Spring свяжет значение и поместит в вашу переменную titleId
Показать ещё 9 комментариев

Ещё вопросы

Сообщество Overcoder
Наверх
Меню