아키텍처와 함께

블로그 이미지
by gregorio
  • Total hit
  • Today hit
  • Yesterday hit

'전체 글'에 해당되는 글 56건

  1. 2018.02.22
    JSP의 img, script에 jsessionid가 추가되는 경우
  2. 2018.02.20
    Html a tag function call
  3. 2018.02.13
    CDI를 이용한 Java 개발
  4. 2018.02.12
    Java Class Instance화
  5. 2018.02.07
    Google Map javascript API 사용법

JSP에서 taglib c를 사용하여 img, script. css tag src를 지정하는 경우 resource에 jsessionid가 붙어 페이지를 처음 로딩할 때 jsessionid가 붙어 화면이 제대로 로딩되지 않는 경우가 발생한다.


화면을 다시 로딩하면 정상적으로 script, imgae, css가 적용된다.



■ 사용 예제

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


<link rel="stylesheet" type="text/css" href="<c:url value='/rui/plugins/ui/form/LFileBox.css'/>"/> 


■ 오류 결과

<link type="text/css" rel="stylesheet" href="/resource/css/import.css;jsessionid=589184C928C5896286836A1EF0DE6880" />

<link rel="alternate stylesheet" title="bh_style1" type="text/css" href=";jsessionid=589184C928C5896286836A1EF0DE6880resource/css/global_style_Rtl.css" id="bhStyle1"></link>
<link rel="stylesheet" title="en_style1" type="text/css" href=";jsessionid=589184C928C5896286836A1EF0DE6880resource/css/global_style.css" id="enStyle1"></link>
<script type="text/javascript" src="/resource/js/dui_prototype.js;jsessionid=589184C928C5896286836A1EF0DE6880"></script>
<script type="text/javascript" src="/resource/js/dui_hhmenu.js;jsessionid=589184C928C5896286836A1EF0DE6880"></script>
<script type="text/javascript" src="/resource/js/foriegnCheck.js;jsessionid=589184C928C5896286836A1EF0DE6880"></script>


브라우저에서 소스보기를 선택하여 소스를 확인하면 모든 script, css에 jessionid가 붙어 있어 404 오류가 발생한다.


이를 해결하기 위해 여러가지 방법이 있지만, 소스를 수정하지 않고 해결하는 방법은 web.xml에 sessoin-config에 tracking-mod를 추가하면 해결된다.


tracking-mods는 web-app_3.0이상에서만 지원하기 때문에 web.xml namespace를 변경해야한다.


■해결방법

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

xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

id="WebApp_ID" version="3.0">


  <session-config>

  <session-timeout>30</session-timeout>

<tracking-mode>COOKIE</tracking-mode>

  </session-config>

 


'Java' 카테고리의 다른 글

JVM GC 설정  (0) 2018.06.07
Java Reflection 사용법  (0) 2018.04.12
Html a tag function call  (0) 2018.02.20
CDI를 이용한 Java 개발  (0) 2018.02.13
Java Class Instance화  (0) 2018.02.12
AND

HTML 또는 JSP에서 <a> tag에서 URL을 호출하기 위해서 다음과 같이 코딩한다.


■ javascript

function localeChange(locale) { 

    debugger; 

    document.location.href = "<c:url value='/service/changeLocale.do?locale=" + locale + "'/>"; }


■ jsp

            <div id="LblockSupportMenu">

            <ul>

            <li class="Lfirst" id="liEmpNm" >

            Welcome to <a href="#" onclick="preference();"><strong><erp:sess attr="EMP_NM"></erp:sess></strong></a>

            </li>

            <li class="Llast" >

           

            <input type="button"  id="btnLogin" value="Login"  />

            <input type="button"  id="btnLogout" value="Logout"  onclick="logout();" />

                        <!-- button type="button" id="btnLogin" class="btn_action">Login</button -->

  <!-- button type="button" id="btnLogout" class="btn_action"  onclick="logout();" style="margin : 0 0 10 0px">Logout</button -->

            </li>

            <li class="lang"><a href="#" onclick="localeChange('bh');"> <img src="/ibm/resource/images/new/utility_arabic.png" alt="sehati" /></a> </li>

            <li class="lang"><a href="#" onclick="localeChange('en');"> <img src="/ibm/resource/images/new/utility_arabic.png" alt="sehati" /></a> </li>

            </ul>

            </div> 


'Java' 카테고리의 다른 글

JVM GC 설정  (0) 2018.06.07
Java Reflection 사용법  (0) 2018.04.12
JSP의 img, script에 jsessionid가 추가되는 경우  (0) 2018.02.22
CDI를 이용한 Java 개발  (0) 2018.02.13
Java Class Instance화  (0) 2018.02.12
AND

Spring Framework에서 다양한 Annotation을 지원해주기 때문에 프로그램 개발 시 필요한 Bean을 찾아서 사용하면 되는 강력한 기능을 제공하고 있다.


그러나 Spring Framework를 사용하지 않는 일반 POJO 프로그램에서 Annotation을 이용하여 Bean을 가져 올 수 있는 방법을 찾던 중에  JBOSS에서 제공하는 CDI(Context and Dependency Injection)를 적용할 수 있도록 개발했던 내용이다.


먼저 CDI를 사용하기 위해서는 jar 프로젝트에서는 /src/main/resources/META-INF 폴더에 beans.xml을 생성해야 한다.


■ beans.xml

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

<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"

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

       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"

       bean-discovery-mode="all">

       

</beans>


Bean으로 사용하기 위한 Class를 다음과 같이 생성한다.


■LowerCaseTextProcssor.java

 import javax.inject.Named;


@Named("lowerCase")

public class LowerCaseTextProcessor implements TextProcessor{


public String processText(String text) {

return text.toLowerCase();

}

}

LowerCaseTextProcess의 Class에 @Named Annotation을 이용하여 bean 이름을 설정한다.

여기서는 bean 이름을 lowerCase로 설정하였다.



프로젝트에 여러개의 Bean이 설정될 수 있기 때문에서 bean이름으로 해당 Class를 Return하는 공통 Class를 작성하여 Bean을 가져 올 수 있게 한다.


■BeanUtil.java

import java.util.Iterator;

import java.util.Set;


import javax.annotation.PreDestroy;

import javax.enterprise.inject.spi.Bean;


import org.jboss.weld.environment.se.Weld;

import org.jboss.weld.environment.se.WeldContainer;


public class BeanUtil {


private static WeldContainer container = null;

private static Weld weld = null;

private static Object sync = new Object();

/**

*<pre>

* Return bean class

*</pre>

* @param beanName

* @return

* @throws Exception

*/

@SuppressWarnings("unchecked")

public static <T> T getBean(String beanName) throws Exception {

init();

Set<Bean<?>> beans = container.getBeanManager().getBeans(beanName);

    Class<?> clazz = null;

//    beans = CDI.current().getBeanManager().getBeans(beanName);

    //Why need to iterator....

    Iterator<Bean<?>> itr = beans.iterator();

    while(itr.hasNext()) {

    Bean<?> bean = itr.next();

    String tempBeanName = bean.getName();

    if (tempBeanName.equals(beanName)) {

    clazz = bean.getBeanClass();

    break;

    }

    }

    return (T)(clazz != null ? container.select(clazz).get() : null);

}

/**

*<pre>

* Initialize Bean Manager

*</pre>

* @throws Exception

*/

private static void init() throws Exception {

if (container == null) {

synchronized(sync) {

    weld = new Weld();

    container = weld.initialize();

}

}


BeanUtil.java는 getBean Method에 beanName을 받아 객체를 Return한다.



특정 Class에서 Bean을 Inject하는 예제는 다음과 같다.

■ TextApplication.java

import java.io.BufferedReader;

import java.io.IOException;


import javax.inject.Inject;

import javax.inject.Named;



@Named("textApplication")

public class TextApplication {

@Inject

@Named("lowerCase")

private TextProcessor textProcessor;


@Inject

private BufferedReader reader;

public TextApplication() {

// this.textProcessor = textProcessor;

// this.userInputReader = new BufferedReader(new InputStreamReader(System.in));

// userInputReader.getBufferedReader();

}

public void run() throws IOException {

System.out.println("Enter the text to process : ");

String text = reader.readLine();

System.out.println(textProcessor.processText(text));

}



@Inject 과 @Named Annotation을 이용하여 필요한 Bean을 Field Level로 정의하여 

사용할 수 있다.



모든 필요 Clasa들이 만들었으면 테스트 프로그램을 만들어 테스트를 수행한다.


■Main.java

public class App 

{

    public static void main( String[] args ) throws Exception {


    TextApplication textApplication = BeanUtil.getBean("textApplication");

    textApplication.run();

   

    TextProcessor textProcessor = BeanUtil.getBean("lowerCase");

    System.out.println(textProcessor.processText("aaaaaa"));


    }

}



'Java' 카테고리의 다른 글

JVM GC 설정  (0) 2018.06.07
Java Reflection 사용법  (0) 2018.04.12
JSP의 img, script에 jsessionid가 추가되는 경우  (0) 2018.02.22
Html a tag function call  (0) 2018.02.20
Java Class Instance화  (0) 2018.02.12
AND

Java에서 Class Name으로 객체를 생성하기 위해서는 package이름을 알고 class 이름을 알고 있으면 쉽게 객체를 생성할 수 있다.


현재 프로젝트 내에 있는 모든 패키지에서 특정 클래스 이름으로 객체를 생성하기 위한 예제 코드이다.


  public <T> T getBean(String beanName) throws Exception {

    List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>();

    classLoadersList.add(ClasspathHelper.contextClassLoader());

    classLoadersList.add(ClasspathHelper.staticClassLoader());

    

    Reflections reflections = new Reflections(new ConfigurationBuilder()

            .setScanners(new SubTypesScanner(false), new ResourcesScanner())

            .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))

            .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("MY BASE PACKAGE"))));

    Set<Class<? extends Object>> classes = reflections.getSubTypesOf(Object.class);

    

    for (Class<?> clazz : classes) {

    int idx = clazz.getName().lastIndexOf(".");

    String clazzName = clazz.getName().substring(idx+1);

    if (clazzName.equals(beanName)) {

    return (T)ClassUtils.getClass(clazz.getName()).newInstance();

    }

    }

    

    return null;

}


commons-lang3에서 제공하는 기능을 사용하여 클래스 이름으로 객체를 생성하는 예제이다.


여기서 MY-BASE-PACKAGE를 인자로 사용하면 해당 Package를 포함하여 모든 클래스를 객체화 할 수 있다.



'Java' 카테고리의 다른 글

JVM GC 설정  (0) 2018.06.07
Java Reflection 사용법  (0) 2018.04.12
JSP의 img, script에 jsessionid가 추가되는 경우  (0) 2018.02.22
Html a tag function call  (0) 2018.02.20
CDI를 이용한 Java 개발  (0) 2018.02.13
AND

Google Map Java script API를 이용하여 화면에 Map을 표시하기 위해서 


■ https://developers.google.com/maps/documentation/javascript/get-api-key 를 참조하여 API KEY를 생성한다.


■ JSP 예제

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ page trimDirectiveWhitespaces="true"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>

<%@ page session="false"%>


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">


<html>

  <head>

    <title>Google Map</title>

    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">

    <meta charset="utf-8">

    <style>

      /* Always set the map height explicitly to define the size of the div

       * element that contains the map. */

      #map {

        height: 100%;

      }

      /* Optional: Makes the sample page fill the window. */

      html, body {

        height: 100%;

        margin: 0;

        padding: 0;

      }

      #description {

        font-family: Roboto;

        font-size: 15px;

        font-weight: 300;

      }


      #infowindow-content .title {

        font-weight: bold;

      }


      #infowindow-content {

        display: none;

      }


      #map #infowindow-content {

        display: inline;

      }


      .pac-card {

        margin: 10px 10px 0 0;

        border-radius: 2px 0 0 2px;

        box-sizing: border-box;

        -moz-box-sizing: border-box;

        outline: none;

        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);

        background-color: #fff;

        font-family: Roboto;

      }


      #pac-container {

        padding-bottom: 12px;

        margin-right: 12px;

      }


      .pac-controls {

        display: inline-block;

        padding: 5px 11px;

      }


      .pac-controls label {

        font-family: Roboto;

        font-size: 11px;

        font-weight: 300;

      }


      #pac-input {

        background-color: #fff;

        font-family: Roboto;

        font-size: 12px;

        font-weight: 300;

        margin-left: 12px;

        padding: 0 11px 0 13px;

        text-overflow: ellipsis;

        width: 400px;

      }


      #pac-input:focus {

        border-color: #4d90fe;

      }


      #title {

        color: #fff;

        background-color: #4d90fe;

        font-size: 14px;

        font-weight: 500;

        padding: 6px 12px;

      }

    </style>

  </head>

  <body>

    <div class="pac-card" id="pac-card">

      <div>

        <div id="title">

          Search Location

        </div>

        <div id="type-selector" class="pac-controls">

          <input type="radio" name="type" id="changetype-all" checked="checked">

          <label for="changetype-all">All</label>


          <input type="radio" name="type" id="changetype-establishment">

          <label for="changetype-establishment">Establishments</label>


          <input type="radio" name="type" id="changetype-address">

          <label for="changetype-address">Addresses</label>


          <input type="radio" name="type" id="changetype-geocode">

          <label for="changetype-geocode">Geocodes</label>

        </div>

        <div id="strict-bounds-selector" class="pac-controls">

          <input type="checkbox" id="use-strict-bounds" value="">

          <label for="use-strict-bounds">Strict Bounds</label>

        </div>

      </div>

      <div id="pac-container">

        <input id="pac-input" type="text" placeholder="Enter a location">

      </div>

    </div>

    <div id="map"></div>

    <div id="infowindow-content">

      <img src="" width="16" height="16" id="place-icon">

      <span id="place-name"  class="title"></span><br>

      <span id="place-address"></span>

    </div>


    <script>

      // This example requires the Places library. Include the libraries=places

      // parameter when you first load the API. For example:

      // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">


      function initMap() {

        debugger;

  

//    var curPos = {lat: 37.566535, lng: 126.97796919999996};

    var curPos = {};

    if (navigator.geolocation) {

    navigator.geolocation.getCurrentPosition(function(position) {

    debugger;

        curPos['lat'] = parseFloat(position.coords.latitude);

    curPos['lng'] = parseFloat(position.coords.longitude);

    });

    }

    //if current position is not set, default position is seoul

    if (curPos.lat == null) {   

    curPos['lat'] = 37.566535;

    curPos['lng'] = 126.97796919999996;

    }

    var map = new google.maps.Map(document.getElementById('map'), {

          center: curPos,

          zoom: 13

        });

        

        var infowindow = new google.maps.InfoWindow();

        var card = document.getElementById('pac-card');

        var input = document.getElementById('pac-input');

        var types = document.getElementById('type-selector');

        var strictBounds = document.getElementById('strict-bounds-selector');


        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(card);


        var autocomplete = new google.maps.places.Autocomplete(input);


        // Bind the map's bounds (viewport) property to the autocomplete object,

        // so that the autocomplete requests use the current map bounds for the

        // bounds option in the request.

        autocomplete.bindTo('bounds', map);


        var infowindowContent = document.getElementById('infowindow-content');

        infowindow.setContent(infowindowContent);

        var marker = new google.maps.Marker({

          map: map,

          anchorPoint: new google.maps.Point(0, -29)

        });

        

        autocomplete.addListener('place_changed', function() {

          infowindow.close();

          marker.setVisible(false);

          var place = autocomplete.getPlace();

          if (!place.geometry) {

            // User entered the name of a Place that was not suggested and

            // pressed the Enter key, or the Place Details request failed.

            window.alert("No details available for input: '" + place.name + "'");

            return;

          }


          // If the place has a geometry, then present it on a map.

          if (place.geometry.viewport) {

            map.fitBounds(place.geometry.viewport);

          } else {

            map.setCenter(place.geometry.location);

            map.setZoom(17);  // Why 17? Because it looks good.

          }

          marker.setPosition(place.geometry.location);

          marker.setVisible(true);


          var address = '';

          if (place.address_components) {

            address = [

              (place.address_components[0] && place.address_components[0].short_name || ''),

              (place.address_components[1] && place.address_components[1].short_name || ''),

              (place.address_components[2] && place.address_components[2].short_name || '')

            ].join(' ');

          }


          infowindowContent.children['place-icon'].src = place.icon;

          infowindowContent.children['place-name'].textContent = place.name;

          infowindowContent.children['place-address'].textContent = address;

          infowindow.open(map, marker);

        });


        

        // Sets a listener on a radio button to change the filter type on Places

        // Autocomplete.

        function setupClickListener(id, types) {

          var radioButton = document.getElementById(id);

          radioButton.addEventListener('click', function() {

            autocomplete.setTypes(types);

          });

        }


        function handleLocationError(browserHasGeolocation, infoWindow, pos) {

            infoWindow.setPosition(pos);

            infoWindow.setContent(browserHasGeolocation ?

                                  'Error: The Geolocation service failed.' :

                                  'Error: Your browser doesn\'t support geolocation.');

            infoWindow.open(map);

          }



        setupClickListener('changetype-all', []);

        setupClickListener('changetype-address', ['address']);

        setupClickListener('changetype-establishment', ['establishment']);

        setupClickListener('changetype-geocode', ['geocode']);


        document.getElementById('use-strict-bounds')

            .addEventListener('click', function() {

              console.log('Checkbox clicked! New state=' + this.checked);

              autocomplete.setOptions({strictBounds: this.checked});

         });

      }

    </script>

    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"

        async defer></script>

  </body>

</html>

 


Map이 오픈될 때 현재의 위치를 표시하기 위해 position.coords.latitude, position.coords.longitude 를 이용하여 현재의 위도와 경도를 가지고 온다.


그리고 Google에서 발급받은 API KEY를 YOUR_API_KEY에 대체하면 완성된다.

 

'Spring Framrwork' 카테고리의 다른 글

Spring framework XML Marshaller( Jaxb2Marshaller )  (0) 2018.03.09
spring framework interceptor  (0) 2018.03.02
C3 Bar Chart  (0) 2018.02.05
Spring Batch 모니터링 SQL  (0) 2018.02.03
MybatisBatchWriter 오류 해결방법  (0) 2018.02.03
AND

ARTICLE CATEGORY

분류 전체보기 (56)
Spring Framrwork (33)
Linux (1)
APM (1)
Java (8)
python (0)
ant (1)
chart (1)
OS (1)
tomcat (1)
apache (1)
database (0)

RECENT ARTICLE

RECENT COMMENT

CALENDAR

«   2024/10   »
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

ARCHIVE

LINK