네로개발일기

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

'web/Spring'에 해당되는 글 67건


반응형

1. Mybatis resultMap 기능

mybatis는 ORM 기술 중 하나이다. ORM(Object Relational Mapping)이란 객체 지향 언어의 객체와 관계형 데이터를 서로 변환해준다는 것이다.

DB 조회 결과를 복잡한 객체 구조로 변환해야 할 때 mybatis의 resultMap 기능을 사용한다. 여러 테이블의 조인 결과를 여러 자바 객체에 담을 때 resultMap 기능이 유용하다.

 

2. Mybatis mapper 구현 방법

1) annotation으로 구현하기

간단한 SQL을 구현할 때 annotation을 이용하여 구현하는 것이 편하다.

2) mapper XML에서 구현하기

mybatis resultMap 기능을 구현하려면 mapper XML 파일에 구현하는 것이 편하다.

 

mapper/RegisterMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis//DTD Mapper 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-mapper .dtd">

<mapper namespace="mapper.RegisterMapper">
    <resultMap id="RegisterwithStudentCourse" type="dto.Register">
        <id property="id" column="id" />
        <result property="studentId" column="studentId" />
        <result property="courseId" column="courseId" />
        <result property="grade" column="grade" />
        <result property="createDate" column="createDate" />
        <association property="student" javaType="dto.Student">
            <id property="id" column="studentId" />
            <result property="studentNumber" column="studentNumber" />
            <result property="name" column="studentName" />
        </association>
        <association property="course" javaType="dto.Course">
            <id property="id" column="courseId" />
            <result property="courseName" column="courseName" />
            <result property="unit" column="unit" />
        </association>
    </resultMap>
</mapper>

 

<mapper namespace="mapper.RegisterMapper">

RegistMapper에 대한 SQL 명령이나 resultMap 등을 정의하기 위한 mapper 태그이다.

패키지까지 포함해서 mapper 클래스의 이름을 적는다.

 

<resultMap id="RegisterwithStudentCourse" type="dto.Register">

조회 결과를 Regist 객체로 채우는 방법을 정의한다. SQL 조회 결과를 Java 객체 구조에 채우는 방법을 정의한 것이 resultMap이다.

 

<id property="id" column="id" />

조회 결과의 id 칼럼은 Register 클래스의 id 속성(property)에 채운다. 이 칼럼이 테이블의 기본키(primary)이기 때문에 <id> 태그를 사용한다.

 

<result property="studentId" column="studentId" />

조회 결과의 studentId 칼럼을 Register 클래스의 studentId 속성에 채운다. 테이블의 기본키가 아니기 때문에 <result> 태그를 사용한다.

 

<association property="student" javaType="dto.Student">

Register 클래스의 student 속성에 Student 객체를 대입한다.

 

/mapper/RegisterMapper.java

import java.util.List; 

import org.apache.ibatis.annotations.Mapper; 
import org.apache.ibatis.annotations.ResultMap; 
import org.apache.ibatis.annotations.Select; 

import dto.Register; 

@Mapper 
public interface RegisterMapper { 

    @ResultMap("RegisterWithStudentAndCourse") 
    @Select("SELECT r.*, s.studentNumber, s.name studentName, c.courseName, c.unit " + 
            " FROM register r JOIN student s ON r.studentId = s.id " + 
            " JOIN course c ON r.courseId = c.id " + 
            " ORDER BY s.studentNumber ") 
    List<Register> findAll(); 
}

 

@ResultMap("RegisterWithStudentAndCourse")

 

RegisterMapper.xml 파일의 id="RegisterWithStudentAndCourse" resultMap 방법으로 조회 결과를 Java 객체들에 채워서 리턴한다.

728x90
반응형
blog image

Written by ner.o

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

반응형

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

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

반응형

[텍스트를 출력하는 기능 - 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

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