컨피그 설정 페이지 #3을 추가하면 된다.


#1 : 스프링 어플리케이션 시작 

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


#2 : 컨트롤러 생성

@Controller
public class GreetingController {
    @RequestMapping("/greeting")
    public String greeting() {
        return "greeting";
    }
}


#3 : 뷰리졸버 설정

@Configuration
@EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
    @Bean
    public ViewResolver getViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/");
        resolver.setSuffix(".html");
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }    
}


출처 : http://stackoverflow.com/questions/29953245/configure-viewresolver-with-spring-boot-and-annotations-gives-no-mapping-found-f

요약하면, 생성자는 ModelAndView(View, Pointer, Holder); 형태로 구성이 되어 있으며

화면(View)에 그것을 가르치는(Pointer)것에 내용을 담아서(Holder) 설정하는 것이다.


Here in this case, we are having 3 parameter's in the Method namely ModelandView

According to this question, the first parameter is easily understood from the question. It represents the View which will be displayed to the client.
The other two parameters are just like The Pointer and The Holder
Hence you can sum it up like this 

ModelAndView(View, Pointer, Holder);

The Pointer just points the information in the The Holder

When the Controller binds the View with this information, then in the said process, you can use The Pointer in the JSP page to access the information stored in The Holder to display that respected information to the client. 
Here is the visual depiction of the respected process.



출처 : http://stackoverflow.com/questions/5055358/what-is-model-in-modelandview-from-spring-mvc


설정 방식으로 적용하는 예제


@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**");
            }
        };
    }
}


Filter 방식으로 적용하는 예제


@Configuration
public class MyConfiguration {

	@Bean
	public FilterRegistrationBean corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		CorsConfiguration config = new CorsConfiguration();
		config.setAllowCredentials(true);
		config.addAllowedOrigin("http://domain1.com");
		config.addAllowedHeader("*");
		config.addAllowedMethod("*");
		source.registerCorsConfiguration("/**", config);
		FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
		bean.setOrder(0);
		return bean;
	}
}


출처 :

https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

TypeScript 2.1 출시


https://www.typescriptlang.org


Microsoft는 TypeScript 2.1을 출시하여 불필요한 타이핑을 줄이고 도구 체인을 간소화하는 많은 기능을 제공합니다.


이 릴리스 이전에는 TypeScript가 async / await를 지원했지만 ES2015를 대상으로 만했습니다. 이 코드는 고급 환경에서만 사용할 수 있도록 개발되었지만 모든 브라우저에서 개발되지 않은 개발자에게는 적합하지 않습니다. 개발자는 코드를 모든 브라우저에서 사용 가능한 상태로 변환하기 위해 도구 체인에 추가로 transpiler (Babel과 같은)를 추가해야했습니다.


2.1을 사용하면 TypeScript에서 ES3 / ES5 레벨 코드로 비동기 / 대기 상태로 바벨을 필요하지 않게 할 수 있습니다.


React에서 근무하는 TypeScript 개발자의 경우 스프레드 연산자의 부족은 코드를 변경하거나 바벨을 추가하여 처리하는 것을 의미합니다. React에서 스프레드 연산자는 속성을 하위 수준 구성 요소에 전달하거나 상태를 변형 할 때 자주 사용됩니다. 2.1 이전 버전에서 그러기 위해 TypeScript는 변환을 처리 할 Babel을 추가해야했습니다. 스프레드 연산자는 다른 방법으로도 유용하지만 개발자가 없으면 개발자가 JavaScript 피쳐 객체를 사용해야 객체를 결합 할 수 있습니다. 결과는 비슷하지만 스프레드 연산자는 필요한 코드의 양을 크게 줄이고 가독성을 높입니다.


TypeScript 프로그램 관리자 인 Daniel Rosenwasser는 async / await 및 spread 연산자가 Babel에서 잠시 동안 사용 가능했지만 2.1의 지연은 타이핑 시스템이 예상대로 계속 작동하는지 확인했기 때문이라고 설명합니다.


TypeScript에서 기능을 구현할 때 우리는 길이가 적절하게 입력되고 성능 특성이 합리적임을 보장합니다. 즉, 객체 휴식 / 스프레드를 사용할 때 유형이 효과적으로 적용되는 환경을 제공하지 않고 오류가 발생하면 사용자를 좌절시킬 수 있습니다. async / await을 사용하여 emit 파이프 라인을 다시 작성해야했기 때문에 방출 시간과 출력 시간을 동일하게 유지해야했습니다. 투자가 나타 났으며 TypeScript는 여전히 매우 빠릅니다.


TypeScript 2.1 Announcement에서 Rosenwasser는 keyof 연산자, 더 쉬운 임포트 및 매핑 된 유형과 같은 많은 다른 새로운 기능을 수행합니다. Rosenwasser는 매핑 된 유형이 "TypeScript 2.1에서 가장 흥미로운 기능"이라고 말합니다. 속성이 거의 동일 할 때 개발자가 기존 객체의 새로운 변종을 만들 필요가 없도록했습니다. 수입 경험을 개선하기 위해 Rosenwasser는 솔루션이 더욱 유연 해지고 있다고 말했습니다.


우리는 TypeScript를 더 신뢰해야한다고 결정했고, TypeScript 2.1에서는 패키지가 설치되어 있다면 사용할 수 있습니다.


TypeScript 2.1은 모든 일반 채널에서 사용할 수 있습니다.


출처 : https://www.infoq.com/news/2016/12/typescript-2-1-released?utm_campaign=infoq_content&utm_source=infoq&utm_medium=feed&utm_term=global


번역 : 구글



소켓의 accept 을 응용한 형태로 구현해 봤습니다.

이 형태가 맞는지 ? 원본 소스를 보지 않았는데 나중에 시간되면 한번 봐봐야지요 -_-;


아래 부분을 좀 수정 해야 될거 같은데 흠..

Thread.sleep(Long.MAX_VALUE);


결과 : 


Thread가 2개가 유지 됨 / 1,2 => 2,3 => 3,4 이런 형태로 유지


start

create : 274064735

create : 841752171

close : 274064735

create : 592705150

close : 841752171

create : 244621161

close : 592705150

package kr.co.jwsnt.libs.test;


public class TeNotifyRecur{
	
	/*
	 * 결과
	 * 
	 */

	public static void main(String[] args){
		new TeNotifyRecur();
	}
	
	class TeThread extends Thread{
		
		private TeNotifyRecur p;
		
		public TeThread(TeNotifyRecur p){
			this.p = p;
		}
		
		@Override
		public void run() {
			try {
				Thread.sleep(2000);
				p.reconnect();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	TeNotifyRecur(){

		System.out.println("start");
		
		connect();
		
		while(true){
			try {
				Thread.sleep(Long.MAX_VALUE);
			} catch (InterruptedException e) {
				break;
			}
		}
		System.out.println("end");
		
	}
	
	private void connect()
	{
		Object obj = new Object();
		System.out.println( "create : " + obj.hashCode() );

		try{
			Thread t = new TeThread(this);
			t.setDaemon(true);
			t.start();
			startWait();
		}catch(Exception e){
			System.out.println( "conn : " + e.toString() );
		}finally{
			close(obj);	
		}
	}
	
	private void close(Object obj){
		System.out.println( "close : " + obj.hashCode() );
		obj = null;
	}
	
	public synchronized void reconnect(){
		notify();
		connect();
	}
	
	public synchronized void startWait() throws InterruptedException{
		wait();
	}
}


스레드를 활용한 wait 처리를 구현하기 위해 테스트한 결과를 기록해 두었음.


평소에 thread를 잘 활용하지 않으니 이런 문제가 발생한거 같은데 좀더 많은 탐구가 필요한 것으로 사료 됨.

응용하면 consumer, producer형태에 사용할 수 있음. 이번에 mq관련 프로젝트에서 아래 내용을 활용해서 적용.


socket listen => client socket 개별 생성 => map에 메시지 넣고 wait

mq consumer thread로 동작 메시지 수신 시 map에서 꺼내 notify => client socket은 응답 메시지 작업 후 close


그냥 주저리 내용이므로 참조만 바랍니다. 볼 사람이나 있을려나 훗~


결과 :


job-1

job-2

waitStart-1

run-1

run-2

waitEnd-1

waitEnd-2

run-3

waitStart-2

job-3


public class TeParent {

	class TeChild implements Runnable{
		TeParent p;
		TeChild(TeParent p){
			this.p = p;
		}
		
		@Override
		public void run() {
			try {
				System.out.println("run-1");
				Thread.sleep(3000);
				System.out.println("run-2");
				this.p.waitEnd();
				System.out.println("run-3");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public synchronized void waitStart() throws InterruptedException{
		System.out.println("waitStart-1");
		wait();
		System.out.println("waitStart-2");
	}
	
	public synchronized void waitEnd(){
		System.out.println("waitEnd-1");
		notify();
		System.out.println("waitEnd-2");
	}
	
	TeParent(){
		try{
			System.out.println("job-1");
			new Thread(new TeChild(this)).start();;
			System.out.println("job-2");
			waitStart();
			System.out.println("job-3");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args){
		new TeParent();
	}
}


angular-js post 하면 request inputstream 에는 값이 설정됨(payload)

 jQuery post 하면 modelAttribute 값이 자동 binding 되며 request inputstream 에는 값이 설정되지 않음.


( 표 1 : chrome에서 network 부분을 일부 발췌하여 캡춰 함)

구분

request-inputstream

modelAttribute

result

angular-js

O

X

 

angular-js

with

content-type

X

X


 

jQuery

X

O


 

 

 

 

아래 글을 보면 알 수 있듯이 jquery 와 angularJs 의 데이터 전송처리에는 직렬화 처리의 차이점이 존재한다.

또한 전송 시 content-type이 다른 것을 확인 할 수 있다.

그래서 spring에서 @modelAttribute 로 값을 바인딩 하는 경우 jquery 는 되는데 angular-js는 안되는 현상을 맞이할 수 있다.


출처 : http://stackoverflow.com/questions/19254029/angularjs-http-post-does-not-send-data

The difference is in how jQuery and AngularJS serialize and transmit the data. Fundamentally, the problem lies with your server language of choice being unable to understand AngularJS’s transmission natively ... By default, jQuery transmits data using Content-Type: x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization. AngularJS, however, transmits data using Content-Type: application/json and { "foo": "bar", "baz": "moe" } JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.


그래서 기본 전송 시 해더 정보와 전송 되는 값을 직렬화 처리를 하여 전송하면 angular-js 또한 jquery 와 동일한 결과를 확인할 수 있다. 

 

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

 

출처 : https://gist.github.com/bennadel/11212050

angular-js-form-post

 

데이터 직렬화 처리

 

function serializeData( data ) {

 

  // If this is not an object, defer to native stringification.

  if ( ! angular.isObject( data ) ) {

    return( ( data == null ) ? "" : data.toString() );

  }

 

  var buffer = [];

  // Serialize each key in the object.

  for ( var name in data ) {

    if ( ! data.hasOwnProperty( name ) ) {

      continue;

    }

 

    var value = data[ name ];

    buffer.push(

      encodeURIComponent( name ) + "=" +

      encodeURIComponent( ( value == null ) ? "" : value )

    );

  }

 

  // Serialize the buffer and clean it up for transportation.

  var source = buffer.join( "&" ).replace( /%20/g, "+" );

 

  return( source );

}

 

 


출처 : http://slipp.net/questions/254


위 링크에서와 같이 다양한 곳에서 문제 가 발생한다.


URL 한글 파라미터 전달

DB 조회 시 설정

서버 locale 설정

JSon 인코딩 문제


등과 같이 다양한 문제가 발생하는데 위 링크를 참조 하면서 해결하면 왠만한 문제가 해결 될것 같다.



'기타 > Old' 카테고리의 다른 글

[JAVA] thread example  (0) 2015.08.13
angular-js form post 처리 (spring-modelAttribute 처리)  (0) 2015.07.08
[Arduino] 사운드 센서  (0) 2015.06.26
highlight 강조 표현 처리  (0) 2015.06.18
matches 사용방법  (0) 2015.06.18

드디어 아두이노 yun + Grove 셋트를 구매 !

이제부터 하나씩 응용해 보면서 개발 해봐야지 하는 마음으로 오늘부터 하나씩 기록 해 보도록 할 예정임

아...  선 정리에 불편함이 완전 줄어 들어서 넘 좋은거 같음. 브레드 보드여 안녕 ~ 난 단위 모듈만 끼워 넣겠다 ㅋㅋㅋㅋㅋ




사운드 센서 + LED

=> 목표 : 소리가 일정 크기 이상이 되면 불이 들어오도록 함.

=> 응용 : 도서관에서 소리가 큰 사람의 자리는 불이 들어오록 함 -_-;;;


출처 : http://www.seeedstudio.com/wiki/Grove_-_Sound_Sensor


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
int LED = 13;
int SOUND_SENSOR = A0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(SOUND_SENSOR, INPUT); 
  pinMode(LED, OUTPUT); 
}

void loop() {
  int sensorValue = analogRead(SOUND_SENSOR);//use A0 to read the electrical signal
  Serial.print("sensorValue : ");
  Serial.println(sensorValue);
  if( sensorValue > 650 ){
    digitalWrite(LED, HIGH);
    delay(200);
  }
  digitalWrite(LED, LOW);
  
}


요약 : innerHTML 을 통해 태그를 추가해주면 됨.


기능

- 검색 단어 하이라이트

- 대소문자 무시처리

- 하이라이트 된 라인만 보이도록 처리 ( 유용할 듯 ? )


댓글로 있으면 더 좋을거 같은 기능 알려주시면 추가 할께요... 그런데 과연 댓글을 줄사람이 있을까? ㅋㅋㅋ


활용은 맘대로 사용하세요 / 출처 남겨주시면 고맙고 ... 아니면 뭐 ^^;



'기타 > Old' 카테고리의 다른 글

자바 웹 프로젝트를 하면서 격는 한글 처리 문제점...  (0) 2015.07.01
[Arduino] 사운드 센서  (0) 2015.06.26
matches 사용방법  (0) 2015.06.18
cordova - platform support  (0) 2015.06.05
cordova - overview  (0) 2015.06.05

+ Recent posts