如何在JSF中创建一个选择列表?使用JS/jQuery尝试移动了项目,但提交了“验证错误:值无效"错误. [英] How to create a picklist in JSF? Tried moving items using JS/jQuery, but submit errors with "Validation Error: Value is not valid"

查看:108
本文介绍了如何在JSF中创建一个选择列表?使用JS/jQuery尝试移动了项目,但提交了“验证错误:值无效"错误.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JSF 2.0创建Web应用程序,在该应用程序中,我分配用户以查看项目.为此,我有两个清单.具有未分配该项目的用户的第一列表和具有分配该项目的用户的列表B.而且我们可以交换数据.

I am creating web application using JSF 2.0 where I am assigning users to view projects. For that I have two list. First list that have users who are not assigned that project and list B have users who have assigned that project. And we can interchange the data.

我的代码是

<t:selectManyListbox id="sourceCars"  style="width: 40%;"
                     value="#{PersonalInformationDataBean.listOfUsers}" size="10">
    <t:selectItems value="#{PersonalInformationDataBean.showAllMyRemData()}" var="t"
                   itemLabel="#{t.title}" itemValue="#{t.status}"/>
</t:selectManyListbox>

<span>
    <input type="button" value=" >> " id="dbleMeRight"/>
    <input type="button" value=" &lt;&lt; " id="dbleMeLeft"/>
</span>

<t:selectManyListbox id="targetCars"  style="width: 40%;"
                     value="#{PersonalInformationDataBean.listOfUsers}" size="10">
    <t:selectItems value="#{PersonalInformationDataBean.showAllMyData()}" var="n"
                   itemLabel="#{n.title}" itemValue="#{n.status}"/>
</t:selectManyListbox>

<h:commandButton value="Save Edited Project Info." action="#{PersonalInformationDataBean.editPatentData(MyLogin.loginname)}" />

其中t是xmlns:t="http://myfaces.apache.org/tomahawk".

PersonalInformationDataBean.java

private List<String> listOfUsers = new ArrayList<String>();
private List<String> listOfUsers002 = new ArrayList<String>();
private List<CommonBean01> listOfListUsers = new ArrayList<CommonBean01>();
private List<CommonBean01> listOfListUsers002 = new ArrayList<CommonBean01>();

// above getter and setters

Iterator itr = listOfUsers.iterator();
System.out.println("list of usersssss == " + listOfUsers);

while (itr.hasNext()) {
    psmtt = conn.prepareStatement("INSERT INTO patentInvite (invitedWhom, patentId, personalInfoId) VALUES (?,?,?)");
    String inviteWhom = itr.next().toString();
    System.out.println("to who we have invited is " + inviteWhom);
    psmtt.setString(1, inviteWhom);
    psmtt.setLong(2, patentId);
    psmtt.setLong(3, personalInfoId);
    psmtt.execute();

    System.out.println("Data entered is == " + inviteWhom + "==" + patentId + "==" + personalInfoId + "==");
}

public List<CommonBean01> showAllMyRemData() {
    try {
        CommonBean01 commonBean = new CommonBean01();
        listOfListUsers = new ArrayList<CommonBean01>();
        ConnectToDatabase db = new ConnectToDatabase();
        Connection conn = db.makeconnection();


        PreparedStatement psmt = conn.prepareStatement("SELECT * FROM patentInvite WHERE patentId=?");
        System.out.println("patent id here is " + patentId);
        psmt.setLong(1, patentId);
        ResultSet rs = psmt.executeQuery(), rs2 = null;
        PreparedStatement pstt = null;

        int dd = 0;
        String listOfUser = "";
        int myCounter = 0;
        while (rs.next()) {
            if (myCounter==0) {
                listOfUser = "'" + rs.getString(2) + "'"; 
            } else {
                listOfUser = listOfUser + ",'" + rs.getString(2) + "'";
            }
            myCounter++;
        }

        System.out.println("id selected are :: " + listOfUser);

        psmt = conn.prepareStatement("SELECT userid, fullName, userType FROM userDetails WHERE userid NOT IN (" + listOfUser + ")");
        rs = psmt.executeQuery();

        listOfListUsers = new ArrayList<CommonBean01>();
        while (rs.next()) {
            commonBean = new CommonBean01();
            commonBean.setStatus(rs.getString(1));
            commonBean.setTitle(rs.getString(2) + " [" + rs.getString(3) + "]");
            listOfListUsers.add(commonBean);
            System.out.println("wat say....(" + rs.getString(1) + ") -- " + rs.getString(2) + "");
        }
        return listOfListUsers;
    } catch (Exception e) {
        System.out.println("Exception = " + e);
        return null;
    }
}

public List<CommonBean01> showAllMyData() {
    try {
        CommonBean01 commonBean = new CommonBean01();
        listOfListUsers = new ArrayList<CommonBean01>();
        ConnectToDatabase db = new ConnectToDatabase();
        Connection conn = db.makeconnection();

        PreparedStatement psmt = conn.prepareStatement("SELECT * FROM patentInvite WHERE patentId=?");
        System.out.println("patent id here is " + patentId);
        psmt.setLong(1, patentId);
        ResultSet rs = psmt.executeQuery(), rs2 = null;
        PreparedStatement pstt = null;
        listOfListUsers = new ArrayList<CommonBean01>();

        while (rs.next()) {
            System.out.println("");
            pstt = conn.prepareStatement("SELECT userid, fullName, userType FROM userDetails WHERE userid=?");
            pstt.setString(1, rs.getString(2));
            System.out.println("setting id for " + rs.getString(1));
            rs2 = pstt.executeQuery();

            int dd = 0;
            while (rs2.next()) {
                System.out.println("inside data " + rs2.getString(2));
                commonBean = new CommonBean01();
                commonBean.setStatus(rs2.getString(1));
                commonBean.setTitle(rs2.getString(2) + " [" + rs2.getString(3) + "]");
                listOfListUsers.add(commonBean);
                System.out.println("wat say here....(" + rs2.getString(1) + ") -- " + rs2.getString(2) + "");
            }
        }
        return listOfListUsers;
    } catch (Exception e) {
        System.out.println("Exception = " + e);
        return null;
    }
}


CommonBean01.java

public class CommonBean01 {
    private String title;
    private String status;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final CommonBean01 other = (CommonBean01) obj;
        if ((this.status == null) ? (other.status != null) : !this.status.equals(other.status)) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 89 * hash + (this.status != null ? this.status.hashCode() : 0);
        return hash;
    }
}


现在,当我将用户从左列表移到右列表并单击Save Edit Info按钮时,出现错误,显示为targetCars: Validation Error: Value is not valid.


Now when I take user from left list to right list and click Save Edit Info button, I get error as targetCars: Validation Error: Value is not valid.

注意:

当我不更改任何列表并单击Save Edit Info时,它会很好地工作.

When I don't change any list and click Save Edit Info, it works well.

知道为什么我会收到此错误吗?

Any idea why I am getting this error?

我做了以下更改

<t:selectManyListbox id="sourceCars"  style="width: 40%;"
                     value="#{PersonalInformationDataBean.listOfUsers002}" size="10">
    <t:selectItems value="#{PersonalInformationDataBean.showAllMyRemData()}" var="t"
                   itemLabel="#{t.title}" itemValue="#{t.status}"/>
</t:selectManyListbox>


public List<CommonBean01> showAllMyRemData() {
    try {
        CommonBean01 commonBean = new CommonBean01();
        listOfListUsers002 = new ArrayList<CommonBean01>();
        ConnectToDatabase db = new ConnectToDatabase();
        Connection conn = db.makeconnection();


        PreparedStatement psmt = conn.prepareStatement("SELECT * FROM patentInvite WHERE patentId=?");
        System.out.println("patent id here is " + patentId);
        psmt.setLong(1, patentId);
        ResultSet rs = psmt.executeQuery(), rs2 = null;
        PreparedStatement pstt = null;

        int dd = 0;
        String listOfUser = "";
        int myCounter = 0;
        while (rs.next()) {
            if (myCounter==0) {
                listOfUser = "'" + rs.getString(2) + "'"; 
            } else {
                listOfUser = listOfUser + ",'" + rs.getString(2) + "'";
            }
            myCounter++;
        }

        System.out.println("id selected are :: " + listOfUser);

        psmt = conn.prepareStatement("SELECT userid, fullName, userType FROM userDetails WHERE userid NOT IN (" + listOfUser + ")");
        rs = psmt.executeQuery();

        listOfListUsers002 = new ArrayList<CommonBean01>();
        while (rs.next()) {
            commonBean = new CommonBean01();
            commonBean.setStatus(rs.getString(1));
            commonBean.setTitle(rs.getString(2) + " [" + rs.getString(3) + "]");
            listOfListUsers002.add(commonBean);
            System.out.println("wat say....(" + rs.getString(1) + ") -- " + rs.getString(2) + "");
        }
        return listOfListUsers002;
    } catch (Exception e) {
        System.out.println("Exception = " + e);
        return null;
    }
}

我仍然遇到相同的错误.

still I am getting same error.

用于移动项目的jQuery代码如下.

jQuery code to move items are as below.

$(function() {
    var  sourceCars=$('#sourceCars option').clone();
    $('#filterDis').change(function() {
        var val = $(this).val();
        alert("changed me=="+val+"==");
        $('#sourceCars').empty();
        alert("changed me=="+sourceCars+"==");
        sourceCars.filter(function(idx, el) {
            var found=false;
            $('#targetCars option').each(function(){
                if ($(this).val()===$(el).text())
                    found=true;
            });
            alert(found);

            if(found)
                return false;

            return val === 'ALL' || $(el).text().indexOf('[' + val + ']') >= 0;
        }).appendTo('#sourceCars');
        $("#targetCars option").attr("selected", "selected");
    });

    $('#sourceCars').dblclick(function() {
        $('#sourceCars option:selected').appendTo('#targetCars');
        $("#targetCars option").attr("selected", "selected");
    });

    $('#dbleMeRight').click(function() {
        $('#sourceCars option:selected').appendTo('#targetCars');
        $("#targetCars option").attr("selected", "selected");
    });

    $('#targetCars').dblclick(function() {

        var targetList=$('#targetCars option:selected');
        var filterVal= $('#filterDis').val();
        if( filterVal === 'ALL' || targetList.text().indexOf('[' + filterVal + ']') >= 0)
            targetList.appendTo('#sourceCars');
        else
            targetList.remove();
        var foption = $('#sourceCars option:first');
        var soptions = $.makeArray($('#sourceCars option:not(:first)')).sort(function(a, b) {
            return a.text == b.text ? 0 : a.text &lt; b.text ? -1 : 1
        });
        $('#sourceCars').html(soptions).prepend(foption);
        foption.attr("selected", true).siblings("option").removeAttr("selected");
        $("#targetCars option").attr("selected", "selected");
    });

    $('#dbleMeLeft').click(function() {

        var targetList=$('#targetCars option:selected');
        var filterVal= $('#filterDis').val();
        if( filterVal === 'ALL' || targetList.text().indexOf('[' + filterVal + ']') >= 0)
            targetList.appendTo('#sourceCars');
        else
            targetList.remove();
        var foption = $('#sourceCars option:first');
        var soptions = $.makeArray($('#sourceCars option:not(:first)')).sort(function(a, b) {
            return a.text == b.text ? 0 : a.text &lt; b.text ? -1 : 1
        });
        $('#sourceCars').html(soptions).prepend(foption);
        foption.attr("selected", true).siblings("option").removeAttr("selected");
        $("#targetCars option").attr("selected", "selected");
    });

});

注意:如果我将项目从列表B(右)移到列表A(左),则可以正常工作.但是,当我将项目从列表A(左)移到列表B(右)时,会出现此错误.

NOTE: If I move item from List B (Right) to List A (left), it works fine. BUT WHEN I move item from List A (Left) to List B (right), I get this error.

推荐答案

至此,您的具体问题是由使用JavaScript/jQuery而不是JSF填充列表框项的错误引起的.这样就永远不会使JSF知道JavaScript添加的新项目.您需要使用JSF而不是JavaScript/jQuery填充列表框项目.

To the point, your concrete problem is caused by the mistake that you filled listbox items using JavaScript/jQuery instead of JSF. This way JSF is never been made aware of the new items added by JavaScript. You need to fill the listbox items using JSF instead of JavaScript/jQuery.

当您提交带有UISelectOne/UISelectMany组件的表单时,JSF将始终将提交的值与<f:selectItem(s)>中的可用项目列表进行比较.如果提交的值未包含在可用项目列表中,那么您将完全得到此Validation Error: Value is not valid错误.这是针对篡改/攻击请求的内置保护措施的一部分.客户端应该不能提交服务器未指定的项目.

When you submit a form with an UISelectOne/UISelectMany component, then JSF will always compare the submitted value to the list of available items from <f:selectItem(s)>. If the submitted value is not contained in the list of available items, then you will get exactly this Validation Error: Value is not valid error. This is part of builtin safeguard against tampered/attacked requests. The client should not be able to submit a item which the server has not specified.

更改JavaScript/jQuery方面的可用项目并不会自动地更改JSF <f:selectItems>方面的可用项目.您确实需要在JSF端更改可用的项目.您可以轻松地使用JSF 2.x ajax功能.这是一个具体的启动示例:

Changing the available items in JavaScript/jQuery side does not automagically also change the available items in JSF <f:selectItems> side as well. You really need to change the available items in JSF side. You can easily use the JSF 2.x ajax powers for this. Here's a concrete kickoff example:

<h:form>
    <h:panelGrid columns="3">
        <h:selectManyListbox id="left" value="#{bean.leftSelected}">
            <f:selectItems value="#{bean.leftAvailable}" />
            <f:ajax event="dblclick" render="left right" listener="#{bean.leftToRight}" />
        </h:selectManyListbox>
        <h:panelGroup>
            <h:commandButton value="left to right">
                <f:ajax execute="left" render="left right" listener="#{bean.leftToRight}" />
            </h:commandButton>
            <br/>
            <h:commandButton value="right to left">
                <f:ajax execute="right" render="left right" listener="#{bean.rightToLeft}" />
            </h:commandButton>
        </h:panelGroup>
        <h:selectManyListbox id="right" value="#{bean.rightSelected}">
            <f:selectItems value="#{bean.rightAvailable}" />
            <f:ajax event="dblclick" render="left right" listener="#{bean.rightToLeft}" />
        </h:selectManyListbox>
    </h:panelGrid>
</h:form>

使用

@ManagedBean
@ViewScoped
public class Bean {

    private List<String> leftSelected;
    private List<String> leftAvailable;
    private List<String> rightSelected;
    private List<String> rightAvailable;

    @PostConstruct
    public void init() {
        leftAvailable = new ArrayList<String>(Arrays.asList("one", "two", "three", "four", "five"));
        rightAvailable = new ArrayList<String>();
    }

    public void leftToRight() {
        leftAvailable.removeAll(leftSelected);
        rightAvailable.addAll(leftSelected);
        leftSelected = null;
    }

    public void rightToLeft() {
        rightAvailable.removeAll(rightSelected);
        leftAvailable.addAll(rightSelected);
        rightSelected = null;
    }

    // Add/generate getters+setters. Note: the "available" lists doesn't need setters.
}

仅此而已.无需JS/jQuery混乱.使用自定义非字符串对象时,请不要忘记提供适当的转换器和equals()方法.

That's all. No JS/jQuery mess necessary. When using custom non-string objects don't forget to provide a proper converter and equals() method.

  • What is the need of JSF, when UI can be achieved from CSS, HTML, JavaScript, jQuery?
  • Jsf : Validation error value is not valid for SelectOneMenu
  • JSF Validation Error While Using Custom Converter

这篇关于如何在JSF中创建一个选择列表?使用JS/jQuery尝试移动了项目,但提交了“验证错误:值无效"错误.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆