在Spring MVC中绑定UUID [英] Bind UUID in Spring MVC

查看:351
本文介绍了在Spring MVC中绑定UUID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Spring MVC中绑定UUID的最简单方法是什么,这样可行:

What is the easiest way to bind a UUID in Spring MVC, such that this works:

@RequestMapping("/MyController.myAction.mvc")
@ResponseBody
public String myAction(UUID id, String myParam)...

使用上面我当前获得以下异常:

Using the above I currentely get the following exception:

org.springframework.beans.BeanInstantiationException: 
Could not instantiate bean class [java.util.UUID]: 
No default constructor found; 
nested exception is java.lang.NoSuchMethodException: java.util.UUID.<init>()

还有其他问题围绕着这个,但似乎没有人回答它。我正在使用Spring 3.latest(实际上是4 EA)。我正在采用最新,最简单的方法来实现这一目标。

There are other questions on SO that skirt around this, but none seem to answer it. I'm using Spring 3.latest (4 EA actually). I'm after the latest, simplest way to achieve this.

推荐答案

UUID 是一个不能简单地实例化的类。假设它作为请求参数出现,您应首先使用 @RequestParam 注释参数。

UUID is a class that cannot simply be instantiated. Assuming that it comes as a request parameter you should first annotate the argument with @RequestParam.

@RequestMapping("/MyController.myAction.mvc")
@ResponseBody
public String myAction(@RequestParam UUID id, String myParam)...

现在这需要一个名为 id 的请求参数在请求中可用。该参数将转换为 UUID 。但是目前这会失败,因为目前没有什么可以从 String 转换为 UUID

Now this expects a request parameter with the name id to be available in the request. The parameter will be converted to a UUID. However at the moment this will fail because there is, currently, nothing that can convert from a String to a UUID.

为此创建一个转换器,可以做到这一点。

For this create a Converter which can do this.

public class StringToUUIDConverter implements Converter<String, UUID> {
    public UUID convert(String source) {
        return UUID.fromString(source);
    }
}

将此课程挂钩到 ConversionService ,您应该对请求参数进行UUID转换。 (如果它是一个请求标题,这也可以工作,基本上是用于点击 ConversionService 的所有内容)。你也可能想要一个转换器用于其他方式(UUID - > String)。

Hook this class up to the ConversionService and you should have UUID conversion for request parameters. (This would also work if it was a request header, basically for everything that taps into the ConversionService). You also might want to have a Converter for the other-way (UUID -> String).

挂钩它在参考指南(假设您使用xml配置)。但简而言之:

Hooking it up to Spring MVC is nicely explained in the reference guide (assuming you use xml config). But in short:

<mvc:annotation-driven conversion-service="conversionService"/>

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="org.company.converter.StringToUUIDConverter"/>
        </set>
    </property>
</bean>

注意:截至Spring 3.2 Spring a 添加了 StringToUUIDConverter ,它会自动注册。

NOTE: As of Spring 3.2 Spring a StringToUUIDConverter has been added, which automatically registers.

这篇关于在Spring MVC中绑定UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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