案例2—使用 Jersey 基于 iPortal 已有资源扩展子资源

发送反馈


如果您希望在 iPortal 的已有资源下追加新的 REST API 进行扩展开发,例如:在“我的服务”资源下新增一个“我的 WMS 服务”资源,iPortal 提供了基于 Jersey 的后端资源扩展方式,本案例所使用的示范代码位于:%SuperMap iPortal_HOME%\samples\code\CustomPortal\Custom_Portal。

1.在开始进行扩展前,请搭建好定制开发环境

2.在编写您的自定义资源时请使用 Jersey 开发,并在入口类上添加注解 @ExtendPortalResource,示例的自定义资源实现类位于 src > com.supermap.iportal.web.custom.rest.resource.impl,代码如下:

package com.supermap.iportal.web.custom.rest.resource.impl;

import javax.ws.rs.GET;

import javax.ws.rs.Path;

import javax.ws.rs.WebApplicationException;

import org.apache.shiro.subject.Subject;

import org.apache.shiro.util.ThreadContext;

import org.springframework.beans.factory.annotation.Autowired;

import com.supermap.iportal.web.commontypes.ServiceInfo;

import com.supermap.iportal.web.commontypes.ServiceSearchParameter;

import com.supermap.iportal.web.commontypes.SourceType;

import com.supermap.iportal.web.components.ServiceInfoComponent;

import com.supermap.iportal.web.rest.extention.ExtendPortalResource;

import com.supermap.services.components.commontypes.Page;

/**

 * 用户扩展资源

 *

 * @author Administrator

 *

 */

@ExtendPortalResource

@Path("/")

public class CustomServiceResources {

    @Autowired

    ServiceInfoComponent serviceInfoComponent;//注入组件层

    @GET//指定请求方式为GET

    @Path("/mycontent/my-wms-services")//指定资源的路径

    public Page<ServiceInfo> getMyWmsServices() {

        Page<ServiceInfo> page = null;

        ServiceSearchParameter searchParameter = new ServiceSearchParameter();

        searchParameter.userNames = new String[] { getCurrentUserName() };

        searchParameter.types = new SourceType[] { SourceType.WMS };

        page = serviceInfoComponent.getServiceInfosByUser(searchParameter);

        return (page != null) ? page : new Page<ServiceInfo>();

    }

    protected String getCurrentUserName() {

        String userName = null;

        Subject subject = ThreadContext.getSubject();

        if (subject != null && subject.getPrincipal() != null) {

            userName = subject.getPrincipal().toString();

        } else {

            throw new WebApplicationException(401);

        }

        return userName;

    }

}

示例中在 mycontent 资源下添加了新的子资源 my-wms-services,返回作者为当前登录用户的所有的 WMS 服务资源列表。资源的响应体的将会根据发送请求体的不同(json,rjson,xml)自动转换为对应类型。

3.在 WebContent\WEB-INF\config 文件夹下添加 extendPortalResources.xml 文件作为添加资源的 Spring 配置文件,上述示例所对应的配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="

     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"

    default-lazy-init="true">

    <bean  class="com.supermap.iportal.web.custom.rest.resource.impl.CustomServiceResources" />

</beans>

粗体代码为配置加载的资源类。

4.访问 localhost:8091/iportal/web/mycontent/my-wms-services.json,即可返回我的服务中所有 WMS 类型的服务。