Spring 08 (23.04.17)

Jane·2023년 4월 17일
0

IT 수업 정리

목록 보기
106/124

1. Restful 게시판 만들기 (이어서)

1-1. 제목을 누르면 내용 보기

  • resource 자리에 rest_list_view.html 만들기

  • javascript에서 원하는 컬럼의 객체 가져오기

    • let searchParams = new URLSearchParams(window.location.search);
      console.log(searchParams.has('bid'));
    • let bid = searchParams.get('bid')
      console.log(bid);

rest_list_view.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>RestBoard</title>
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- http://localhost:8282/rest_content_view.html?bid=747 -->
<script type="text/javascript">
	$(document).ready(function() {
		let searchParams = new URLSearchParams(window.location.search);
		console.log(searchParams.has('bid'));
		let bid = searchParams.get('bid')
		console.log(bid);

		$.ajax({
			type : "GET",
			url : "/rboard/" + bid,
			success : function(board) {

				console.log(board);
				$("#input_hidden").val(board.bid);
				$("#td_bid").text(board.bid);
				$("#td_hit").text(board.bhit);

				$("#input_bname").val(board.bname);
				$("#input_btitle").val(board.btitle);
				$("#textarea_bcontent").text(board.bcontent);

			},
			error : function(e) {
				console.log(e);
			}
		});

	})
</script>
</head>
<body>

	<form id="updateForm" action="modify" method="post">
		<table id="list-table" border="1">
			<input id="input_hidden" type="hidden" name="bid" value="">
			<tr>
				<td>번호</td>
				<td id="td_bid"></td>
			</tr>
			<tr>
				<td>히트</td>
				<td id="td_hit"></td>
			</tr>
			<tr>
				<td>이름</td>
				<td><input id="input_bname" type="text" name="bname" value=""></td>
			</tr>
			<tr>
				<td>제목</td>
				<td><input id="input_btitle" type="text" name="btitle" value=""></td>
			</tr>
			<tr>
				<td>내용</td>
				<td><textarea id="textarea_bcontent" rows="10" name="bcontent"></textarea></td>
			</tr>
			<tr>
				<td colspan="2"><input id="input_modify" type="submit"
					value="수정"> &nbsp;&nbsp; <a href="list">목록보기</a>
					&nbsp;&nbsp; <a id="a-delete"
					href="${pageContext.request.contextPath}/rest/delete?bId=${content_view.bId}">삭제</a>
					&nbsp;&nbsp; <a href="reply_view?bId=${content_view.bId}">답변</a></td>

			</tr>
		</table>
	</form>

</body>
</html>

RestBoardController.java (함수 추가)

	@GetMapping("/{bid}")
	public BoardVO rboard_content_view(BoardVO board) {
		log.info("view()...");

		return boardService.get(board.getBid());
	}

1-2. 수정하기 버튼 (modify)

  • 지금 form은 submit을 누르면 modify로 받아낸다.
  • action으로 받는 것이 아니라, ajax로 처리해야 한다.

rest_content_view.html (script 추가)

<!-- modify -->
<script type="text/javascript">
	$(document).ready(function() {
		$("#updateForm").submit(function(event) {
			event.preventDefault();
			console.log("ajax 호출전");

			var bname = $("#input_bname").val();
			var btitle = $("#input_btitle").val();
			var bcontent = $("#textarea_bcontent").text();
			var bid = $("#input_hidden").val();

			var form = {
				bid : bid,
				bname : bname,
				btitle : btitle,
				bcontent : bcontent
			};

			$.ajax({
				type : "PUT",
				url : "/rboard/" + bid,
				cashe : false,
				contentType : 'application/json; charset=utf-8',
				data : JSON.stringify(form),
				success : function(result) {
					console.log(result);
					$(location).attr('href', '/rest_list.html')
 					// location.href='/rest_list.html'
				},
				error : function(e) {
					console.log(e);
				}
			});

		});
	});
</script>

RestBoardController.java (함수 추가)

	@PutMapping("/{bid}")
	public int rboard_update(@RequestBody BoardVO board) {
		log.info("update()...");

		return boardService.modify(board);
	}
  • RequestBody : json이 java 객체로 변신

1-3. DeleteMapping 수정

RestBoardController.java

	@DeleteMapping("/{bid}")
	public ResponseEntity<String> rest_delete(BoardVO boardVO, Model model) {

		ResponseEntity<String> entity = null;
		log.info("rest_delete..");

		try {
			int rn = boardService.remove(boardVO);
			// 삭제가 성공하면 성공 상태메시지 저장
			log.info("delete 넘어온 숫자:::::" + rn);

			entity = new ResponseEntity<>(String.valueOf(rn), HttpStatus.OK);
		} catch (Exception e) {
			e.printStackTrace();
			// 댓글 삭제가 실패하면 실패 상태메시지 저장
			entity = new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
		}
		// 삭제 처리 HTTP 상태 메시지 리턴
		return entity;
	}

2. 정적 리소스

  • 동적 리소스 : 컴파일해서 바꿔야 하는 것 (jsp)
  • 정적 리소스 (static) : 컴파일 대상이 아닌 것 (html, css, js, img....)

  • 기존에 있는 html 소스코드들도 static에 넣어서 사용할 수 있다.
  • 작업한 jsp에서 static에 있는 image를 불러올 수 있다.

3. Spring Security

3-1. 기초 설정

  • pom.xml에 라이브러리 작성 (처음 깃허브에 올릴 때에는 스프링 시큐리티 내용이 없는 pom.xml을 올릴 예정)

  • Maven > Update Project로 라이브러리 업데이트

(OK하면 체크를 해준다.)

  • .gitignore 만들기 (class 파일처럼 로컬에서만 필요한 파일들은 거른다.)
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/

### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache

### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr

### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/

### VS Code ###
.vscode/

# Created by https://www.gitignore.io/api/java,macos,windows,eclipse
# Edit at https://www.gitignore.io/?templates=java,macos,windows,eclipse

### Eclipse ###
.metadata
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.settings/
.loadpath
.recommenders

# External tool builders
.externalToolBuilders/

# Locally stored "Eclipse launch configurations"
*.launch

# PyDev specific (Python IDE for Eclipse)
*.pydevproject

# CDT-specific (C/C++ Development Tooling)
.cproject

# CDT- autotools
.autotools

# Java annotation processor (APT)
.factorypath

# PDT-specific (PHP Development Tools)
.buildpath

# sbteclipse plugin
.target

# Tern plugin
.tern-project

# TeXlipse plugin
.texlipse

# STS (Spring Tool Suite)
.springBeans

# Code Recommenders
.recommenders/

# Annotation Processing
.apt_generated/

# Scala IDE specific (Scala & Java development for Eclipse)
.cache-main
.scala_dependencies
.worksheet

### Eclipse Patch ###
# Eclipse Core
.project

# JDT-specific (Eclipse Java Development Tools)
.classpath

# Annotation Processing
.apt_generated

.sts4-cache/

### Java ###
# Compiled class file
*.class

# Log file
*.log

# BlueJ files
*.ctxt

# Mobile Tools for Java (J2ME)
.mtj.tmp/

# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

### macOS ###
# General
.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon

# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db

# Dump file
*.stackdump

# Folder config file
[Dd]esktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp

# Windows shortcuts
*.lnk

# End of https://www.gitignore.io/api/java,macos,windows,eclipse

.metadata/ 
Servers/ 
*.class 
*.classpath 
/target/ 
/bin/
/.settings/
/.apt_generated_tests/
#server port number
server.port = 8282

#datasource (oracle)
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521/xe
#spring.datasource.driver-class-name=net.sf.log4jdbc.sql.jdbcapi.DriverSpy
#spring.datasource.url=jdbc:log4jdbc:oracle:thin:@localhost:1521/xe
spring.datasource.username=scott
spring.datasource.password=tiger

spring.devtools.livereload.enabled=true 

#jsp  
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

HomeController.java

package edu.global.ex.controller;

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

@Controller
public class HomeController {

	@GetMapping("/")
	public String home() {
		return "home";
	}

}

3-2. GitHub에 올리기

  • home.jsp 만들고 (지정된 위치에), localhost:8282/ 실행해서 확인

  • Team > Share Project

  • Team > Commit 에서 내용 모두 추가하고 Commit

  • 소스트리 열고 경로 설정

  • 소스토리 > 브랜치 > 브랜치 생성

  • 생성한 브랜치에서 Security 관련 라이브러리 추가
		<!-- Spring Security 라이브러리 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- 스프링 부트에서는 jsp 태그를 지원 하지 않기 때문에 직접 입력 해야야함 -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-taglibs</artifactId>
		</dependency>

(이 내용도 커밋)

3-3. 쿠키와 세션으로 관리

  • localhost:8282/ 접속하고 로그인하기 (ID : user, PW : 로그된 내용)

  • 로그인하면 F12 - 애플리케이션 - 쿠키에 세션이 생긴다.
  • 기록을 지우면 다시 로그인 해야한다.

3-4. Security Configuration

SecurityConfig.java

package edu.global.ex.config;

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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable(); // CSRF 설정 해제 (초기 개발시 꺼놓고 작업)
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {

		auth.inMemoryAuthentication().withUser("user").password("{noop}user").roles("USER").and().withUser("admin")
				.password("{noop}admin").roles("ADMIN");

	}

}
profile
velog, GitHub, Notion 등에 작업물을 정리하고 있습니다.

0개의 댓글