Spring <form:select> 标签在 Spring mvc + Hibernate 应用程序中导致错误

Posted

技术标签:

【中文标题】Spring <form:select> 标签在 Spring mvc + Hibernate 应用程序中导致错误【英文标题】:Spring <form:select> tag causing error in Spring mvc + Hibernate app 【发布时间】:2013-12-26 20:55:19 【问题描述】:

首先,我想说的是,我已经在整个 Internet 和 SO 上搜索了解决方案,但没有找到针对这种特殊情况的解决方案。我只是在学习 java web 编程。我正在制作简单的 mvc 应用程序,用于将教师添加到 mysql 数据库。 DB只有3个表:'teacher'、'title'和连接表'teacher_title'。 'title' 是一个查找表,具有 'title_id' / 'title_description' 值。 在我的 jsp 页面中,我有用于选择教师职称(例如博士、理学硕士等)的下拉列表、用于输入教师名字和姓氏的 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

这是标题实体:

    @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;
    

到目前为止,我设法理解的是问题出在我的 jsp 中的 select 标记上。当我注释掉选择标签并手动输入参数时(例如 URL?id=1),保存到数据库就可以了。否则我会收到以下错误:“HTTP 状态 400 - 客户端发送的请求在语法上不正确。”。我也在网上搜索过这个错误,但没有找到适用的解决方案。

我无法确定我在哪里犯了错误。提前谢谢你。

更新: 这是添加新教师的新控制器方法,其中@RequestParamvalue 属性从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)));
         
     );

结束!

【问题讨论】:

你应该发布一些不太冗长的问题,这真的很难理解。您可以从删除不必要的 getter 和 setter 开始... 我猜add?id=titleId 应该是add?id=$titleId @Bart 我试过了,但发送的是add?id= 。似乎$titleId 是空的(就像从列表中选择项目甚至不起作用)。知道为什么吗? org.springframework 上将日志级别设置为 TRACE 时会输出什么?它应该显示出了什么问题 【参考方案1】:

您收到此错误是因为您正在使用

@ModelAttribute("teacherAttribute") 老师老师)

Spring 无法将您的 requestParam “title”(即字符串)转换为属于教师实体的 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);

【讨论】:

'@storm_buster' 它不会让我在评论中标记你,所以我不得不添加引号只是为了显示你的用户名。另外,谢谢您的解释...除了接受您的回答,我还能为您的声誉评分做些​​什么吗?我无权投票给答案...:/ @just_a_girl 我认为没关系。很高兴它起作用了。随便问什么。【参考方案2】:

&lt;c:url var="saveUrl" value="/essays/main/teacher/add?id=titleId" /&gt;

您不需要手动将参数写为?id=titleId,它会自动添加。在这种情况下,在请求正文中(因为它是 POST 请求)。

另外,表单标签中的path 属性和控制器属性中的@RequestParam 中的value 必须相同。所以写,比如@RequestParam(value = "title") Integer titleId

【讨论】:

好的,如果我在jsp中丢失了?id=titleId,并且在处理程序方法中丢失了@RequestParam(value="id") Integer titleId,我如何访问控制器中的titleId(因为我需要通过它给教师服务)?很抱歉问了这样一个初学者的问题... 当你给&lt;form:select path="title" ..@RequestParam(value = "title") .. 赋予相同的名字时,Spring 将绑定值并放入你的titleId 变量中 我明白了,我按照你说的做了(删除了?id=titleId 并将@RequestParam 中的'id' 重命名为'title')但我仍然收到同样的错误(“客户端发送的请求是语法不正确。") :( 你知道如何通过&lt;form:options ...&gt; 标签告诉控制器itemValue="titleId",我相信这就是它所期望的吗?还是我错了? BTW Max Vasileusky 我不知道如何在我的评论中标记你,'@Max Vasileusky' 不起作用...... itemValue 用于填充列表。如果下拉列表没问题,那么 itemValue 没问题 :) 如果您使用的是 Chrome,您可以按 F12,打开网络选项卡,从页面发送请求,看看它的参数是否符合预期。 (其他浏览器也有类似的工具)

以上是关于Spring <form:select> 标签在 Spring mvc + Hibernate 应用程序中导致错误的主要内容,如果未能解决你的问题,请参考以下文章

Spring <form:select> 标签在 Spring mvc + Hibernate 应用程序中导致错误

表单中f.select上的“未定义”占位符

Vue form-item select option 自定义校验

Vue form-item select option 自定义校验

如何添加 optgroup do dijit.form.Select 或其他小部件类型

前端 form select js处理