네로개발일기

개발자 네로의 개발 일기, 자바를 좋아합니다 !

'2022/01'에 해당되는 글 13건


반응형

1. 속성 파일 사용

가장 빠르고 쉬운 방법은 기본 속성 값을 재정의하는 것이다.

서버 포트를 설정하는 속성은 server.port 이다. spring boot의 기본 내장 포트는 8080이다.

 

application.properties

server.port=8081

application.yml

server:
  port: 8081

 

2. 프로그래밍 방식 구성

@SpringbootApplication 클래스에서 속성을 설정하는 방법이다.

@SpringBootApplication
public class CustomApplication {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(CustomApplication.class);
        app.setDefaultProperties(Collections
          .singletonMap("server.port", "8083"));
        app.run(args);
    }
}

서버 구성을 사용자 정의하려면 WebServerFactoryCustomizer 인터페이스 를 구현해야한다.

@Component
public class ServerPortCustomizer 
  implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> {
 
    @Override
    public void customize(ConfigurableWebServerFactory factory) {
        factory.setPort(8086);
    }
}

Spring Boot 2.x 버전부터 적용된다.

 

3. 명령어 사용

애플리케이션을 jar로 패키징하고 실행할 때 java 명령으로 server.port 인수를 설정할 수 있다.

$ java -jar spring.jar --server.port=8081

또는

$ java -jar -Dserver.port=8081 spring.jar

 

 

출처

https://recordsoflife.tistory.com/325

 

Spring Boot에서 기본 포트를 변경하는 방법

If you have a few years of experience in the Java ecosystem, and you're interested in sharing that experience with the community (and getting paid for your work of course), have a look at the "Write..

recordsoflife.tistory.com

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

1. Export MySQL Database

> mysqldump -u username -p database_name > dbname.sql

2. Import MySQL Database

> mysql -p -u username database_name < file.sql

 

출처

https://gesatech.net/knowledgebase/50/MySQL-Import-and-Export-.sql-file-via-SSH.html

 

MySQL Import and Export (.sql file) via SSH - Knowledgebase - Gesatech Solutions - Customer Centre

Please enter a number between 8 and 64 for the password length Generate new password Copy

gesatech.net

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

[텍스트를 출력하는 기능 - text, utext]

 

타임리프는 기본적으로 HTML 태그의 속성에 기능을 정의해서 동작한다. HTML의 콘텐츠(content)에 데이터를 출력할 때는 다음과 같이th:text를 사용한다.

<span th:text="${data}"></span>

HTML 태그의 속성이 아니라 HTML 콘텐츠 영역 안에서 직접 데이터를 출력하고 싶으면 다음과 같이 [[...]]를 사용하면 된다.

[[${data}]]

 

BasicController.java

@Controller
@RequestMapping("/basic")
public class BasicController {
    @GetMapping("/text-basic")
    public String textBasic(Model model) {
        model.addAttribute("data", "Hello Spring!");
        return "basic/text-basic";
    }
}

/resources/templates/basic/text-basic.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>데이터 출력</h1>
    <ul>
        <li>th:text 사용 <span th:text="${data}"></span></li>
        <li>직접 출력 [[${data}]]</li>
    </ul>
</body>
</html>

 

# Escape

HTML 문서는 <, > 같은 특수 문자를 기반으로 정의된다. 따라서 뷰 템플릿으로 HTML 화면을 생성할 때는 출력하는 데이터에 이러한 특수문자가 있는 것을 주의해서 사용해야 한다. 

 

BasicController에서 "Hello Spring!""Hello <b>Spring!</b>"로 변경해보면

웹 브라우저에서 그대로 출력됨. => Hello <b>Spring!</b>

소스에서는 Hello &lt;b&gt;Spring!&lt;/b&gt;

 

HTML 엔티티

웹 브라우저는 <를 HTML 태그의 시작으로 인식한다. 따라서 <를 태그의 시작이 아니라 문자로 표햔할 수 있는 방법이 필요하다. HTML에서 사용하는 특수문자로 HTML 엔티티로 변경하는 것을 이스케이프(escape)라고 한다. 타임리프가 제공하는 th:text, [[...]]기본적으로 이스케이프(escape)를 제공한다.

 

- < => &lt;

- > => &gt;

 

# Unescape

타임리프는 다음 두 기능을 제공한다.

- th:utext

- [(...)]

 

=> escape를 사용하지 않아서 HTML이 정상 렌더링이 되지 않는 문제가 발생할 수 있으므로 escape를 기본으로 하고 unescape는 필요할 때만 사용하는 것으로 !

 

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

# 타임리프의 특징

1. 서버사이드 HTML 렌더링 (SSR)

JSP처럼 타임리프는 백엔드 서버에서 HTML을 동적으로 렌더링 하는 용도로 사용한다. 

 

2. 네츄럴 템플릿

타임리프는 순수 HTML을 최대한 유지하는 특징이 있다. 

타임리프로 작성한 파일은 HTML을 유지하기 때문에 웹 브라우저에서 파일을 직접 열어도 내용을 확인할 수 있고, 서버를 통해 뷰 템플릿을 거치면 동적으로 변경된 결과를 확인할 수 있다.

JSP를 포함한 다른 뷰 템플릿은 해당 파일을 열면, 예를 들어 JSP 파일 자체를 웹 브라우저에서 열면 정상적인 HTML 결과를

반면에 타임리프로 작성된 파일은 해당 파일을 그대로 웹 브라우저에서 열어도 정상적인 HTML 결과를 확인할 수 없다. 오직 서버를 통해서 JSP가 렌더링되고 HTML 응답 결과를 받아야 화면을 확인할 수 있다.

반면에, 타임리프로 작성된 파일은 그대로 웹 브라우저에서 열어도 정상적인 HTML 결과를 확인할 수 있다. 물론 이 경우 동적으로 결과가 렌더링되지 않는다.

순수 HTML을 그대로 유지하면서 뷰 템플릿도 사용할 수 있는 타임리프의 특징을 네츄럴 템플릿(natural templates)이라 한다.

 

3. 스프링 통합 지원

자연스럽게 통합되고, 스프링의 다양한 기능을 편리하게 사용할 수 있게 지원한다.

 

 

# 타임리프 기본 기능

타임리프 사용 선언

<html xmlns:th="http://www.thymeleaf.org">

기본 표현식

- 간단한 표현

    * 변수 표현식 ${...}

    * 선택 변수 표현식 *{...}

    * 메시지 표현식 #{...}

    * 링크 URL 표현식 @{...}

    * 조각 표현식 ~{...}

- 리터럴

    * 텍스트 'text', 'Spring' , ...

    * 숫자 0, 421, 4.0

    * 불린 true, false

    * 널 null

    * 리터럴 토큰 one, sometext, main, ...

- 문자 연산

    * 문자 합치기 +

    * 리터럴 대체 |The name is ${name}|

- 산술 연산

    * Binary operators +, -, *, /, %

    * Minus sign (unary operator) -

- 불린 연산

    * Binary operators: and, or

    * Boolean negation (unary operator) !, not

- 비교와 동등

    * 비교 >, <, >=, <= (gt, lt, ge, le)

    * 동등 연산 ==, != (eq, ne)

- 조건 연산

    * If-then (if) ? (then)

    * If-then-else (if) ? (then) : (else)

    * Default (value) ?: (defaultvalue)

- 특별한 토큰

    * No-Operation _

 

 

 

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

[이전 글]

 

[Spring] RestTemplate / spring 에서 http 통신하는 법 / API 호출

🐝 Rest 서비스를 호출하는 방법 - RestTemplate Spring 3부터 지원, REST API 호출 이후 응답을 받을 때까지 기다리는 동기 방식 - AsyncRestTemplate Spring 4에 추가된 비동기 RestTemplate - WebClient Spring..

frogand.tistory.com

 

🌱 UriComponentsBuilder

org.springframework.web.util.UriComponentsBuilder를 사용하면 명확한 URI 문자열을 생성할 수 있다.

final String uri = "https://frogand.tistory.com";
final String uriWithParameter = UriComponentsBuilder.fromHttpUrl(uri)
                                    .path("/category/programming/ECMAScript6"
                                    .queryParam("page", 2)
                                    .toString();
// https://frogand.tistory.com/category/programming/ECMAScript6?page=2

 

예제) parameter가 있는 url로 HTTP GET Method 호출

public static List<DataDto> selectDataByMemberId(String memberId) {
    if (StringUtils.isEmpty(memberId)) {
        return null;
    }

    final String selectDataUrl = "http://localhost:8080" + "/api/Data";
    String httpUrl = UriComponentsBuilder.fromHttpUrl(selectDataUrl)
            .queryParam("memberId", memberId)
            .toUriString();

    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<List<DataDto>> userRecommendResponse = 
            restTemplate.exchange(
            httpUrl,
            HttpMethod.GET, 
            null, 
            new ParameterizedTypeReference<List<DataDto>>() {
            });

    return userRecommendResponse.getBody();
}

 

 

출처

https://stackoverflow.com/questions/8297215/spring-resttemplate-get-with-parameters

 

Spring RestTemplate GET with parameters

I have to make a REST call that includes custom headers and query parameters. I set my HttpEntity with just the headers (no body), and I use the RestTemplate.exchange() method as follows: HttpHead...

stackoverflow.com

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !