Tiny Bunny
본문 바로가기
프로젝트/My

MYPROJECT(12) - 주요 코드 정리

by 내이름효주 2024. 5. 14.
  • 중복아이디 검증 
function callByAjax(loginId) {
	var form = document.form1;
	var action = "../member/doAction";
	var loginId = form.loginId.value;
	$.get(action, {
	loginId : loginId,
}, function(data) {
	$('.msg').text(data);
	ajaxCalled = true;
	console.log(ajaxCalled);
	updatePage();
	}, 'html');
}
@SuppressWarnings("unused")
@RequestMapping("/usr/member/doAction")
@ResponseBody
public String doAction(String loginId) {

	Member existsMember = memberService.getMemberByLoginId_1(loginId);

	String msg = "중복된 아이디가 존재합니다.";

	if (existsMember == null) {
		if (loginId == "") {
			msg = "아이디는 필수 정보입니다.";
			return msg;
		}
		msg = "사용가능한 아이디입니다.";
		return msg;
	}
	return msg;
}
  • 응원선수 등록
function register() {

					 	    var selectedPlayer = $("#favoritePlayer").val();
					 	    console.log(selectedPlayer);
					 	   
					 	   // 선택한 선수의 값으로 select 요소의 옵션을 선택
					 	    $("#favoritePlayer").val(selectedPlayer);
					 	   
					 	    $.ajax({
					 	        type: "POST",
					 	        url: "/usr/member/selectplayer", 
					 	        data: { player: selectedPlayer },
					 	        success: function(data) {

					 	        	console.log(data.pname);
					 	           	// 선수 정보 업데이트
					                $(".1").text(data.pname);
					                $(".2").text(data.pnumber);
					                $(".3").text(data.position);

					 	        	// 선수 요소의 배경 이미지 업데이트
					                $(".square-box2").css("background-image", "url('" + data.pimage + "')");
					 	        },
					 	        error: function(error) {
					 	            console.error("Error during registration:", error);
					 	        }
					 	    });
					 	    
					 	}
  • 회원 탈퇴
@PostMapping("/usr/member/dodel")
	@ResponseBody
	public String dodel(@RequestBody Member member, HttpServletRequest req) {
		Rq rq = (Rq) req.getAttribute("rq");
		int id = rq.getLoginedMemberId();
		String loginId = rq.getLoginedMember().getLoginId();

		Member findmember = memberService.getMemberByLoginId(loginId);

		if (!findmember.getLoginPw().equals(member.getLoginPw())) {
			return "비밀번호가 일치하지 않습니다";
		} else{
			memberService.delMember(id);
			rq.logout();
			return "탈퇴되었습니다.";
		}
	}
	
	// 로그인 시 탈퇴 계정 확인 로직 추가!!!
	if (member.isDelStatus()) {
		return Ut.jsHistoryBack("F-5", Ut.f("%s(은)는 탈퇴 계정입니다.", loginId));
	} // boolean값이 0이면 false, 1이면 true
  • 경기정보 모달
function setmodal(team1, team2, score, num, round, formatcurrentDayYear){
   	 const hometeam = document.getElementById("hometeam");
   	 const otherteam = document.getElementById("otherteam");
   	 const hometeamscore = document.getElementById("hometeamscore");
   	 const otherteamscore = document.getElementById("otherteamscore");
   	 const gameresult = document.getElementById("gameresult");
   	 const gamehighlight = document.getElementById("gamehighlight");
   	
   	 // 경기결과 링크
   	 let gameresultLink = "https://kovo.co.kr/redsparks/game/v-league/" + num + "?season=020&gPart=201&gender=%EC%97%AC%EC%9E%90%EB%B6%80&first=%EC%9D%BC%EC%A0%95+%EB%B0%8F+%EA%B2%B0%EA%B3%BC";
   	 
   	 if(round != "V-리그"){
   		 gameresultLink = "https://kovo.co.kr/redsparks/game/v-league/" + num + "?season=020&gPart=202&gender=%EC%97%AC%EC%9E%90%EB%B6%80&first=%EC%9D%BC%EC%A0%95+%EB%B0%8F+%EA%B2%B0%EA%B3%BC";
   	 }
   	
   	 // 하이라이트 영상 링크
   	 let gamehighlightLink = "https://kovo.co.kr/redsparks/media/media-video?third=%EA%B2%BD%EA%B8%B0%EB%B3%84&date=" + formatcurrentDayYear;
   	 hometeam.textContent = team1;
   	 otherteam.textContent = team2;
   	 gameresult.href = gameresultLink;
   	 gamehighlight.href = gamehighlightLink;
   	
   	 const modalscore = score.split("   :   ");
   	// 경기결과
   	 if(modalscore[0] == 3){
   		 hometeamscore.textContent = "승"
       	 hometeamscore.style.color = "red";
       	 otherteamscore.textContent = "패"
       	 otherteamscore.style.color = "black";
   		 const winIcon = document.createElement("i");
   	     winIcon.classList.add("fas", "fa-trophy");
   	     winIcon.style.color = "gold";
   	     winIcon.style.paddingLeft = "3px";
   	     hometeamscore.appendChild(winIcon);
   	     otherteamscore.classList.remove("shake-effect");
   	     hometeamscore.classList.add("shake-effect");  
   	 } else if(modalscore[1] == 3){
   		 hometeamscore.textContent = "패"
   		 hometeamscore.style.color = "black";
       	 otherteamscore.textContent = "승"
       	 otherteamscore.style.color = "red";
       	 const winIcon = document.createElement("i");
            winIcon.classList.add("fas", "fa-trophy");
            winIcon.style.color = "gold";
            winIcon.style.paddingLeft = "3px";
            otherteamscore.appendChild(winIcon);
            hometeamscore.classList.remove("shake-effect");
            otherteamscore.classList.add("shake-effect");
   	 }
   	
}
  • 예매정보
const gamelist = []; // game Date형 배열
const gamelist_gold = []; // game 7일전 Date형 배열
const gamelist_silver = []; // game 5일전 Date형 배열
const gamelist_normal = []; // game 3일전 Date형 배열

// 예매일정 배열
const modifiedgameMinusDates = start_modifiedGameDates.map(date => {
	const [yearStr, monthStr, dayStr] = date.split('-'); 
     
	const year = parseInt(yearStr, 10); //parseInt(string, radix(진수)) 문자열 분석하고 정수로 변환
    const month = parseInt(monthStr, 10);
    const day = parseInt(dayStr, 10);

	  for(let i = 0; i < start_modifiedGameDates.length; i++){
		  
          const [yearStr, monthStr, dayStr] = start_modifiedGameDates[i].split('-');
          
          const year = parseInt(yearStr, 10);
          const month = parseInt(monthStr, 10);
          const day = parseInt(dayStr, 10);

          const gamelistDate = new Date(year, month - 1, day);
          gamelist.push(gamelistDate);
          
          const game1MinusDate = new Date(gamelistDate.getFullYear(), gamelistDate.getMonth(), (gamelistDate.getDate()-1));  
          const formattedDate1 = game1MinusDate.toISOString().split('T')[0]; //날짜 개체를 ISO 문자열로 변환한 다음 "YYYY-MM-DD 형식의 날짜 부분을 추출
          gamelist_normal.push(formattedDate1);
          
          const game3MinusDate = new Date(gamelistDate.getFullYear(), gamelistDate.getMonth(), (gamelistDate.getDate()-3));  
          const formattedDate3 = game3MinusDate.toISOString().split('T')[0]; //날짜 개체를 ISO 문자열로 변환한 다음 "YYYY-MM-DD 형식의 날짜 부분을 추출
          gamelist_silver.push(formattedDate3);
          
          const game5MinusDate = new Date(gamelistDate.getFullYear(), gamelistDate.getMonth(), (gamelistDate.getDate()-5));      
          const formattedDate5 = game5MinusDate.toISOString().split('T')[0]; //날짜 개체를 ISO 문자열로 변환한 다음 "YYYY-MM-DD 형식의 날짜 부분을 추출
          gamelist_gold.push(formattedDate5);
	  }  
});


// 일정 넣기
const goldmember = {
    id: `event${i}`,
    title: start_modifiedGameDates[i].substring(5,start_modifiedGameDates[i].length) + ' 경기 예매',
    start: gamelist_gold[i],
    end: end_modifiedGameDates[i], // end의 날짜 전날까지 입력 일정이 들어가!
    allDay: true, // event가 하루 종일인지 여부
    backgroundColor: "#fbf3ee",
    textColor: 'black',
    extendedProps: {
        comment: '골드회원'
    }
};

events.push(goldmember);
  • 멤버쉽 랜덤코드 발급
if (lv == 1) {
			membercode = "G" + (int) (Math.random() * (99999 - 10000 + 1) + 10000);
			type = "골드";
		} else {
			membercode = "S" + (int) (Math.random() * (99999 - 10000 + 1) + 10000);
			type = "실버";
		}
  • 멤버쉽 결제 금액
function makePayment() {
    var clientKey = "my_clientKey";
    var tossPayments = TossPayments(clientKey);

    var amount = 0;
    var level = document.querySelector('input[name="level"]:checked').value;

    var orderName = null;
    var customerName = document.getElementById('mname').value;
    
    if (level === "1") { // Gold membership
        amount = 100000;
        orderName = "Gold membership";
    } else if (level === "2") { // Silver membership
        amount = 70000;
        orderName = "Silver membership";
    }
    
    tossPayments.requestPayment("카드", {
        amount: amount,
        orderId: "",
        orderName: orderName,
        customerName: customerName
    }).then(function () {
    	 document.getElementById("membershipForm").submit();
    }).catch(function (error) {
        // Handle payment error
        console.error("Payment error:", error);
        // Optionally, display an error message to the user
        alert("결제가 실패했습니다. 잠시 후 다시 시도해주세요.");
    });
}
  • 멤버쉽 가입 후 문자 전송
DefaultMessageService messageService =  NurigoApp.INSTANCE.initialize("", "", "https://api.coolsms.co.kr");
		// Message 패키지가 중복될 경우 net.nurigo.sdk.message.model.Message로 치환하여 주세요
		Message message = new Message();
		message.setFrom("발신자번호");
		message.setTo(cellphoneNum);
		message.setText(mname + "님, " + type + "멤버쉽 가입이 완료되었습니다.\n" + "멤버쉽 코드: [" + type + "]" + membercode);
		
		try {
		  // send 메소드로 ArrayList<Message> 객체를 넣어도 동작합니다!
		  messageService.send(message);
		} catch (NurigoMessageNotReceivedException exception) {
		  // 발송에 실패한 메시지 목록을 확인할 수 있습니다!
		  System.out.println(exception.getFailedMessageList());
		  System.out.println(exception.getMessage());
		} catch (Exception exception) {
		  System.out.println(exception.getMessage());
		}
  • 지도
<script type="text/javascript" src="https://dapi.kakao.com/v2/maps/sdk.js?appkey=19cf78438548356f5de2f18b79f43362"></script>
		<script>
       var lat = ${team.latitude};
       var lon = ${team.longitude};
       
       // 카카오지도
       var mapContainer = document.getElementById('map');
       var mapOption = {
           center: new kakao.maps.LatLng(lat, lon),
           level: 3
       };
       var map = new kakao.maps.Map(mapContainer, mapOption);
      
       var content = '<div class ="label"><span class="left"></span><span class="center">대전충무체육관</span><span class="right"></span></div>';
    	 // 커스텀 오버레이가 표시될 위치입니다
       var position = new kakao.maps.LatLng(lat, lon); 
       // 커스텀 오버레이를 생성합니다
       var customOverlay = new kakao.maps.CustomOverlay({
           position: position,
           content: content  
       });
       // 커스텀 오버레이를 지도에 표시합니다
       customOverlay.setMap(map);
  • 페이지네이션
		int articlesCount = 0;

		int itemsInAPage = 15; // 페이지당 보여줄 게시글 수
		
		if(boardId == 4) { // 페이지에 보여줄 게시글이랑 게시글 수
			articles = articleService.getForPrintMyArticles(id, itemsInAPage, page, searchKeywordTypeCode, searchKeyword);
			// -> int limitFrom = (page - 1) * itemsInAPage;
			// -> int limitTake = itemsInAPage;
			articlesCount = articleService.getMyArticlesCount(id, searchKeywordTypeCode, searchKeyword);
		
		} else {
			articles = articleService.getForPrintArticles(boardId, itemsInAPage, page, searchKeywordTypeCode, searchKeyword);
			articlesCount = articleService.getArticlesCount(boardId, searchKeywordTypeCode, searchKeyword);
		}
		
		int pagesCount = (int) Math.ceil(articlesCount / (double) itemsInAPage);
  • 질의응답 게시판 
document.addEventListener('DOMContentLoaded', function() {
    var links = document.querySelectorAll('a[href^="detail?id="]');
    links.forEach(function(link) {
        link.addEventListener('click', function(event) {
        	var articleId = this.getAttribute('href').match(/\d+$/)[0];
            var boardId = this.getAttribute('data-boardId');
            
            var inputPassword = document.getElementById('loginPw');
            //inputPassword.dataset.articleId = articleId;
            
            if (boardId === '3') {
                event.preventDefault(); 
                openModal(articleId); 
            }
        });
    });
});
function togglePasswordVisibility() {
        var passwordField = document.getElementById("loginPw");
        var toggleIcon = document.getElementById("toggleIcon");

        if (passwordField.type === "password") {
            passwordField.type = "text";
            toggleIcon.src = "https://github.com/ohyo555/my_project_03/assets/153146836/025eaaf9-aee2-483f-925a-bc884a7fe688";
        } else {
            passwordField.type = "password";
            toggleIcon.src = "https://github.com/ohyo555/my_project_03/assets/153146836/665f7e05-f73f-4491-a7df-c1f9f8ff74c4";
        }
    }
  • 파일 첨부
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

	for (String fileInputName : fileMap.keySet()) {
		MultipartFile multipartFile = fileMap.get(fileInputName);

		if (multipartFile.isEmpty() == false) {
			genFileService.save(multipartFile, id);
		}
	}
	
// 새 파일이 저장될 폴더(io파일) 객체 생성
String targetDirPath = genFileDirPath + "/" + relTypeCode + "/" + fileDir;
java.io.File targetDir = new java.io.File(targetDirPath);

// 새 파일이 저장될 폴더가 존재하지 않는다면 생성
if (targetDir.exists() == false) {
	targetDir.mkdirs();
}

String targetFileName = newGenFileId + "." + fileExt;
String targetFilePath = targetDirPath + "/" + targetFileName;

// 파일 생성(업로드된 파일을 지정된 경로롤 옮김)
try {
	multipartFile.transferTo(new File(targetFilePath));
} catch (IllegalStateException | IOException e) {
	return new ResultData("F-3", "파일저장에 실패하였습니다.");
}

return new ResultData("S-1", "파일이 생성되었습니다.", "id", newGenFileId, "fileRealPath", targetFilePath, "fileName",
		targetFileName, "fileInputName", fileInputName);
  • 게시글 조회
//조회시 local에 article 번호로 조회 여부 저장

function ArticleDetail__doIncreaseHitCount() {
		const localStorageKey = 'article__' + params.id + '__alreadyView';
	 
		if (localStorage.getItem(localStorageKey)) {
			return;
		}
		
		localStorage.setItem(localStorageKey, true);

		$.get('../article/doIncreaseHitCountRd', {
			id : params.id,
			ajaxMode : 'Y'
		}, function(data) {
			$('.article-detail__hit-count').empty().html(data.data1);
		}, 'json');
	}

	$(function() {
		setTimeout(ArticleDetail__doIncreaseHitCount, 2000); // 2초 후 실행
	});
  • 댓글 좋아요 
// 게시글, 댓글 code 구분하여 좋아요 실행

function doGoodReaction(articleId) {
		
		$.ajax({
			url: '/usr/reactionPoint/doGoodReaction',
			type: 'POST',
			data: {relTypeCode: 'article', relId: articleId },
			dataType: 'json',
			success: function(data){
				console.log(data);
				console.log('data.data1Name : ' + data.data1Name);
				console.log('data.data1 : ' + data.data1);
				console.log('data.data2Name : ' + data.data2Name);
				console.log('data.data2 : ' + data.data2);
				if(data.resultCode.startsWith('S-')){
					var likeButton = $('#likeButton');
					var likeCount = $('#likeCount');
					/* var DislikeButton = $('#DislikeButton');
					var DislikeCount = $('#DislikeCount');
					 */
					if(data.resultCode == 'S-1'){
						if(data.msg == '좋아요!'){
							likeButton.html('♥');
							likeCount.text(data.data1);
						} else {
							likeButton.html('♡');
							likeCount.text(data.data1);
						}
					}
					
				}else {
					alert(data.msg);
				}
		
			},
			error: function(jqXHR,textStatus,errorThrown) {
				alert('좋아요 오류 발생 : ' + textStatus);

			}
			
		});
	}
  • 뉴스 크롤링
System.setProperty("webdriver.chrome.driver", "C:\\work\\sts-4.21.0.RELEASE-workspace\\myproject\\chromedriver.exe");
		
		ChromeOptions options = new ChromeOptions();
		options.addArguments("--headless"); // 브라우저를 표시하지 않고 실행할 경우
		
		List<News> newsList = new ArrayList<>();
		// 웹 드라이버 초기화
		WebDriver driver = new ChromeDriver(options);
		try {
			String url = "https://search.naver.com/search.naver?where=news&ie=utf8&sm=nws_hty&query=%EC%A0%95%EA%B4%80%EC%9E%A5+%EB%A0%88%EB%93%9C%EC%8A%A4%ED%8C%8C%ED%81%AC%EC%8A%A4";
			
			driver.get(url);
			
			 WebElement button = driver.findElement(By.cssSelector("#snb > div.mod_group_option_filter._search_option_simple_wrap > div > div.option_area.type_sort > a:nth-child(2)"));
			 button.click();
			List<WebElement> Elements = driver.findElements(By.cssSelector("#main_pack > section > div.api_subject_bx > div.group_news > ul > li"));
			
			for (WebElement Element : Elements) {
	            String company_img = Element.findElement(By.cssSelector(".bx > .news_wrap.api_ani_send > div > div.news_info > div.info_group > a.info.press > span > img")).getAttribute("src");
	            String company_name = Element.findElement(By.cssSelector(".bx > .news_wrap.api_ani_send > div > div.news_info > div.info_group > a.info.press")).getText();
	            String date = Element.findElement(By.cssSelector(".bx > .news_wrap.api_ani_send > div > div.news_info > div.info_group > span")).getText();
	            String title = Element.findElement(By.cssSelector(".bx > .news_wrap.api_ani_send > div > div.news_contents > a.news_tit")).getText();
	            String content = Element.findElement(By.cssSelector(".bx > .news_wrap.api_ani_send > div > div.news_contents > div")).getText();
	            String title_img = Element.findElement(By.cssSelector(".bx > .news_wrap.api_ani_send > div > div.news_contents > a.dsc_thumb > img")).getAttribute("src");
	            String news_url = Element.findElement(By.cssSelector(".bx > .news_wrap.api_ani_send > div > div.news_contents > a.news_tit")).getAttribute("href");
	            News news = new News(company_img, company_name, date, title, content, title_img, news_url);
	            newsList.add(news);
	        }
		}