环境:IDEA java geoserver。
参考:github项目:geoserver-manager
功能:使用java语言通过Geoserver软件发布shp(zip格式)地图服务。
1、新建maven项目
2、pom.xml代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>TestGeoserver_success</groupId>
<artifactId>TestGeoserver_success</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>it.geosolutions</groupId>
<artifactId>geoserver-manager</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.11</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
</project>
3、PublishStyle.java代码
package geoserver;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
import it.geosolutions.geoserver.rest.GeoServerRESTReader;
import java.io.File;
import java.util.List;
//发布sld样式
public class PublishStyle {
public static void main(String[] args) throws Exception {
final String geoserverUrl = "http://localhost:8080/geoserver";
final String geoserverUsername = "admin";
final String geoserverPassword = "geoserver";
GeoServerRESTPublisher geoServerRESTPublisher = new GeoServerRESTPublisher(geoserverUrl,geoserverUsername,geoserverPassword);
GeoServerRESTReader geoServerRESTReader = new GeoServerRESTReader(geoserverUrl,geoserverUsername,geoserverPassword);
String workspace = "bbb"; //工作空间
File sldFile = new File("G:\\test\\restteststyle2.sld"); //默认发表的样式名等于文件名
int index = sldFile.getName().lastIndexOf(".");
String sldFileName = sldFile.getName().substring(0,index);
System.out.print(sldFileName);
//workspace是否存在,不存在则新建。
List<String> workspacesList = geoServerRESTReader.getWorkspaceNames();
boolean wsNull = !workspacesList.contains(workspace);
if(wsNull){
geoServerRESTPublisher.createWorkspace(workspace);
}
//样式是否存在
boolean styleFlag = geoServerRESTReader.existsStyle(workspace,sldFileName);
if(styleFlag){
System.out.println(sldFileName+"样式已经存在了!");
}else{
boolean sldPublishResult = geoServerRESTPublisher.publishStyleInWorkspace(workspace,sldFile);
if(sldPublishResult){
System.out.println(sldFileName+"样式发布成功!");
}else{
System.out.println(sldFileName+"样式发布失败!");
}
}
}
}