Tags

onclick 자바스크립트 Anchor JUnit j 초기화 커피스크립트 정규표현식 conceal nbsp Coffeescript springframework Java 스프링 프레임워크 Import :: static initialization block 테스팅 Web Controller Testing Join line a tag regExp href 자바 VIM Trail JavaScript 임폴트 Prototype

초기화 코드를 넣는 Initialization Blocks

Static Initialization Block

자바 코드들을 읽다 보면 다음과 같은 코드가 쉽게 눈에 띈다

class Whatever {
	public static final int myInt; 
	static { 
		myInt = 4444;
	}
}

바로 static 초기화 블럭이다

클래스가 생성되는 시점에 초기화 되는 코드

그런데, 오늘 신기한 녀석을 StaticOverflow - Is there a best practice for writing maps literal style in Java?에서 발견했다.

Instance Initialization Block

Map map = new HashMap() {
	{
		put("foo", "bar");
		put(123, 456);
	}
};

객체 초기화 블럭, 이런 녀석도 있었다.

정말 동작하는지 공식 문서를 찾아보니 The Java Tutorials - Initializing Fields에 떡하니 쓰여있는 내용

Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods. The Java Tutorials

즉, 생성자에서 변수를 초기화 하는 방법을 대신해서 객체의 변수 값을 초기화 하는 방법은 초기화 블럭파이널 메소드 이다. 라고...

파이널 메소드 방법은 공식 문서 참조.

저작자 표시 변경 금지
Trackback 0: Comment 0

스프링 프레임웍 에서 웹 컨트롤러 테스트하기.

참고로 난 JUnit, Springframework 에 대한 이해가 매우 낮음.

import static org.springframework.test.web.ModelAndViewAssert.*;
import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ModelAndView;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/mvc-test.xml"})
public class IndexControllerTest {

	@Autowired
	private XxxController controller;

	@Autowired
	private ApplicationContext applicationContext;
	private HandlerAdapter handlerAdapter;
	private MockHttpServletRequest request;
	private MockHttpServletResponse response;

	@Before
	public void setUp() {
		request = new MockHttpServletRequest();
		response = new MockHttpServletResponse();
		handlerAdapter = applicationContext.getBean(HandlerAdapter.class);
	}

	@Test
	public void testIndexController() throws Exception {
		request.setRequestURI("/index.daum");
		final ModelAndView mav = handlerAdapter.handle(request, response, controller);
		assertViewName(mav, "/main/index");
	}
}

위에 코드에는 모르는 내용이 수두룩 하지만 당장 testIndexController() 코드만 살펴보기로 함.

MockHttpServletRequest 객체에 테스트 하고 싶은 URI 를 설정함

HandlerAdapter에 해당 request 를 넣어 ModelAndView객체를 구해 옮.

그리고 구해 놓은 ModelAndView 의 객체 내용을 하나하나 확인.

가볍게 살펴보는 모르는 것들.

ApplicationContext
org.springframework.context.ApplicationContext 인터페이스는 BeanFactory인터페이스를 상속받은 하위 인터페이스로서 BeanFactory가 제공하는 빈 관리 기능 이외에 파일과 같은 자원 처리 추상화, 메시지 지원 및 국제화 지원, 이벤트 지원 등 추가 적인 기능을 제공하고 있다. 웹 개발자를 위한 스프링 2.5 프로그래밍 중.

무슨 소리인지 잘 모르겠음. 아마 스프링 실행 문맥 이 아닐까 생각됨, 거기서 BeanFactory의 getBean() 메서드를 이용하여 HandlerAdapter 객체를 가져오는 목적으로 사용된 듯.

HandlerAdapter
Helps the DispatcherServlet to invoke a handler mapped to a request regardless of the handler is actually invoked. For example, invoking an annotated controller requires resolving various annotations. Thus the main purpose of a HandlerAdapter is to shield the DispatcherServlet from such details. Spring Framework Reference Documentation

DispatcherServlet 이 request 에 맞는 handler 를 호출하는 것을 돕는 녀석이란 뜻인가?

뭔가 아직 모르는게 너무 많음을 확인한 포스팅, 이 낙서의 요점은, 위 코드 이다! 웹 컨트롤러 테스트 코드 작성할 때 빈번하게 쓰일 것 같은 내용이라 이곳에 정리.

저작자 표시 변경 금지
Trackback 0: Comment 0

누구냐 넌 import static!?

매번 Static 메서드의 클래스를 입력하지 않아도 되는 방법!, 아래 ModelAndViewAssert.assertViewName(...) 처럼.

...
import static org.springframework.test.web.ModelAndViewAssert.*;
...

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/test.xml" })
public class ControllerTest {

	@Autowired
	private Controller controller;

	@Test
	public void viewNameTest() {
		ModelAndView mav = controller.index();
		assertViewName(mav, "/main/index");
	}
}
static 메소드나 static 변수를 접근하기 위해 해당 클래스의 이름과 함께 써 주어야 한다. 하지만 유틸리티성 메소드나 상수의 경우 일일이 클래스 이름을 써주기 귀찮은 경우가 있는데 이 경우 static import를 사용하면 클래스 이름 없이 static 메소드나 static 변수 이름만으로 사용할 수 있다. Sigel's house made of ice 。。。블로그 본문
저작자 표시 변경 금지
Trackback 0: Comment 0

vim 명령어 'J'

필요할 때마다 생각나지 않는 vim 명령어. 대문자 J

아래 줄을 가져와 공백을 제거하고, 뒤에 붙히는 명령어

Join [count] lines, with a minimum of two lines. Remove the indent and insert up to two spaces (see below). VIM - main help file
저작자 표시 변경 금지
Trackback 0: Comment 0

String 객체

.search(정규표현식 | 문자열)

정규표현식을 전달인자, 가장처음 매칭되는 위치를 반환, 매칭이 없다면 -1을 반환

"JavaScript".search(/script/i);

.replace(정규표현식 | 문자열, 교체할 문자열 | 함수)

'g'가 있음 모든 매칭 문자열 교체, 만약 교체할 문자열에 $숫자 가 나오면, 숫자 번째 매칭된 부분 문자열로 치환됨.

두번째 인자로 교체될 문자열을 동적으로 계산하는 함수 가능

.match(정규표현식)

매치된 결과를 배열로 반환. g의 유무에 따라 아래와 같은 결과

"1=a plus 2=bb equals 3=c".match(/(\d+)=(\w)/); // => ["1=a", "1", "a"]
"1=a plus 2=bb equals 3=c".match(/(\d+)=(\w)/g); // => ["1=a", "2=b", "3=c"]

g 가 없음,리턴값에 index 프로퍼티가 존재하게 되며, 이는 매칭이 시작된 위치.

input 프로퍼티가 존재, 이는 검색 대상 문자열의 사본.

s.match(r) 은 r.exec(s)와 같은 값을 반환.

.split(문자 | 정규표현식)

전달인자를 분리 기준으로 문자열을 쪼개 배열을 리턴.

RegExp 객체

문자열 리터럴과 정규표현식은 둘다 '\'를 이스케이프 시퀀스로 사용하기 때문에 RegExp 생성자의문자열 리터럴로 전달할 때는 '\'를 '\\'로 바꿔야 한다.

new RegExp("\\d{}5", "g")

.exec(문자열)

매치된 부분이 없다면 null 리턴, 매치된 부분이 있다면 배열 리턴, [매치된 문자열, 괄호1, ...]

index 프로퍼티에 매치가 일어난 idx 저장.

input 프로퍼티에 검색 대상 문자열. 참조?

g 플래그 무시

* 정규표현식 lastIndex 속성에 다음 매치를 시작할 idx값 저장.

처음부터 다시 검색하려면 반듯시 0으로 초기화 해야 함.

while((result = pattern.exec(text)) != null) {
  ... 반복 처리..
}

.test(문자열)

매치되는 부분이 있음 true 아님 false를 리턴.

.lastIndex가 가르키는 위치에서 검색을 시작.

예제코드

저작자 표시 변경 금지
Trackback 0: Comment 0

a태그의 href속성에 자바스크립트 함수 연결하기

<a href="javascript:theFunc();" >펑션</a>

예전에 어디에선가 링크로 연결해야 하면, a 태그를 쓰고, 자바스크립트 함수를 연결해야 하면, button 태그를 쓰란 말을 들은 적이 있습니다.

하지만 기존에 a 태그로 되어 있고, 이를 자바스크립트 이벤트 핸들러에 연결해야 하는 경우라면, 더욱이 button 으로 고치면 디자인이 깨지는 경우라면, 그냥 아래와 같이 쓰기로 마음 먹었습니다.

<a href="javascript:;" onclick="theFunc();" >펑션</a>
저작자 표시 변경 금지
Trackback 0: Comment 0