字段为空时不显示错误消息

时间:2019-12-15 16:50:53

标签: spring-mvc jstl

Spring MVC

这是我的控制器:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
  @Controller
public class CategoryController {
    private static final Logger logger = LoggerFactory.getLogger(CategoryController.class);

    private CategoryService categoryService;

    @Autowired(required = true)
    @Qualifier(value = "categoryService")
    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    @Autowired
    @Qualifier("categoryValidator")
    private Validator validator;

    @InitBinder
    private void initBinder(WebDataBinder binder) {
        binder.setValidator(validator);
    }

    @RequestMapping(value = "/categories", method = RequestMethod.GET)
    public String listCategories(Model model) {
        List<Category> listCategories = this.categoryService.getCategoryList();
        model.addAttribute("category", new Category());
        model.addAttribute("listCategories", listCategories);
        return "category";
    }

    @RequestMapping(value = "/category/add", method = RequestMethod.POST)
    public String addCategory(@ModelAttribute("category") @Validated Category category, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return "redirect:/categories";
        }
        if (category.getId() == 0) {
            category.setCreatedAt(System.currentTimeMillis());
            categoryService.addCategory(category);
        } else {
            category.setUpdatedAt(System.currentTimeMillis());
            categoryService.updateCategory(category);
        }
        return "redirect:/categories";
    }

    @RequestMapping("/edit/{id}")
    public String editCategory(@PathVariable("id") long id, Model model) {
        model.addAttribute("category", categoryService.getCategoyById(id));
        model.addAttribute("listCategories", this.categoryService.getCategoryList());
        return "category";
    }

    @RequestMapping("/remove/{id}")
    public String removeCategory(@PathVariable("id") long id) {
        categoryService.removeCategory(id);
        return "redirect:/categories";
    }

这是我的验证器:

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import ru.otus.sd.eshop.model.Category;

public class CategoryValidator implements Validator {

    public boolean supports(Class<?> clazz) {
        return Category.class.isAssignableFrom(clazz);
    }

    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "required.name", "Field name is required");
    }

}

这里是jsp:

<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<jsp:useBean id="createdAtDateValue" class="java.util.Date" />
<jsp:useBean id="updatedAtDateValue" class="java.util.Date" />
<c:set var='datePattern' value="dd.MM.yyyy HH:mm" />
<%@ page session="false"%>
<html>
<head>
<title><spring:message code="category.page" /></title>
<style type="text/css">
.redtext {
    color: red;
}
</style>
</head>
<body>
    <h1><spring:message code="add.category" /></h1>

    <c:url var="addAction" value="/category/add"></c:url>

    <form:form action="${addAction}" commandName="category">
        <form:errors path="*" class="redtext" element="div" />
        <table>
            <c:if test="${!empty category.name}">
                <tr>
                    <td><form:label path="id">
                            <spring:message text="ID" />
                        </form:label></td>
                    <td><form:input path="id" readonly="true" size="8"
                            disabled="true" /> <form:hidden path="id" /></td>
                </tr>
            </c:if>
            <tr>
                <td><form:label path="name">
                        <spring:message text="Name" />
                    </form:label></td>
                <td><form:input path="name" /></td>
                <td><form:errors path="name" class="redtext" /></td>
            </tr>
            <tr>
                <c:if test="${!empty category.name}">
                    <td><form:label path="createdAt">
                            <spring:message text="Created at" />
                        </form:label></td>
                    <jsp:setProperty name="createdAtDateValue" property="time"
                        value="${category.createdAt}" />
                    <td><form:input path="createdAt" value="${createdAtDateValue}"
                            pattern="${datePattern}" readonly="true" disabled="true" /> <form:hidden
                            path="createdAt" /></td>
                </c:if>
            </tr>
            <tr>
                <td colspan="2"><c:if test="${!empty category.name}">
                        <input type="submit"
                            value="<spring:message text="Edit Category"/>" />
                    </c:if> <c:if test="${empty category.name}">
                        <input type="submit" value="<spring:message text="Add Category"/>" />
                    </c:if></td>
            </tr>
        </table>
    </form:form>
    <br>
    <h3>Category List</h3>
    <c:if test="${!empty listCategories}">
        <table class="tg">
            <tr>
                <th width="80">ID</th>
                <th width="120">Name</th>
                <th width="120">Created At</th>
                <th width="120">Updated At</th>
                <th width="60"></th>
                <th width="60"></th>
            </tr>
            <c:forEach items="${listCategories}" var="category">
                <jsp:setProperty name="createdAtDateValue" property="time"
                    value="${category.createdAt}" />
                <c:if test="${not empty category.updatedAt}">
                    <jsp:setProperty name="updatedAtDateValue" property="time"
                        value="${category.updatedAt}" />
                </c:if>
                <tr>
                    <td>${category.id}</td>
                    <td>${category.name}</td>
                    <td><fmt:formatDate value="${createdAtDateValue}"
                            pattern="${datePattern}" /></td>
                    <c:if test="${empty category.updatedAt}">
                        <td />
                    </c:if>
                    <c:if test="${not empty category.updatedAt}">
                        <td><fmt:formatDate value="${updatedAtDateValue}"
                                pattern="${datePattern}" /></td>
                    </c:if>
                    <td><a href="<c:url value='/edit/${category.id}' />">Edit</a></td>
                    <td><a href="<c:url value='/remove/${category.id}' />">Delete</a></td>
                </tr>
            </c:forEach>
        </table>
    </c:if>
    <p>
        <spring:message code="category.count"
            arguments="${fn:length(listCategories)}" />
    </p>
</body>
</html>

,这里是servlet-context.xml:

  <beans:bean id="categoryDAO"
        class="com.myproject.eshop.dao.CategoryDAOImpl">
        <beans:property name="sessionFactory"
            ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean>
    <beans:bean id="categoryService"
        class="com.myproject.eshop.service.CategoryServiceImpl">
        <beans:property name="categoryDAO" ref="categoryDAO"></beans:property>
    </beans:bean>
    <context:component-scan
        base-package="com.myproject.eshop" />

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

    <beans:bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <beans:property name="sessionFactory"
            ref="hibernate4AnnotatedSessionFactory" />
    </beans:bean>

    <beans:bean id="categoryValidator"
        class="com.myproject.eshop.validator.CategoryValidator" />

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

当我打开

http://localhost:8080/eshop/categories

此处结果:

enter image description here

很好。

现在,我添加了一些新类别,然后按添加类别

此处结果:

enter image description here

很好,这是正确的。

但是,如果尝试添加空白类别,则必须显示错误消息(红色文本)。 但是错误消息(必填字段)未显示:

enter image description here

在控制器成功调用中:

if (bindingResult.hasErrors()) {
            return "redirect:/categories";
        }

必须从jsp中显示此内容:

<td><form:errors path="name" class="redtext" /></td>

但错误消息未显示。

0 个答案:

没有答案