How can I enable MultiPartFeature?

…衆ロ難τιáo~ 提交于 2019-11-28 13:44:32
Paul Samsotha

Not sure why you don't just use a ResourceConfig instead of an Application class. The only reason I can think of is portability, but the use of the Jersey specific multipart feature already breaks that portability.

But anyway, I'll try to answer this in the "most portable" way. What you can do is set a property, as you would in a web.xml. To set arbitrary properties, you can override

@Override
public Map<String, Object> getProperties() {}

in the Application subclass, and set the properties there.

@Override
public Map<String, Object> getProperties() {
    Map<String, Object> props = new HashMap<>();
    props.put("jersey.config.server.provider.classnames", 
            "org.glassfish.jersey.media.multipart.MultiPartFeature");
    return props;
}

This will maintain the classpath scanning for your resources and providers. The scanning is only disabled if you override getClasses() or getSingletons() (and return non-empty sets), but getProperties() is fine.

Another Option:

Create a Feature to wrap that feature, and let the feature be discovered, as seen here

Personally, I would...

Just use a ResourceConfig, as you're already breaking portability (what's a little more breakage :-)

@ApplicationPath("/")
public class AppConfig extends ResourceConfig {
    public AppConfig() {
        packages("packages.to.scan");
        register(MultiPartFeature.class);
    }
}

For me worked like below:

        final ResourceConfig resourceConfig = new ResourceConfig(ApplicationConfig.class);
        resourceConfig.packages("com.econorma.rest");
        resourceConfig.register(MultiPartFeature.class);

        ServletHolder jerseyServlet  = new ServletHolder(new ServletContainer(resourceConfig));

This is ApplicationConfig class

@ApplicationPath("/")
public class ApplicationConfig extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        final Set<Class<?>> resources = new HashSet<Class<?>>();
        resources.add(MultiPartFeature.class);
        resources.add(EntryPoint.class);
        return resources;
    }

    @Override
    public Map<String, Object> getProperties() {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("jersey.config.server.provider.packages", "com.econorma.rest");
        return properties;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!