본문 바로가기
IT 개발/GeoServer

GeoServer 사용하기 (Proxy 설정하여 GeoServer Layer 가져오기)

by Love of fate 2020. 2. 5.
728x90
반응형

* CommonController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package gamum.test1.test;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
public class CommonController {
 
    private String GEOSERVER 
= "http://localhost:8080/geoserver/[geoserver에서 설정한 작업공간 명]/wms";
    
    @ResponseBody
    @RequestMapping(value="/cmm/gisProxy.do")
    public void gisProxy(
        @RequestParam(value="_encode", required=false, defaultValue="UTF-8"String encode,
        HttpServletRequest request,
        HttpServletResponse response
    ) throws Exception {
 
        String url = GEOSERVER;
        WebUtil.getProxy(url, encode, request, response);
    }
    
}
 
 

* WebUtil.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
    /**
     * Description : 동인근원정책(Same-Origin Policy) 정책을 해결하기 위한 방법으로써, 
     * 사용자의 요청/응답을 특정 API로 연결해주는 역할을 수행
     *
     * @param reqUrl(String)                - 연결 URL
     * @param encode(String)                - Connection 인코딩(ex : UTF-8)
     * @param request(HttpServletRequest)    - 사용자 요청 객체
     * @param response(HttpServletResponse)    - 사용자 응답 객체
     */
    public static void getProxy(String reqUrl, String encode, 
        HttpServletRequest request, HttpServletResponse response) {
 
        getProxy(reqUrl, encode, null, request, response, null);
    }
 
    public static void getProxy(String reqUrl, String encode, Map<String,String> addHeader, 
        HttpServletRequest request, HttpServletResponse response, Map<StringObject> additionalParam) {
 
        HttpURLConnection httpURLConnection = null;
        InputStream is = null
 
        try {
            
            Enumeration<String> e = request.getParameterNames();
            
            StringBuffer param = new StringBuffer();
            
            while(e.hasMoreElements()){
                String paramKey = e.nextElement();
                
                String[] values = request.getParameterValues(paramKey);
                
                for(String value : values) {
                    param.append(paramKey + "=" + value + "&");
                }
            }
            
            String query = param.toString();
            query = query.substring(0, query.lastIndexOf("&"));
            
            if(request.getQueryString() != null && !"".equals(request.getQueryString())){
                reqUrl = reqUrl + "?" + query; 
            }
            
            
            URL targetURL = new URL(reqUrl);
            httpURLConnection = (HttpURLConnection)targetURL.openConnection();
            
            Enumeration<String> headerKey = request.getHeaderNames();
            
            while(headerKey.hasMoreElements()) {
                String key = headerKey.nextElement();
                String value = request.getHeader(key);
                httpURLConnection.addRequestProperty(key, value);
            }
            
            httpURLConnection.setRequestMethod(request.getMethod().toUpperCase());
 
            response.setContentType(httpURLConnection.getContentType());
            
            if(httpURLConnection.getResponseCode() == 200) {
                IOUtils.copy(httpURLConnection.getInputStream(), response.getOutputStream());
            }else{
                IOUtils.copy(httpURLConnection.getErrorStream(), response.getOutputStream());
            }
            
        } catch (Exception e) {
            if(LOGGER.isErrorEnabled()) {
                LOGGER.error("Proxy Error : ("+reqUrl+")", e);
            }
        } finally {
            try { if(is != null) { is.close(); } } catch(IOException e) {
                if(LOGGER.isErrorEnabled()) {
                    LOGGER.error("exception", e);
                }
            } 
            if(httpURLConnection != null) { httpURLConnection.disconnect(); }
        }
    }
 

 

* map.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
 * 지도 첫 셋팅
 * dataProjection : EPSG:4326
 * mapProjection : EPSG:3857
 */
function initMap() {
 
    var center = new ol.geom.Point([ 127.0149999999999937.53 ]).transform(dataProjection, mapProjection);
 
    map = new ol.Map({
        target : 'map',
        layers : [ // 강제로 WKT형식의 Vworld로 변경하면 지도의 이미지가 눌린다. ㅠ
            new ol.layer.Tile({
                name : "baseLayer",
                source : new ol.source.XYZ({
                    //url : 'http://xdworld.vworld.kr:8080/2d/Base/201802/{z}/{x}/{y}.png'
                    url : 'http://api.vworld.kr/req/wmts/1.0.0/[Vworld API KEY]/Base/{z}/{y}/{x}.png'
                    })
            }), 
            new ol.layer.Tile({
                name : "satelliteLayer",
                source : new ol.source.XYZ({// Vworld Tile 변경 : Satellite : 항공사진 레이어 타일
                    url: 'http://api.vworld.kr/req/wmts/1.0.0/[Vworld API KEY]/Satellite/{z}/{y}/{x}.jpeg'
                }) 
            }),
            new ol.layer.Tile({
                name : "hybridLayer",
                source : new ol.source.XYZ({// Vworld Tile 변경 : HYBRID : 문자 타일 레이어 
                    url: 'http://api.vworld.kr/req/wmts/1.0.0/[Vworld API KEY]/Hybrid/{z}/{y}/{x}.png'
                })
            }),
            new ol.layer.Tile({ //Geoserver Layer
                name : "wmsLayer",
                source : new ol.source.TileWMS({
                    url :_contextPath + 'cmm/gisProxy.do',
                    params: {
                        'service' : 'WMS',
                        'request' : 'GetMap',
                        'layers''[geoserver에서 설정한 layer]',
                        'styles' : '[geoserver에서 layer에 적용한 style]'
                    },
                    singleTile: true,
                    serverType : 'geoserver'
                })
            })],
        view : new ol.View({
            projection : mapProjection, //EPSG:3857 
            center : center.getCoordinates(), // coordinates : 좌표 //// center의 좌표 반환
            zoom : 9 
        }),
    });
    
    map.getView().setMinZoom(9); // 최소 줌 설정
 

 

728x90
반응형