스프링프레임워크 태그 사용법

스프링프레임워크의 JSP 기술중에 form taglib 가 있습니다. form 태그라이브러리를 사용하면 HTML 폼에 데이터를 바인딩하거나 에러메세지 처리등을 간편하게 할 수 있습니다. 스프링프레임워크 form

offbyone.tistory.com

 

 

스프링 폼태그와 벨리데이션 체크

회원가입에서 많이 사용되는 …

seonhyungjo.github.io

build.gradle에 의존성 추가

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'
}

 

ORM 기술로 JPA, 보안을 위한 스프링 시큐리티, View 템플릿 타임리프와 롬복, MariaDB 등을 추가했습니다.

 

Config 패키지 생성 후 Sring Security 관리 클래스 생성

package com.sh.springsec.config;

import com.sh.springsec.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@RequiredArgsConstructor
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserService userService;

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/css/**", "/js/**", "/img/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login", "/signup", "/user").permitAll()
                .antMatchers("/").hasRole("USER")
                .antMatchers("/admin").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login") // 로그인 페이지 링크
                .defaultSuccessUrl("/") // 로그인 성공 후 리다이렉트 주소
                .and()
                .logout()
                .logoutSuccessUrl("/login") // 로그아웃 성공시 리다이렉트 주소
                .invalidateHttpSession(true); // 세션 날리기
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }
}

 

Spring Security를 사용하기 위해 WebSecurityConfigurerAdater를 상속받은 Security Config 클래스를 만들었습니다. Spring Security 사용을 위해서는 @EnableWebSecurity 어노테이션을 달아줘야 합니다. 위에서 오버라이딩한 메소드는 configure 메소드는 각각 WebSecurity, HttpSecurity와 AuthenticationManagerBuilder를 매개변수로 받습니다.

 

메소드 역할

public void configure(WebSecurity web) {

    web.ignoring().antMatchers("/css/**", "/js/**", "/img/**");

}

 

스프링 시큐리티 인증 없이도 접근 가능하게 할 경로를 설정합니다.

 

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/login", "/signup", "/user").permitAll()
        .antMatchers("/").hasRole("USER")
        .antMatchers("/admin").hasRole("ADMIN")
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .defaultSuccessUrl("/")
        .and()
        .logout()
        .logoutSuccessUrl("/login")
        .invalidateHttpSession(true);
}

 

권한에 따라 접근할 수 있는 경로를 지정합니다.

 

메소드 역할
.authorizeRequests() 시큐리티 처리에 HttpServletRequest를 사용
.antMatchers(String) 특정 경로를 지정
.hasRole(String) 지정된 경로에 특정 권한을 가진 사용자만 접근 가능
.permitAll() 지정된 경로에 모든 사용자가 접근 가능
.anyRequest() 위에서 지정되지 않은 경로
.authenticated() 권한을 갖지 않은 사용자를 로그인 페이지로 리다이렉트
.formLogin() 커스텀 로그인 페이지에 관한 설정
.loginPage(String) 로그인 페이지 지정
.defaultSuccessUrl(String) 로그인 성공 시 리다이렉트 할 페이지 지정
.logout() 로그아웃 설정
.logoutSuccessUrl(String) 로그아웃 성공 시 리다이렉트 할 페이지 지정
.invalidateHttpSession(boolean) 로그아웃 후 사용자 권한과 세션의 제거 여부 설정

 

타임리프는 스프링 부트에서 공식적으로 지원하는 View 템플릿입니다. JSP와 달리 Thymeleaf 문서는 html 확장자를 갖고 있어 JSP처럼 Servlet이 문서를 표현하는 방식이 아니기 때문에 서버 없이도 동작 가능합니다.

 

Spring Boot 타임리프 기본 설정

 

1. Spring Boot에서 타임리프를 사용하기 위해서는 라이브러리를 추가해야 합니다.

 

MVNRepository Spring Boot Starter Thymeleaf

 

2. 타임리프를 적용할 HTML 문서를 작성하고 상단 <html> 태그 내부에 다음과 같이 작성합니다.

 

<!DOCTYPE html>


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


<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>

 

타임리프 사용법

 

타임리프에서는 JSP처럼 서버에서 받아온 데이터를 ${ } 을 이용하여 표기합니다.

 

 

컨트롤러 부분

 

컨트롤러에서 Model을 통해 'name'이란 이름에 'Rooney'를 넣어 View 부분으로 보냅니다.

 

@RequestMapping("/article")
public class ArticleController {
    
    
    @GetMapping("/list")
    public String articleList(Model model) {
    
        model.addAttribute("name", "Rooney");
        
        return "article/list";
    }
}

 

View(타임리프) 부분

 

타임리프 문법 중 글씨를 출력하는 th:text=""에 넘긴 데이터 ${name}을 넣어주면 위에 컨트롤러에서 매핑한 /article/list로 접속했을 때 화면에 Rooney가 출력됩니다.

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div th:text="${name}"></div>

</body>
</html>

 

"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."


타임리프 문법

 

타임리프 문법은 공식 홈페이지를 참고해주세요.

 

 

Tutorial: Using Thymeleaf

1 Introducing Thymeleaf 1.1 What is Thymeleaf? Thymeleaf is a modern server-side Java template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. The main goal of Thymeleaf is to provide a

www.thymeleaf.org

 

타임리프 자주 사용하는 문법

 

문법 역할 예제
th:text 문자열 생성 th:text=" ${data} "
th:each 반복문 th:each="article : ${articleList}"
th:if if 조건문 th:if=${data != null}
th:href 이동 경로 th:href=" @{/article/list(id= ${data} )} "

 

Spring에서 테스트 클래스 사용을 위한 두 가지 어노테이션들에 대해 알아봅시다.

 

우선, Mokito를 사용하기 위해서는 아래와 같은 코드 작성을 해줘야 합니다. 테스트클래스 위에 @RunWith 어노테이션을 작성하여 Mock 객체를 사용하거나, @RunWith 어노테이션을 작성하지 않을 경우 setUp() 메소드를 아래처럼 만들어줍니다. 

 

@RunWith(MokitoJunitRunner.class)
public class TestClass {

}

public class TestClass {

    @BeforeEach
    public void setUp() {
        MokitoAnnotations.initMocks(this);
    }
}

 

@Mock

 

실제 인스턴스가 없는 가상의 Mock 인스턴스를 만들어 반환합니다.

 

@MockBean

 

ApplicationContext에 Mock 객체를 추가합니다.

 

@InjectMock

 

@Mock이나 @Spy 객체를 자신의 멤버 클래스와 일치하면 주입합니다.

 

@SpyBean

 

ApplicationContext에 Spy 객체를 추가합니다.

 

 

@Mock, @MockBean의 차이

 

@MockBean은 @Mock과 달리 spring-boot-test에서 제공하는 어노테이션으로, Spring이 관리하는 Bean들 중에서 하나 이상을 Mock 객체로 사용하고 싶을 때 사용합니다.

+ Recent posts