복붙노트

[SPRING] 동적으로 생성 된 필드 서버 측의 유효성 검사 방법

SPRING

동적으로 생성 된 필드 서버 측의 유효성 검사 방법

Spring 3.1을 사용하여 웹 애플리케이션을 개발했다.

하나의 모듈에서 많은 OperationParameter 객체를 가진 하나의 Operation 객체를 저장해야합니다. 그래서보기에서 특정 Operation을위한 OperationParameters를 생성하기 위해 사용자를위한 추가 버튼을 제공했습니다.

두 모델 모두 최대 절전 매핑을 가지고 있으며 연산과 연산 매개 변수 사이에 일대 다 많은 관계가 있습니다. 그리고 Operation 모델에는 사용자가 동적으로 추가 한 OperationParameters로 새로운 Operation이 생성 될 때 데이터베이스에 삽입 될 OperationParameters List가 있습니다.

유효성 검사를 사용하지 않으면 정상적으로 작동합니다. Operation 모델에 삽입 작업을 수행하면 OperationParameter의 목록도 OperationParameter 테이블에 삽입됩니다.

내 질문은 OperationParameter 필드에 대한 서버 측 유효성 검사를 어떻게 수행 할 수 있습니까? 유효성 검사가 오류로 완료되면 특정 OperationParameter 필드의 오류를 어떻게 표시합니까?

Operation.java

    package com.abcprocure.servicerepo.model;
// Generated Feb 9, 2012 11:30:06 AM by Hibernate Tools 3.2.1.GA


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

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.apache.commons.collections.FactoryUtils;
import org.apache.commons.collections.list.LazyList;

@Entity
@Table(name="Operations"
    ,schema="dbo"

)
public class Operations  implements java.io.Serializable {


     private int operationId;
     @Embedded
     private Services services;
     private String operationName;
     private String isHqlsql;
     private String isMultipleTables;
     private String listOfTablesAffected;
     private String hqlQuery;
     private String typeOfOperation;
     private String operationDetail;
     private String inputVariables;
     private String outputparamdatatype;
     private String isCountQuery;
     private String isDynamicWhereQry;
     private String isPaginationRequired;
     private String biInputParameters;
    private List<OperationParameters> operationParameterses = LazyList
            .decorate(new ArrayList<OperationParameters>(),
                    FactoryUtils.instantiateFactory(OperationParameters.class));

    public Operations() {
    }


    public Operations(int operationId, Services services, String operationName) {
        this.operationId = operationId;
        this.services = services;
        this.operationName = operationName;
    }
    public Operations(int operationId, Services services, String operationName, String isHqlsql, String isMultipleTables, String listOfTablesAffected, String hqlQuery, String typeOfOperation, String operationDetail, String inputVariables, String outputparamdatatype, String isCountQuery, List operationParameterses) {
       this.operationId = operationId;
       this.services = services;
       this.operationName = operationName;
       this.isHqlsql = isHqlsql;
       this.isMultipleTables = isMultipleTables;
       this.listOfTablesAffected = listOfTablesAffected;
       this.hqlQuery = hqlQuery;
       this.typeOfOperation = typeOfOperation;
       this.operationDetail = operationDetail;
       this.inputVariables = inputVariables;
       this.outputparamdatatype = outputparamdatatype;
       this.isCountQuery = isCountQuery;
       this.operationParameterses = operationParameterses;
    }

    @Id 
    @GeneratedValue
    @Column(name="operationId", unique=true, nullable=false)
    public int getOperationId() {
        return this.operationId;
    }

    public void setOperationId(int operationId) {
        this.operationId = operationId;
    }

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="serviceId", nullable=false)
    public Services getServices() {
        return this.services;
    }

    public void setServices(Services services) {
        this.services = services;
    }

    @Column(name="operationName", nullable=false, length=250)
    public String getOperationName() {
        return this.operationName;
    }

    public void setOperationName(String operationName) {
        this.operationName = operationName;
    }

    @Column(name="isHQLSQL", length=50)
    public String getIsHqlsql() {
        return this.isHqlsql;
    }

    public void setIsHqlsql(String isHqlsql) {
        this.isHqlsql = isHqlsql;
    }

    @Column(name="isMultipleTables", length=50)
    public String getIsMultipleTables() {
        return this.isMultipleTables;
    }

    public void setIsMultipleTables(String isMultipleTables) {
        this.isMultipleTables = isMultipleTables;
    }

    @Column(name="listOfTablesAffected", length=500)
    public String getListOfTablesAffected() {
        return this.listOfTablesAffected;
    }

    public void setListOfTablesAffected(String listOfTablesAffected) {
        this.listOfTablesAffected = listOfTablesAffected;
    }

    @Column(name="hqlQuery")
    public String getHqlQuery() {
        return this.hqlQuery;
    }

    public void setHqlQuery(String hqlQuery) {
        this.hqlQuery = hqlQuery;
    }

    @Column(name="typeOfOperation", length=50)
    public String getTypeOfOperation() {
        return this.typeOfOperation;
    }

    public void setTypeOfOperation(String typeOfOperation) {
        this.typeOfOperation = typeOfOperation;
    }

    @Column(name="operationDetail")
    public String getOperationDetail() {
        return this.operationDetail;
    }

    public void setOperationDetail(String operationDetail) {
        this.operationDetail = operationDetail;
    }

    @Column(name="inputVariables", length=5000)
    public String getInputVariables() {
        return this.inputVariables;
    }

    public void setInputVariables(String inputVariables) {
        this.inputVariables = inputVariables;
    }

    @Column(name="outputparamdatatype", length=50)
    public String getOutputparamdatatype() {
        return this.outputparamdatatype;
    }

    public void setOutputparamdatatype(String outputparamdatatype) {
        this.outputparamdatatype = outputparamdatatype;
    }

    @Column(name="isCountQuery", length=10)
    public String getIsCountQuery() {
        return this.isCountQuery;
    }

    public void setIsCountQuery(String isCountQuery) {
        this.isCountQuery = isCountQuery;
    }

    public String getIsDynamicWhereQry() {
        return isDynamicWhereQry;
    }


    public void setIsDynamicWhereQry(String isDynamicWhereQry) {
        this.isDynamicWhereQry = isDynamicWhereQry;
    }


    public String getIsPaginationRequired() {
        return isPaginationRequired;
    }


    public void setIsPaginationRequired(String isPaginationRequired) {
        this.isPaginationRequired = isPaginationRequired;
    }

    public String getBiInputParameters() {
        return biInputParameters;
    }


    public void setBiInputParameters(String biInputParameters) {
        this.biInputParameters = biInputParameters;
    }

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="operations")
    public List<OperationParameters> getOperationParameterses() {
        return this.operationParameterses;
    }

    public void setOperationParameterses(List<OperationParameters> operationParameterses) {
        this.operationParameterses = operationParameterses;
    }

}

OperationParameters.java

package com.abcprocure.servicerepo.model;

// Generated Feb 9, 2012 11:30:06 AM by Hibernate Tools 3.2.1.GA


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="OperationParameters"
    ,schema="dbo"

)
public class OperationParameters  implements java.io.Serializable {


     private int parameterId;
     private Operations operations;
     private String inputOutputParamName;
     private String inputOutputParamType;
     private String inputOutputParamDataType;

    public OperationParameters() {
    }

    public OperationParameters(int parameterId, Operations operations, String inputOutputParamName, String inputOutputParamType, String inputOutputParamDataType) {
       this.parameterId = parameterId;
       this.operations = operations;
       this.inputOutputParamName = inputOutputParamName;
       this.inputOutputParamType = inputOutputParamType;
       this.inputOutputParamDataType = inputOutputParamDataType;
    }

    @Id 
    @GeneratedValue
    @Column(name="parameterId", unique=true, nullable=false)
    public int getParameterId() {
        return this.parameterId;
    }

    public void setParameterId(int parameterId) {
        this.parameterId = parameterId;
    }
@ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="operationId", nullable=false)
    public Operations getOperations() {
        return this.operations;
    }

    public void setOperations(Operations operations) {
        this.operations = operations;
    }

    @Column(name="inputOutputParamName", nullable=false, length=250)
    public String getInputOutputParamName() {
        return this.inputOutputParamName;
    }

    public void setInputOutputParamName(String inputOutputParamName) {
        this.inputOutputParamName = inputOutputParamName;
    }

    @Column(name="inputOutputParamType", nullable=false, length=250)
    public String getInputOutputParamType() {
        return this.inputOutputParamType;
    }

    public void setInputOutputParamType(String inputOutputParamType) {
        this.inputOutputParamType = inputOutputParamType;
    }

    @Column(name="inputOutputParamDataType", nullable=false, length=250)
    public String getInputOutputParamDataType() {
        return this.inputOutputParamDataType;
    }

    public void setInputOutputParamDataType(String inputOutputParamDataType) {
        this.inputOutputParamDataType = inputOutputParamDataType;
    }




}

새로운 Operation을 추가하기위한 post 요청을 제공하는 Controller 메소드.

/**
     * Method that will serve the post request to add the operation and operation parameters submitted by the user.
     * @param operations
     * @param map
     * @return {@link String} The view name that will redirect to the get request to display the previous page with newly entered operation in the list. 
     */
    @RequestMapping(value="/add", method=RequestMethod.POST)
    public String addOperations(@ModelAttribute Operations operations, ModelMap map) {
        operations.getOperationParameterses().removeAll(Collections.singleton(null));

        for(int i=0; i<operations.getOperationParameterses().size(); i++) {
            System.out.println("parameterName :: " + ((OperationParameters)operations.getOperationParameterses().get(i)).getInputOutputParamName());
            if(((OperationParameters)operations.getOperationParameterses().get(i)).getInputOutputParamName() == null || "".equalsIgnoreCase((((OperationParameters)operations.getOperationParameterses().get(i))).getInputOutputParamName())) {
                operations.getOperationParameterses().remove(i);
                System.out.println("empty parameter removed....");
            }
        }

        return "redirect:/operations/" + operations.getServices().getServiceId();
    }

이와 관련하여 좋은 제안이나 예는 나에게 큰 도움이 될 것입니다. :)

**

**

또한 필드 배열을 검사하고 jsp 파일에서 오류를 다시 표시 할 수 있는지 여부를 알고 싶습니다.

제발 도와주세요.

해결법

  1. ==============================

    1.데이터 유형을 기반으로 OperationParameters의 유효성을 검사하는 도우미 클래스를 만들 수 있습니다. 문자열의 경우 null 또는 빈 문자열 등을 확인하십시오. 확인 클래스에는 유효한 전자 메일 주소와 같은 컨텍스트 확인도있을 수 있습니다.

    데이터 유형을 기반으로 OperationParameters의 유효성을 검사하는 도우미 클래스를 만들 수 있습니다. 문자열의 경우 null 또는 빈 문자열 등을 확인하십시오. 확인 클래스에는 유효한 전자 메일 주소와 같은 컨텍스트 확인도있을 수 있습니다.

    이것을 가지고 작업 객체를 저장하기 전에 OperationParameters의 Operations 목록을 반복하고, 데이터 유형 및 / 또는 정보의 컨텍스트를 포함하는 필드 (예 : 전자 메일, 평일)를 확인하고 적절한 유효성 검사를 호출합니다. 너의 도우미 클래스.

    불일치를 잡으면 그냥 설명하는 사용자 정의 예외를 throw하십시오. 코드를 처리하는 코드 부분은 잘못된 필드가있는 페이지로 json을 반환 할 수 있으며, 사용자에게 피드백을 제공합니다 (예 : 오류 메시지가있는 필드의 빨간색 텍스트).

  2. ==============================

    2.브레인 스토밍에서 일주일 후 직접 솔루션을 찾았습니다. 마침내 나는 이것을 성취하게되어 정말 기쁩니다. :)

    브레인 스토밍에서 일주일 후 직접 솔루션을 찾았습니다. 마침내 나는 이것을 성취하게되어 정말 기쁩니다. :)

    동적으로 생성 된 필드의 유효성을 검사하기 위해 서버 측에서 사용자 지정 유효성 검사를 수행해야합니다. 동적으로 생성 된 필드에 대해 Annotation 기반 유효성 검사를 사용하면 유효성 검사 후 컨트롤러 기능이 제공되지 않기 때문입니다.

    따라서 사용자 정의 유효성 검사를 수행 할 때마다 유효성 검사가 제어기 기능에서 호출됩니다. 그리고 거기에서 목록에 동적으로 생성 된 필드에 오류를 생성 할 수 있습니다.

    유효성 검사가 성공적이지 않으면 JSP 페이지로 돌아가서 양식에 오류를 표시해야합니다. 동적으로 생성 된 필드 값을 사용하여 오류와 함께 표시해야합니다.

    나는이 일이 같은 일을하기를 원하는 사람들을 도울 수 있기를 바랍니다.

  3. from https://stackoverflow.com/questions/10614718/how-to-validate-dynamically-generated-fields-server-side by cc-by-sa and MIT license