【问题标题】:Form Error Messages are not displaying in jsp in spring MVCSpring MVC中的jsp中不显示表单错误消息
【发布时间】:2015-05-21 13:05:19
【问题描述】:

我向 jsp 页面添加了验证,验证正在运行,但没有显示消息。

下面是代码:

JSP:

<body>
<h2>Contact Manager</h2>
<form:form method="post" action="addContact.html">

    <table>
    <tr>
        <td><form:label path="firstname">First Name</form:label></td>
        <td><form:input path="firstname" /><br/></td> 
    </tr>
    <tr>
    <td><font color="red"> <form:errors path="firstname"></form:errors></font></td>
    </tr>
    <tr>
        <td><form:label path="lastname">Last Name</form:label></td>
        <td><form:input path="lastname" /></td>
    </tr>
    <tr>
    <td><font color="red"> <form:errors path="lastname"></form:errors></font></td>
    </tr>
    <tr>
        <td><form:label path="email">Email</form:label></td>
        <td><form:input path="email" /></td>
    </tr>
    <tr>
    <td><font color="red"> <form:errors path="email"></form:errors></font></td>
    </tr>
    <tr>
        <td><form:label path="telephone">Telephone</form:label></td>
        <td><form:input path="telephone" /></td>
    </tr>
    <tr>
    <td><font color="red"> <form:errors path="telephone"></form:errors></font></td>
    </tr>
    <tr>
        <td colspan="2">
            <input type="submit" value="Add Contact"/>
        </td>
    </tr>
</table>    

</form:form>
</body>
</html>

以下是配置:

Spring-servlet.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:property-placeholder location="classpath:resources/jdbc.properties" />
<context:component-scan
        base-package="com.DDD" />
<mvc:annotation-driven />
<bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass">
            <value>
                org.springframework.web.servlet.view.tiles2.TilesView
            </value>
        </property>
    </bean>
    <bean id="tilesConfigurer"
        class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/tiles.xml</value>
            </list>
        </property>

    </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>com.DDD.dto.RegisterDto</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>
    <!-- Configuring message properties -->
    <bean id="messageSource"
      class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:resources/messages_en.properties" />
</bean>

</beans>

以下是控制器代码:

控制器:

package com.DDD.controller;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
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.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.ezkart.form.Contact;
@Controller
@SessionAttributes

public class ContactController {

    private static final Logger logger = Logger.getLogger(ContactController.class);

    @RequestMapping(value = "/addContact", method = RequestMethod.POST)
    public ModelAndView addContact(@ModelAttribute("contact") @Valid Contact contact, BindingResult result) {
        logger.info("Add Contact is Being Executing");
        if(result.hasErrors()) {
            logger.warn("Requested Fields Has Errors");
            logger.error("Field Error Count:"+result.getFieldErrorCount());
            return new ModelAndView("contact", "command",contact);
        }else{
            logger.warn("Requested Fields Has No Errors");
            return new ModelAndView("contact", "command", new Contact());
        }

        //return "redirect:contact.html";
    }


    @RequestMapping("/contact")
    public ModelAndView showContacts() {
        logger.warn("Contact Page is Being Executed");
        return new ModelAndView("contact", "command", new Contact());
    }
}

下面是pojo bean:

表格:

package com.DDD.form;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.Size;

public class Contact {
    @NotEmpty(message = "First Name should not be blank.")
    private String firstname;

    @NotEmpty(message = "Last Name should not be blank.")
    private String lastname;

    //@NotEmpty(message = "Email should not be blank.") @Email
    private String email;

    @NotEmpty(message = "Phone should not be blank.")
    //@Size(min = 5, max = 8, message = "Password length should be between 5 to 8 Characters.")
    private String telephone;


    public String getEmail() {
        return email;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public String getFirstname() {
        return firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

}

我认为属性文件不是必需的,但我添加了它

属性文件:

NotEmpty.user.firstname=User Name can not be blank.
Size.user.name=User Name must be between 5 to 20 characters
Min.user.age= Minimum age must be 5 years
Size.user.location=Location must be between 5 to 50 characters

我哪里做错了

【问题讨论】:

  • 由于您自己的错误行为,现在不再出现错误。你正在做return new ModelAndView("contact", "command",contact);,它有效地破坏了带有错误的完全填充的模型,只留下一个空模型。不要那样做。最简单的方法是只返回一个String,它会导致视图呈现(如果成功,只需进行重定向)。如果您真的想返回 ModelAndView,请针对错误情况执行类似 new ModelAndView("contact", result.getModel()); 的操作。
  • 我已经更改了如下代码但仍然没有运气.. :( if(result.hasErrors()) { logger.warn("Requested Fields Has Errors"); logger.error("字段错误计数:"+result.getFieldErrorCount()); return new ModelAndView("contact", result.getModel()); }else{ logger.warn("Requested Fields Has No Errors"); return new ModelAndView("contact ", "命令", 联系人); }
  • 请再次阅读我的评论,不要将代码发布为 cmets。基本上你已经修复了错误的路径。
  • 另外,您的 @SessionAttributes 什么也不做,将您的 Contact 添加为 command 也无济于事,因为它应该命名为 contact 而不是 command。跨度>
  • 好的,我现在明白了,在这两种情况下,我都返回 return "redirect:contact.html";如何在 jsp 中显示错误消息,所以我想我错过了一些地方并且我接近逻辑@Denium 你能帮忙吗

标签: spring validation model-view-controller


【解决方案1】:
@Controller
public class ContactController {

    private static final Logger logger = Logger.getLogger(ContactController.class);

    @RequestMapping(value = "/addContact", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("command") @Valid Contact contact, BindingResult result) {
        logger.info("Add Contact is Being Executing");
        if(result.hasErrors()) {
            return "contact";
        }else{
            return "redirect:/contact";
        }
    }

    @ModelAttribute("command")
    public Contact formBackingObject() {
        return new Contact();
    }

    @RequestMapping("/contact")
    public String showContacts() {
        logger.warn("Contact Page is Being Executed");
        return "contact";
        return new ModelAndView("contact", "command", new Contact());
    }
}

除非你需要,否则不要乱用模型。此外,您在@ModelAttribute 中使用了错误的参数应该是command 而不是contact。删除了@SessionAttributes,因为它在这里什么都不做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 2012-04-28
    • 2014-09-23
    • 2012-06-21
    • 2012-01-21
    相关资源
    最近更新 更多