简体   繁体   English

Spring MVC数据绑定-基本类型

[英]Spring MVC Data Binding - primitive types

I'm currently revising a web application, and I have questions about data binding. 我目前正在修改Web应用程序,并且对数据绑定有疑问。 I have a method that has been mapped with @RequestMapping, and in one of it's arguments I have a primitive integer type, something like this (the following code is basically a summary of my problem, not the actual code): 我有一个已使用@RequestMapping映射的方法,在其中一个参数中,我有一个原始整数类型,类似这样(以下代码基本上是我的问题的摘要,而不是实际的代码):

@RequestMapping(value = "/processSomething" , method = RequestMethod.GET)
public String processSomething(@ModelAttribute("myValue") int myValue)
{
   // Do something with "myValue".
}

When I run the web application, i get the following: 当我运行Web应用程序时,得到以下信息:

HTTP Status 500 - Request processing failed; HTTP状态500-请求处理失败; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [int]: No default constructor found; 嵌套的异常是org.springframework.beans.BeanInstantiationException:无法实例化bean类[int]:找不到默认的构造函数;默认值为0。 nested exception is java.lang.NoSuchMethodException: int.() 嵌套异常是java.lang.NoSuchMethodException:int。()

It makes me realize that data binding works only with objects. 这让我意识到数据绑定仅适用于对象。 I tried to change int with Integer, but I ended up getting something very similar: 我尝试使用Integer更改int,但最终得到了非常相似的信息:

HTTP Status 500 - Request processing failed; HTTP状态500-请求处理失败; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [java.lang.Integer]: No default constructor found; 嵌套的异常是org.springframework.beans.BeanInstantiationException:无法实例化bean类[java.lang.Integer]:没有找到默认的构造函数;它没有实例化。 nested exception is java.lang.NoSuchMethodException: java.lang.Integer.() 嵌套的异常是java.lang.NoSuchMethodException:java.lang.Integer。()

I know @ModelAttribute allows us to make data binding with the Spring MVC model, and if a model is not in there, it is created automatically by Spring and then it's returned. 我知道@ModelAttribute允许我们与Spring MVC模型进行数据绑定,如果模型不在其中,Spring会自动创建它,然后将其返回。 What am I doing wrong? 我究竟做错了什么? What I forgot to do? 我忘了做什么? Do I need to create a PropertyEditor for primitive types? 我需要为原始类型创建PropertyEditor吗?

The funny thing is that it works perfectly with @RequestParam, but I would not want the user to see the value of my property in the URL. 有趣的是,它可以与@RequestParam完美配合,但是我不希望用户在URL中看到我的属性的值。

NOTE : I'm currently using Spring Web MVC 4.1.1.RELEASE (with MAVEN) 注意 :我当前正在使用Spring Web MVC 4.1.1.RELEASE(与MAVEN一起使用)


UPDATE UPDATE

I did what was suggested by tofindabhishek user. 我做了tofindabhishek用户的建议。 I created a class with the name Inteiro (translated as Integer), and I am using it as @ModelAttribute, just like this: 我创建了一个名为Inteiro的类(翻译为Integer),并将其用作@ModelAttribute,如下所示:

@RequestMapping(value = "/usuarios" , method = RequestMethod.GET)
public String getUsuarios(
        Model model , 
        @RequestParam("pag")            int pagina ,                    
        @ModelAttribute("total")        Inteiro registros ,             
        @ModelAttribute("pesquisa")     CriterioBuilder criterio ,      
        @ModelAttribute("id_sexo_f")    Inteiro idSexF ,                
        @ModelAttribute("id_grupo_adm") Inteiro idGrpAdm )              
{
    // ...
}

The Inteiro class has basically just a single int primitive field with a public and empty constructor, and a set, get, equals and hashCode method. Inteiro类基本上只有一个int基本字段,带有一个公共和空的构造函数,以及一个set,get,equals和hashCode方法。 The previous problem appears to have been resolved, but when running my application, I came across this: 先前的问题似乎已经解决,但是在运行我的应用程序时,我遇到了以下问题:

HTTP Status 500 - javax.el.ELException: Cannot convert com.regra7.minhaapp.controle.wrap.Inteiro@3b of type class com.regra7.minhaapp.controle.wrap.Inteiro to class java.lang.Long HTTP状态500-javax.el.E​​LException:无法将类型com.regra7.minhaapp.controle.wrap.Inteiro类型的com.regra7.minhaapp.controle.wrap.Inteiro@3b转换为类java.lang.Long

Here's the Inteiro source code: 这是Inteiro的源代码:

public class Inteiro
{
    // #############################################################################################
    //                                                                                    INSTÂNCIAS
    // #############################################################################################

    private int valor;

    // #############################################################################################
    //                                                                                  CONSTRUTORES
    // #############################################################################################

    public Inteiro()
    {
        this.valor = 0;
    }

    // #############################################################################################
    //                                                                                 MODIFICADORES
    // #############################################################################################

    public void set(int valor) { this.valor = valor; }

    // #############################################################################################
    //                                                                                        ACESSO
    // #############################################################################################

    public int get() { return this.valor; }

    // #############################################################################################
    //                                                                             EQUALS E HASHCODE
    // #############################################################################################

    @Override
    public boolean equals(Object o) 
    {
        if (o == null) 
        {
            return false;
        }
        else if (o == this) 
        {
            return true;
        }
        else if (o.getClass() != this.getClass()) 
        {
            return false;
        }

        Inteiro inteiro = (Inteiro) o;

        return inteiro.get() == valor;
    }

    @Override
    public int hashCode() 
    {
        return valor;
    }
}

For what reason Spring is complaining that can not convert Inteiro to java.lang.Long? 由于什么原因,Spring抱怨无法将Inteiro转换为java.lang.Long? I'm not working with Long. 我不和朗一起工作。 Moreover... EL? 而且... EL? That would mean "Expression Language", right? 那就是“表达语言”,对吗? Does this have something to do with some of my JSP pages? 这与我的某些JSP页面有关吗? I am trying to develop a JSP page that displays search results, and on this page I use EL. 我正在尝试开发一个显示搜索结果的JSP页面,并且在此页面上使用EL。 Is there any possibility to be a problem in my JSP page? 我的JSP页面是否有可能出现问题?

Thank you for your help. 谢谢您的帮助。

public class ViewModel {
   private Integer myValue;
}

Use Wrapper object(ViewModel) to capture your value and Bind ViewModel class as model attribute in this case you can handle null values by using Wrapper(Integer).if you don't want to handle null values you can use int. 使用Wrapper对象(ViewModel)捕获您的值,并将ViewModel类绑定为模型属性,在这种情况下,您可以使用Wrapper(Integer)处理空值。如果您不想处理空值,则可以使用int。

public class ViewModel {
   private int myValue;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM