'Spring'에 해당되는 글 49건

  1. 2020.10.13 [Spring] WebSocket 관련 링크
  2. 2020.07.23 [Spring] Spring Security Session Timeout Disable.
  3. 2020.07.21 [Spring] viewResolver return types...
  4. 2020.07.07 [Spring] Spring Security 기본 Login Form 제거 및 CSRF 만 사용하기
  5. 2020.07.06 [Spring] 다국어(i18n) 적용 하기.
  6. 2020.06.25 [Spring] Spring Cloud Config 설정 파일 적용
  7. 2020.06.25 [Spring] Spring boot tomcat relaxedQueryChars
  8. 2020.06.18 [Spring] Spring Cloud Config 다중 Backend 사용 시...
  9. 2020.06.16 [Spring] @RefreshScope 적용 시 반영이 잘 안될 때
  10. 2020.06.01 [Spring] Spring boot jar build and run.

[Spring] WebSocket 관련 링크

ITWeb/개발일반 2020. 10. 13. 12:08
https://spring.io/guides/gs/messaging-stomp-websocket/

https://stomp.github.io/stomp-specification-1.2.html

https://github.com/sockjs/sockjs-client

WebSocket 관련 개발 참고 문서 입니다.

:

[Spring] Spring Security Session Timeout Disable.

ITWeb/개발일반 2020. 7. 23. 07:55

application.yml 또는 properties 파일 내 아래와 같이 선언 하시면 됩니다.

server:
  servlet:
    session:
      timeout: 0

 

:

[Spring] viewResolver return types...

ITWeb/개발일반 2020. 7. 21. 10:45

[참고문서]

https://docs.spring.io/spring/docs/4.3.12.RELEASE/spring-framework-reference/htmlsingle/#mvc-ann-return-types

https://docs.spring.io/spring/docs/3.0.0.M3/spring-framework-reference/html/ch16s03.html

 

Spring mvc framework 에서 Controller 에서 사용하는 return type 에 따른 viewResolver 적용방법이 다릅니다.

위 문서를 보시면 이해 하실 수 있습니다.

 

가장 많이 사용 하는 몇 개만 뽑아 왔습니다.

 

  • A ModelAndView object, with the model implicitly enriched with command objects and the results of @ModelAttribute annotated reference data accessor methods.
  • A Model object, with the view name implicitly determined through a RequestToViewNameTranslator and the model implicitly enriched with command objects and the results of @ModelAttribute annotated reference data accessor methods.
  • A Map object for exposing a model, with the view name implicitly determined through a RequestToViewNameTranslator and the model implicitly enriched with command objects and the results of @ModelAttribute annotated reference data accessor methods.
  • A View object, with the model implicitly determined through command objects and @ModelAttribute annotated reference data accessor methods. The handler method may also programmatically enrich the model by declaring a Model argument (see above).
  • A String value that is interpreted as the logical view name, with the model implicitly determined through command objects and @ModelAttribute annotated reference data accessor methods. The handler method may also programmatically enrich the model by declaring a Model argument (see above).
  • void if the method handles the response itself (by writing the response content directly, declaring an argument of type ServletResponse / HttpServletResponse for that purpose) or if the view name is supposed to be implicitly determined through a RequestToViewNameTranslator (not declaring a response argument in the handler method signature).
  • If the method is annotated with @ResponseBody, the return type is written to the response HTTP body. The return value will be converted to the declared method argument type using HttpMessageConverters. See the section called “Mapping the response body with the @ResponseBody annotation”.

제가 실수한 부분은 void 로 선언을 해 놓고 template 수정 후 반영이 되지 않아 cache 를 의심 했었는데 역시 원인은 제가 선언을 잘 못 했기 때문 이였습니다.

 

void 로 선언 시 해석은 

@GetMapping("/hello")
public void helloworld() {...}

hello.html 을 template 으로 찾게 됩니다.

 

:

[Spring] Spring Security 기본 Login Form 제거 및 CSRF 만 사용하기

ITWeb/개발일반 2020. 7. 7. 08:33

사용하다 보면 별의 별 요구사항이 나오게 됩니다.

단순 하게 CSRF 만 사용 하고 싶은데 자꾸 login form 이 나와서 설정만으로 이걸 해결해 보고자 했습니다.

그러나 설정 만으로는 안되더라고요.

 

설정 예시) 비추천

security:
  enable:
    csrf: true
  basic:
    enabled: false

management:
  security:
    enabled: false

 

코드 예시) 추천

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.httpBasic().disable();
  }
}

참고 정보)

dependencies {
  implementation 'org.springframework.boot:spring-boot-starter-quartz'
  implementation 'org.springframework.boot:spring-boot-starter-web'

  // thymeleaf
  implementation 'org.thymeleaf.extras:thymeleaf-extras-java8time'
  implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
  implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'

  // spring security
  implementation 'org.springframework.boot:spring-boot-starter-security'
  implementation 'org.springframework.security:spring-security-test'
  implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'

  implementation 'org.webjars:jquery:3.5.0'
  implementation 'org.webjars:jquery-ui:1.12.1'
  implementation 'org.webjars.bower:bootstrap:4.4.0'

  compileOnly 'org.projectlombok:lombok'
  annotationProcessor 'org.projectlombok:lombok'
  providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
  testImplementation('org.springframework.boot:spring-boot-starter-test') {
    exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
  }
}


<meta id="_csrf" name="_csrf" th:content="${_csrf.token}" />
<meta id="_csrf_header" name="_csrf_header" th:content="${_csrf.headerName}" />

let token = $("meta[name='_csrf']").attr("content");
let header = $("meta[name='_csrf_header']").attr("content");

$(function() {
  $(document).ajaxSend(function(e, xhr, options) {
    xhr.setRequestHeader(header, token);
  });
});


spring:
  security:
    user:
      name: admin
      password: admin

 

 

:

[Spring] 다국어(i18n) 적용 하기.

ITWeb/개발일반 2020. 7. 6. 16:08

다국어를 적용 하기 위한 Code Snippet

 

1. Javascript

- 구글링 해보시면 몇 가지 framework 들이 나옵니다.

- 쉽게 구현을 한다고 하면, 현재의 locale 정보를 cookie 또는  session 에서 읽어 와서 해당 하는 locale 의 message 파일 또는 변수를 가지고 설정 하면 됩니다.

 

예제)

let MESSAGE = new Object();
let INTL = MESSAGE["ko"];

document.addEventListener("DOMContentLoaded", function(){
  let applicationLocale;

  try {
    applicationLocale = $.cookie("APPLICATION_LOCALE");
  } catch (e) {
  }

  if(!applicationLocale) {
    applicationLocale = "ko";
  }

  INTL = MESSAGE[applicationLocale];
});

MESSAGE.ko = {
  "HELLO": "안녕"
};

MESSAGE.en = {
  "HELLO": "Hello"
};

MESSAGE.ja = {
  "HELLO": "こんにちは"
};

- 여기서 원래는 jquery 를 이용 하다 보니 $ 가 들어 갔었는데 $(document).ready(); 였으나 $를 찾지 못해서 걍 바꿔 놓았습니다.

- 코드 설명은 쉽습니다. 그냥 정적으로 정의해서 사용 하는 내용이라 보시면 다 아실 것 같습니다.

 

2. Spring Boot + Thymeleaf

Cookie 와 Session 두 가지로 적용이 가능 합니다.

구글링 해보시면 거의 똑같은 코드로 예제들이 나올 거예요.

그냥 담는 그릇을 Cookie 로 할건지 Session 으로 할 건지의 차이 라고 보시면 됩니다.

- 프로젝트에서 "Resource Bundle 'messages'" 를 추가해 주세요.

- 추가 하면서, ko, en, ja, zh 생성 하시면 됩니다.

- messages.properties

- messages_ko.properties

HELLO=안녕

- messages_en.properties

HELLO=Hello

- messages_zh.properties

- messages_ja.properties

HELLO=こんにちは

 

2.1 Session

@Configuration
public class LocaleConfig implements WebMvcConfigurer {

  @Bean
  public LocaleResolver localeResolver() {

    SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
    sessionLocaleResolver.setDefaultLocale(Locale.KOREAN);

    return sessionLocaleResolver;
  }

  @Bean
  public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
    localeChangeInterceptor.setParamName("locale");
    
    return localeChangeInterceptor;
  }

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
  }

}

 

2.2 Cookie

@Configuration
public class LocaleConfig implements WebMvcConfigurer {

  @Bean
  public LocaleResolver localeResolver() {

    CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
    cookieLocaleResolver.setDefaultLocale(Locale.KOREAN);
    cookieLocaleResolver.setCookieName("APPLICATION_LOCALE");
    return cookieLocaleResolver;
  }

  @Bean
  public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
    localeChangeInterceptor.setParamName("locale");
    return localeChangeInterceptor;
  }

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
  }

}

그래서 Thymeleaf 에서는 아래와 같이 쓰시면 됩니다.

<h1 th:text="#{HELLO}"></h1>

 

:

[Spring] Spring Cloud Config 설정 파일 적용

ITWeb/개발일반 2020. 6. 25. 14:29

spring config client  에 server config 파일이 존재 할 경우 적용 안되는 문제를 해결 하기 위해 아래 설정을 하면 됩니다.

 

https://cloud.spring.io/spring-cloud-static/spring-cloud-commons/2.2.2.RELEASE/reference/html/#overriding-bootstrap-properties

 

1.4. Overriding the Values of Remote Properties

The property sources that are added to your application by the bootstrap context are often “remote” (from example, from Spring Cloud Config Server). By default, they cannot be overridden locally. If you want to let your applications override the remote properties with their own system properties or config files, the remote property source has to grant it permission by setting spring.cloud.config.allowOverride=true (it does not work to set this locally). Once that flag is set, two finer-grained settings control the location of the remote properties in relation to system properties and the application’s local configuration:

  • spring.cloud.config.overrideNone=true: Override from any local property source.

  • spring.cloud.config.overrideSystemProperties=false: Only system properties, command line arguments, and environment variables (but not the local config files) should override the remote settings.

spring:
  cloud:
    config:
      uri: xxxx
      allowOverride: true
      overrideNone: true
      overrideSystemProperties: false

 

:

[Spring] Spring boot tomcat relaxedQueryChars

ITWeb/개발일반 2020. 6. 25. 11:35

https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#server-properties

 

Common Application properties

Various properties can be specified inside your application.properties file, inside your application.yml file, or as command line switches. This appendix provides a list of common Spring Boot properties and references to the underlying classes that consume

docs.spring.io

https://tomcat.apache.org/tomcat-9.0-doc/config/http.html

 

Apache Tomcat 9 Configuration Reference (9.0.36) - The HTTP Connector

This Connector supports all of the required features of the HTTP/1.1 protocol, as described in RFCs 7230-7235, including persistent connections, pipelining, expectations and chunked encoding. If the client supports only HTTP/1.0 or HTTP/0.9, the Connector

tomcat.apache.org

 

server.tomcat.relaxed-path-chars

Comma-separated list of additional unencoded characters that should be allowed in URI paths. Only "< > [ \ ] ^ ` { | }" are allowed.

server.tomcat.relaxed-query-chars

Comma-separated list of additional unencoded characters that should be allowed in URI query strings. Only "< > [ \ ] ^ ` { | }" are allowed.

relaxedPathChars

The HTTP/1.1 specification requires that certain characters are %nn encoded when used in URI paths. Unfortunately, many user agents including all the major browsers are not compliant with this specification and use these characters in unencoded form. To prevent Tomcat rejecting such requests, this attribute may be used to specify the additional characters to allow. If not specified, no additional characters will be allowed. The value may be any combination of the following characters: " < > [ \ ] ^ ` { | } . Any other characters present in the value will be ignored.

relaxedQueryChars

The HTTP/1.1 specification requires that certain characters are %nn encoded when used in URI query strings. Unfortunately, many user agents including all the major browsers are not compliant with this specification and use these characters in unencoded form. To prevent Tomcat rejecting such requests, this attribute may be used to specify the additional characters to allow. If not specified, no additional characters will be allowed. The value may be any combination of the following characters: " < > [ \ ] ^ ` { | } . Any other characters present in the value will be ignored.

의도치 않게 tomcat 에서 에러 처리를 해버려서 이를 방지 하기 위해 설정 후 application 에서 처리 하시면 됩니다.

:

[Spring] Spring Cloud Config 다중 Backend 사용 시...

ITWeb/개발일반 2020. 6. 18. 10:41

Spring Cloud Config 를 이용해서 다중 Backend 를 구성 할 수 있습니다.

그러나 order 옵션이 저는 제대로 동작 하지 않아서 실행 시 사용해야 하는 Backend 에 대한 profile 로 관리하기로 했습니다.

 

동시에 두 개의 Backend 를 사용 하는 것도 가능 한데 이게 같은 설정 파일이 양쪽에 다 존재 할 때 order 에 맞춰서 설정 정보를 가져 와야 하는데 이상하게도 git 에 있는 설정을 먼저 가져 와서 목적에 맞게 사용을 할 수 없었습니다.

 

spring:
  application:
    name: config-server
  profiles:
    active: awss3, git
  cloud:
    config:
      server:
        awss3:
          region: ap-northeast-2
          bucket: ${BUCKET-NAME}
          order: 1
        git:
          uri: https://git/config-repo.git
          skipSslValidation: true
          username: xxxxx
          password: xxxxx
          clone-on-start: true
          order: 2

저렇게 설정 하고 했었는데 잘 못된 부분이 있다면 댓글 좀 달아 주세요. :)

 

profile을 실행 시점에 awss3 나 git 으로 설정해서 사용 하도록 마무리 했습니다.

:

[Spring] @RefreshScope 적용 시 반영이 잘 안될 때

ITWeb/개발일반 2020. 6. 16. 14:51

일단 spring config server 에서 설정을 변경해서 적용 합니다.

 

POST , /actuator/refresh 를  실행 합니다.

 

그럼 기대 하는 건 변경 된 설정 값이 반영이 되어 있어야 한다는 것입니다.

 

그러나 반영이 안되어 있어서 디버깅 하다 아래와 같이 event 를 잡아서 처리를 해주니 잘되는 것을 확인 했습니다.

 

  @EventListener(RefreshScopeRefreshedEvent.class)
  public void onRefresh() {
    log.debug("triggering ----> {}", watcherThreshold);
  }

참고해서 보셔야 하는 코드는 아래 입니다.

/*
 * Copyright 2012-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.cloud.context.scope.refresh;

import java.io.Serializable;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.cloud.context.scope.GenericScope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;

/**
 * <p>
 * A Scope implementation that allows for beans to be refreshed dynamically at runtime
 * (see {@link #refresh(String)} and {@link #refreshAll()}). If a bean is refreshed then
 * the next time the bean is accessed (i.e. a method is executed) a new instance is
 * created. All lifecycle methods are applied to the bean instances, so any destruction
 * callbacks that were registered in the bean factory are called when it is refreshed, and
 * then the initialization callbacks are invoked as normal when the new instance is
 * created. A new bean instance is created from the original bean definition, so any
 * externalized content (property placeholders or expressions in string literals) is
 * re-evaluated when it is created.
 * </p>
 *
 * <p>
 * Note that all beans in this scope are <em>only</em> initialized when first accessed, so
 * the scope forces lazy initialization semantics.
 * </p>
 *
 * <p>
 * The scoped proxy approach adopted here has a side benefit that bean instances are
 * automatically {@link Serializable}, and can be sent across the wire as long as the
 * receiver has an identical application context on the other side. To ensure that the two
 * contexts agree that they are identical, they have to have the same serialization ID.
 * One will be generated automatically by default from the bean names, so two contexts
 * with the same bean names are by default able to exchange beans by name. If you need to
 * override the default ID, then provide an explicit {@link #setId(String) id} when the
 * Scope is declared.
 * </p>
 *
 * @author Dave Syer
 * @since 3.1
 *
 */
@ManagedResource
public class RefreshScope extends GenericScope implements ApplicationContextAware,
		ApplicationListener<ContextRefreshedEvent>, Ordered {

	private ApplicationContext context;

	private BeanDefinitionRegistry registry;

	private boolean eager = true;

	private int order = Ordered.LOWEST_PRECEDENCE - 100;

	/**
	 * Creates a scope instance and gives it the default name: "refresh".
	 */
	public RefreshScope() {
		super.setName("refresh");
	}

	@Override
	public int getOrder() {
		return this.order;
	}

	public void setOrder(int order) {
		this.order = order;
	}

	/**
	 * Flag to determine whether all beans in refresh scope should be instantiated eagerly
	 * on startup. Default true.
	 * @param eager The flag to set.
	 */
	public void setEager(boolean eager) {
		this.eager = eager;
	}

	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
			throws BeansException {
		this.registry = registry;
		super.postProcessBeanDefinitionRegistry(registry);
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		start(event);
	}

	public void start(ContextRefreshedEvent event) {
		if (event.getApplicationContext() == this.context && this.eager
				&& this.registry != null) {
			eagerlyInitialize();
		}
	}

	private void eagerlyInitialize() {
		for (String name : this.context.getBeanDefinitionNames()) {
			BeanDefinition definition = this.registry.getBeanDefinition(name);
			if (this.getName().equals(definition.getScope())
					&& !definition.isLazyInit()) {
				Object bean = this.context.getBean(name);
				if (bean != null) {
					bean.getClass();
				}
			}
		}
	}

	@ManagedOperation(description = "Dispose of the current instance of bean name "
			+ "provided and force a refresh on next method execution.")
	public boolean refresh(String name) {
		if (!name.startsWith(SCOPED_TARGET_PREFIX)) {
			// User wants to refresh the bean with this name but that isn't the one in the
			// cache...
			name = SCOPED_TARGET_PREFIX + name;
		}
		// Ensure lifecycle is finished if bean was disposable
		if (super.destroy(name)) {
			this.context.publishEvent(new RefreshScopeRefreshedEvent(name));
			return true;
		}
		return false;
	}

	@ManagedOperation(description = "Dispose of the current instance of all beans "
			+ "in this scope and force a refresh on next method execution.")
	public void refreshAll() {
		super.destroy();
		this.context.publishEvent(new RefreshScopeRefreshedEvent());
	}

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		this.context = context;
	}

}

 

refreshAll() 을 호출 하게 되어서 반영이 잘됩니다.

 

더불어 그냥 프레임워크에서 제공하는 @Scheduled 사용 하십시오.

 

  @Scheduled(fixedDelayString = "${megatoi.watcher.cpu.period}000")
  private void runner() {
    megatoiCheckerUtil.setWatcherThreshold(watcherThreshold);
    megatoiCheckerUtil.setPayload(getCheckQuery());
    megatoiCheckerUtil.setResourceType(ResourceType.CPU);
    megatoiCheckerUtil.commonRunner();
  }
:

[Spring] Spring boot jar build and run.

ITWeb/개발일반 2020. 6. 1. 18:05

build.gradle)
plugins {
  id 'org.springframework.boot' version '2.3.0.RELEASE'
...중략...
  id 'java'
  id 'war'
}

...중략...

task projectVersion {
  doLast {
    println "${project.version}"
  }
}

task jarName {
  doLast {
    println "${archivesBaseName}-${version}.jar"
  }
}

bootJar {
  archivesBaseName = "springboot-was"
}

war {
  enabled = true
  archivesBaseName = "springboot-was"
}

 

build)
$ ./gradlew clean build bootJar

 

run)
$ sudo java -Djava.security.egd=file:/dev/./urandom -jar springboot-was.jar

 

springboot 프로젝트로 빌드 후 embedded tomcat 으로 실행 하는 예제 입니다.

: