[Spring]Spring Security_1

김피자·2023년 3월 7일
0

Spring

목록 보기
16/28
post-thumbnail

프로젝트 생성


https://start.spring.io/

Maven
Java 11
2.7.9
com.cos.security1
jar

Dependencies
Spring Web
MySQL Driver
Spring Boot DevTools
Lombok
Mustache
Spring Data JPA
Spring Security


MySQL 스키마 생성

create user 'cos'@'%' identified by 'cos1234';
GRANT ALL PRIVILEGES ON *.* TO 'cos'@'%';
create database security;
use security;

application.yml

server:
  port: 8080
  servlet:
    context-path: /
    encoding:
      charset: UTF-8
      enabled: true
      force: true
      
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/security?serverTimezone=Asia/Seoul
    username: cos
    password: cos1234
    
  jpa:
    hibernate:
      ddl-auto: update #create update none
      naming:
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    show-sql: true

yml 파일 말고 properties 파일이라면 아래 것을 사용하면된다.

server.port=8080
server.servlet.context-path=/
server.servlet.encoding.charset=UTF-8
server.servlet.encoding.enabled=true
server.servlet.encoding.force=true

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/security?serverTimezone=Asia/Seoul
spring.datasource.username=cos
spring.datasource.password=cos1234
spring.mvc.view.prefix=/templates/
spring.mvc.view.suffix=.mustache
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

IndexController 생성

package com.cos.security1.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller // View를 리턴한다
public class IndexController {
    //localhost:8082/
    //localhost:8082
    @GetMapping({"","/"})
    public String index(){
        //application.propeertise에 뷰 리졸버 설정 templates (prefix), .mostache (suffix) 생략 가능 
        //머스테치 파일의 기본 경로 src/main/resources/ 
        return "index"; 
    }
}

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Index</title>
</head>
<body>
<h1>인덱스 페이지 입니다.</h1>
</body>
</html>

컨트롤러의 index()메소드를 보면 index.mostache 페이지를 찾아 반환하도록 되어있는데 우리는 html의 확장자로 파일을 작성햇다.

mostache로 변환하면 복잡해지기 때문에 .html을 등록 하겠습니다!


WebMvcConfig 생성

package com.cos.security1.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration // 이 자바 파일을 IoC로 등록하기위해 어노테이션을 붙여준다.
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        MustacheViewResolver resolver = new MustacheViewResolver(); //기존 설정 재설정 
        resolver.setCharset("UTF-8"); //내가 만드는 뷰의 인코딩
        resolver.setContentType("text/html; charset=UTF-8"); //내가 너한테 던지는 데이터는 html 파일이야
        resolver.setPrefix("classpath:/templates/");
        resolver.setSuffix(".html");

        registry.viewResolver(resolver);
    }
}

이렇게 .html 파일을 만들어도 mostache가 인식을 하게된다.

프로젝트 실행! 하면

원래대로라면 정상적으로 실행이 되어야하는데 나는 여기서 오류가 났다.

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class


Action:

Consider the following:
	If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
	If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).


Process finished with exit code 0

원인

스프링에서는 자동으로 DB를 사용하겠다고 설정되어있지만, 프로젝트에 DB관련 정보가 정의되지 않았기 때문에 DB를 읽어올 수 없다는 에러가 뜬 것

해결

@SpringBootApplication(scanBasePackages = "com.cos.security1")
public class Security1Application {

	public static void main(String[] args) {
		SpringApplication.run(Security1Application.class, args);
	}
}

프로젝트명+애플리케이션 파일에 @SpringBootApplication(scanBasePackages = "com.cos.security01") 추가


실행

정상 실행이 되면 콘솔 중간에 password가 나오는데 이걸 복사해둔다.


주소창에 http://localhost:8080 입력해 index.html로 이동을 하려는데

이상하게 자꾸 내가 만든적도 없는 페이지가 나온다1!!
url이 http://localhost:8080/login 으로 이동

그 이유는!! 스프링부트 시큐리티 의존성을 설정하게되면 우리 홈페이지로 들어가는 모든 주소가 막히고 인증이 필요한 서버가 되기때문에!!!!(신기)

로그인을 하기 위해 Username에 user를 입력하고
아까 콘솔창에서 복사한 password 값을 아래에 입력한다.


그러면 제대로 내가 요청한 화면이 나오는 것을 볼 수 있다.

profile
제로부터시작하는코딩생활

0개의 댓글