Spring: @Valid всегда возвращает False - PullRequest
0 голосов
/ 29 апреля 2019

Я новичок в Spring Framework.Я пытаюсь заставить @Valid работать.Привязка данных происходит правильно, но не проверка.hasErrors () всегда возвращает False в классе Controller.Пожалуйста, смотрите код ниже.

Я использую Spring 4.1.3 и валидатор Hibernate 6.0.16.

Context xml :

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">

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

    <context:property-placeholder location="classpath:/config.properties"/>
    <context:annotation-config />
    <mvc:annotation-driven />
    <context:component-scan base-package="com.personal, com.documentum" />
</beans>

Контроллер :

package com.personal.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.personal.search.model.SearchForm;
import com.personal.search.service.SearchService;

@Controller
public class SearchController {

    private SearchService service;

    @Autowired
    public SearchController(SearchService service) {
        this.service = service;
    }

    @RequestMapping(value="/", method=RequestMethod.GET)
    public String searchHome(Model model) {
        model.addAttribute(new SearchForm());
        return "search/search";
    }

    @RequestMapping(value="/", method=RequestMethod.POST)
    public String searchResults(@Valid SearchForm searchForm, BindingResult errors, Model model) {
        if (!errors.hasErrors()) {
            System.out.println(searchForm.getObjectName());
            model.addAttribute(service.getResults(searchForm));
        }
        return "search/search";
    }

}

Просмотр :

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<%@ page session="false" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <sf:form method="POST" commandName="searchForm">
        <sf:errors path="*" />
        <label>Enter Object Name:</label>
        <sf:input path="objectName"/><sf:errors path="objectName" /><br>
        <button type="submit" value="Submit">Submit</button>
    </sf:form>
    <h3>For your search term "${searchForm.objectName}" below are the results: </h3>
    <c:forEach items="${searchResultList}" var="searchResult" >
        <li>
            <div>
                <span>
                (<c:out value="${searchResult.objectName}" />,
                <c:out value="${searchResult.title}" />)</span>
            </div>
        </li>
    </c:forEach>
</body>
</html>

Модель :

Модель SearchForm:

package com.personal.search.model;

import javax.validation.constraints.NotBlank;

public class SearchForm {

    @NotBlank
    private String objectName;

    public SearchForm() {
    }

    public SearchForm(String objectName) {
        this.objectName = objectName;
    }

    public String getObjectName() {
        return objectName;
    }

    public void setObjectName(String objectName) {
        this.objectName = objectName;
    }

}

SearchResult Модель:

package com.personal.search.model;

public class SearchResult {

    private String objectName;
    private String title;

    public SearchResult() {
    }

    public String getObjectName() {
        return objectName;
    }
    public void setObjectName(String name) {
        this.objectName = name;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }



}

Сервис :

package com.personal.search.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.personal.search.dao.SearchDAO;
import com.personal.search.model.SearchForm;
import com.personal.search.model.SearchResult;

@Service
public class SearchService implements ISearchService {

    private SearchDAO dao;

    public SearchService() {
    }

    @Autowired
    public SearchService(SearchDAO dao) {
        this.dao = dao;
    }

    @Override
    public List<SearchResult> getResults(SearchForm searchform) {

        return dao.getSearchObjects(searchform);

    }



}

DAO :

package com.personal.search.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import com.documentum.com.DfClientX;
import com.documentum.fc.client.DfServiceException;
import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfCollection;
import com.documentum.fc.client.IDfQuery;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.IDfLoginInfo;
import com.personal.search.model.SearchForm;
import com.personal.search.model.SearchResult;

@Repository
public class SearchDAO {

    private String repository;
    private String userName;
    private String password;
    private IDfSessionManager sessionMgr = null;

    public SearchDAO() {

    }

    @Autowired
      public SearchDAO(
              @Value("${docbase.repository}") String repository,
              @Value("${docbase.user}") String userName,
              @Value("${docbase.password}") String password) 
      {
          this.repository = repository; 
          this.userName = userName; 
          this.password = password; 
          System.out.println(repository + " " + userName + " " + password);
      }


    /**
     * Creates a  IDfSessionManager
     */
    private IDfSessionManager getSessionManager()
    {
        // create a client object using a factory method in DfClientX
        DfClientX clientx = new DfClientX();
        IDfClient client;
        IDfSessionManager sessionMgr = null;
        try {

            client = clientx.getLocalClient();

            // call a factory method to create the session manager
            sessionMgr = client.newSessionManager();

            addIdentity(clientx, sessionMgr);


        } catch (DfException e) {
            e.printStackTrace();
        }

        return sessionMgr;

    }

    private void addIdentity(DfClientX clientx, IDfSessionManager sessionMgr)
    {
        // create an IDfLoginInfo object and set its fields
        IDfLoginInfo loginInfo = clientx.getLoginInfo();
        loginInfo.setUser(userName);
        loginInfo.setPassword(password);
        if (sessionMgr != null) {
            if (sessionMgr.hasIdentity(repository))
            {
                sessionMgr.clearIdentity(repository);
            }
        }
        try {
            sessionMgr.setIdentity(repository, loginInfo);
        } catch (DfServiceException e) {
            e.printStackTrace();
        }
    }

    public IDfSession getDBSession() {

        IDfSession sess = null;

        // Get a session using a factory method of session manager.
        try {
            sess = sessionMgr.getSession(repository);
        } catch (DfServiceException e) {
            System.out.println(e.getStackTraceAsString());
        }

        return sess;
    }

    public void releaseDBSession(IDfSession sess) {

          sessionMgr.release(sess);

    }


    public List<SearchResult> getSearchObjects(SearchForm searchform) {
        List<SearchResult> lst = new ArrayList<SearchResult>();
        this.sessionMgr = getSessionManager();
        IDfSession sess = null;
        try
        {
            sess = getDBSession();
            if (sess != null) {
                IDfQuery query = new DfClientX().getQuery();
                String dqlStr = "select object_name, title from dm_sysobject where object_name like '%"  + searchform.getObjectName() + "%'";
                System.out.println(dqlStr);
                query.setDQL(dqlStr);
                IDfCollection co = query.execute(sess, IDfQuery.DF_READ_QUERY);
                while (co.next()) {
                    SearchResult searchresult = new SearchResult();
                    searchresult.setObjectName(co.getString("object_name"));
                    searchresult.setTitle(co.getString("title"));
                    lst.add(searchresult);
                }
                if (co != null)
                    co.close();
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            if (sess != null)
                releaseDBSession(sess);
        }
        return lst;
    }

}

Я ожидаю, что вывод hasErrors () будет True.

1 Ответ

0 голосов
/ 30 апреля 2019

Это может быть потому, что вы определили проверку как,

@Null
@Size(min=1, max=30)
private String objectName;

Проверьте, если при отправке запроса в контроллер значение objectName NULL или пустая строка?

ДляСтрока, которую вы должны использовать @NotBlank, а не @Null

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...