jnk1m
Foliage IT
jnk1m
전체 방문자
오늘
어제
  • 분류 전체보기 (209)
    • Today I Learned (34)
    • Java (47)
    • Database (15)
    • [NHN Academy] (27)
    • Spring (47)
    • HTML + CSS + JavaScript (11)
    • JSP (3)
    • Node.js (10)
    • React Native (2)
    • 기타 (8)
    • 스크랩 (5)

인기 글

최근 글

티스토리

hELLO · Designed By 정상우.
글쓰기 / 관리자
jnk1m

Foliage IT

Spring

[Spring] Day04 (Code)

2022. 3. 22. 00:47

1. TestController3

package com.test.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.test.model.TestDTO;
import com.test.model.TestTv;

@Controller
@RequestMapping("day04/")
public class TestController3 {

	@GetMapping("test01")
	public void test01(HttpServletRequest request,HttpSession session, Model model) {
		model.addAttribute("name", "고니");
		//Model:해쉬맵 구조로 key, value 형태. addAttribute(String key, Object value)
		//뒤는 오브젝트 클래스라 뭐든 ok 앞은 스트링
		model.addAttribute("age", 20);
		//데이터는 뷰 페이지, 즉 테스트01 페이지로 간다. 
		
		//request.setAttribute("name", "정마담"); 같은 이름이라 안나옴
		//request.setAttribute("age", 30); 리퀘스트는 요청 당 하나라서 요청할때마다 값이 달라짐
		
		session.setAttribute("name", "아귀");
		session.setAttribute("age", 40); //session이라는 객체는 브라우저당 하나라서 브라우저 하나가지고 계속 사용
		
		model.addAttribute("arr", new int [] {1,2,3,4,5});
		System.out.println("test01 호출");
		
	}
	//라이브러리 배치
	@GetMapping("test02")
	public void test02(Model model) {
		model.addAttribute("dto",new TestDTO());
		model.addAttribute("arr", new int [] {1,2,3,4,5});
		System.out.println("test02 호출");
	}
	
	//fmt
	@GetMapping("test03")
	public void test03(Model model) {
		System.out.println("test03 호출");
		model.addAttribute("day", new Date()); //day이름으로 객체 생성한거 보내주기
		
		model.addAttribute("arr", new int[] {10,20,30,40,50}); //배열
		
		List list = new ArrayList();
		for(int i = 0; i<5;i++) {list.add(i+1);} //list.get(인덱스번호)
		model.addAttribute("list", list); //ArrayList 추가
		
		TestDTO dto = new TestDTO();
		dto.setId("피카츄");
		dto.setPw("34qaewr");
		model.addAttribute("dto", dto); //TestDTO 객체 
	}
	
	//http://localhost:8080/day04/test04?id=java&pw=1111
	@GetMapping("test04")
	public void test04(TestDTO dto, 
			@ModelAttribute("id") String id, //뒤에 String id, pw는 자바빈즈 규악에 맞지 않기 때문에 자동으로 넘어가지 않음. 모델 통해서 어트리뷰트를 하던가 어노테이션 붙이기.
			@ModelAttribute("pw") String pw, Model model) { //그대~로 넘기기
		System.out.println("test04 호출");
		model.addAttribute("newid", id+"hello"); //데이터를 갱신하고 수정해서 넘기려면 이 방법 사용
		model.addAttribute("dto", dto); //가공해서 보내기
	}
	
	//메서드 레벨에 어노테이션 부착: test01~test04 모든 view에서 tv 객체 사용 가능
	//이 클래스에 있는 요청 메서드 호출 전에 먼저 아래 메서드가 호출되면서
	//뷰에 tv 객체 전달. -> 이 클래스에 모든 jsp에서 필요한 객체가 있으면 아래와 같이 작성해주기.
	@ModelAttribute("tv")
	public TestTv getTv(String color) { //http://localhost:8080/day04/test03?color=yellow
		System.out.println("getTv 호출!"); //이게 먼저 호출되서 파라미터 받고 출력한 다음에 호출한 test03이나 04로 넘어감
		TestTv tv = new TestTv();
		tv.setPower(true);
		tv.setCh(10);
		tv.setVol(5);
		tv.setColor(color);
		return tv;
	}
	
	/*
	@GetMapping("test05")
	public String test05(Model model) { //url 경로가 jsp 파일 경로와 동일
		model.addAttribute("hello", "jajaja");
		return "day04/test05"; //jsp 파일 경로 리턴
	}
	요즘은 잘 안쓰는 방식
	@GetMapping("test05") //위처럼 제각각 하는게 아니라 한꺼번에 모델앤뷰.
	public ModelAndView test05() {
		//객체 생성
		ModelAndView mv = new ModelAndView();
		//뷰에 전달할 데이터 추가
		mv.addObject("hello","hahaha"); //model.addAttribute와 동일
		//뷰 경로 저장
		mv.setViewName("day04/test05");
		return mv;
	}
	
	@GetMapping("test05")
	public String test05() {
		System.out.println("test05 호출!!!!!");
		//스프링에서 기본적으로 forward 방식으로 이동.
		return "redirect: /day04/testNewpage";
		
	}
	@GetMapping("testNewpage")
	public void testNewpage() {
		System.out.println("testNewpage 호출!!!!!");
	}*/
	
	@PostMapping("test05")
	public void test05() {
		System.out.println("test05 호출!!!!!");
	}
	
}

 

2. test01

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h2>test01 page</h2>
	
	<h4>${name} </h4>
	<h4>${age} </h4>

	<h4>${requestScope.name} </h4>
	<h4>${requestScope.age} </h4>
	<!-- model로 넣은건 request가 가지고 있다고 생각하면 됨. -->
	
	<h4>${sessionScope.name} </h4>
	<h4>${sessionScope.age} </h4>
	
	<h4>${param.abc}</h4>
	<%-- http://localhost:8080/day04/test01?abc=123 ${param.파라미터명} 요청 시 넘어온 파라미터 값--%>
	
	<h4>${null}</h4>
	<%--값이 없어서 출력이 나오지 않음. --%>
	
	<h4>${arr[0] }</h4>
	
</body>
</html>

 

3. test02

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>test02</h2>


<%--1. 변수 생성 
var: 변수명. 표현식, EL, 정적 텍스트 사용해 값 지정 가능
property: 프로퍼티 이름 지정. 자바 빈의 경우 변수명 (->set메서드 호출)
target: 값 설정할 대상 객체. EL을 사용하여 지정 
 --%>
<c:set var="name">피카츄</c:set> <%-- name이라는 변수에 피카츄를 넣음--%>
<c:set var="id" value="java"/> <%--홑태그로 만들때는 밸류를 써서 넣으면 된다 --%>
<h4>name: ${name}</h4>
<h4>id: ${id}</h4>

<%--dto 넘어온 객체의 변수에 값 넣어주기. 중요: 타겟은 el로 지정 --%>
<c:set target="${dto}" property="id" value="test"/>
<c:set target="${dto}" property="pw" value="35q4978e"/>
<h4>dto.id:${dto.id}</h4>
<h4>dto.pw:${dto.pw}</h4>

<%--변수 삭제: remove --%>
<c:remove var="name"/>
<c:remove var="id"/>
<h4>name: ${name}</h4>
<h4>id: ${id}</h4>

<%--c:if 조건문. 자바에서 if문만 쓰는 형태 
<c:if test="${조건식EL}">
//조건식이 참일 경우 실행된 코드들...(화면에 보여줄 태그들 작성) 
<c:set var="num" value="100"/>
<c:if test="${num>100}">
	<h4>num: ${num}은 100보다 크다</h4>
</c:if>
<c:if test="${num==100}">
	<h4>num: ${num}은 100이다</h4>
</c:if>
<c:if test="${num<100}">
	<h4>num: ${num}은 100보다 작다</h4>
</c:if>


<%--c:choose, c:when, c:otherwise 
<c:choose>
	<c:when test = "${num>100}">
	<h4>num: ${num}은 100보다 크다</h4>
	</c:when>
	<c:when test = "${num==100}">
	<h4>num: ${num}은 100이다</h4>
	</c:when>
	<c:otherwise>
	<h4>num: ${num}은 100보다 작다</h4>
	</c:otherwise>
</c:choose>

<%--c:forEach --%>
<c:forEach var="i" items="${arr}" varStatus="status"> <%--배열이 가진 요소를 반복하면서 i에 담아준다 --%>
	<h3>i: ${i}, index: ${status.index}, count: ${status.count}</h3>
</c:forEach>

<c:forEach var="a" begin="1" end="10" step="1"> <%--a의 값이 1씩 늘어가서 10까지 (10포함) --%>
	<h4>${a}</h4>
</c:forEach>

<%--구구단 2~9단까지 출력 
<c:forEach var="a" begin="2" end="9" step="1">
	<h4>***${a}단***</h4>
	<c:forEach var="b" begin="1" end="9" step="1">
	<h4>${a} * ${b} = ${a*b}</h4>
	</c:forEach>
</c:forEach>--%>

<%--c:forTokens: 반복문, 구분자를 이용하여 토큰 방식으로 잘라서 반복 구현. 에러남. 왜지
<c:forTokens var="a"items="a,b,c,d,e" delims=",">
	<h3>${a}</h3>
</c:forTokens> --%>

<%--c:import : include와 비슷 
<c:import url="/day04/test01"/>--%>

<%--c:redirect 단순 이동(새로 요청) 해당 url의 요청이 controller로 다시 들어감 (GET)
<c:redirect url="/day04/test01"/>--%>

<%--c:url : url 주소 만들 때 /day04/test01?id=java&pw=sdf34
<c:url var="u" value="/day04/test01">
	<c:param name="id" value="java"/> 값을 가지고 감
	<c:param name="pw" value="sdf34"/>
</c:url>
<c:redirect url="${u}"/>--%>

<%--10. c:out 출력태그 --%>
<c:set var="num2" value="50"/>
num2 el: ${num2}
num2 c.out: <c:out value="${num2}"/>

<input type="text" name="test" value="${num2}"/>
<input type="text" name="test" value="<c:out value='${num2}'/>"/>


</body>
</html>

 

4. test03

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h2>test03 page</h2>

<h3>tv: ${tv}</h3>
<h3>tv vol: ${tv.vol}</h3>
<h3>tv.color: ${tv.color}</h3>


<%--1. 날짜와 관련 --%>
<%-- <%request.setCharacterEncoding("UTF-8")%>과 동일 --%>
<fmt:requestEncoding value="UTF-8"/>

<fmt:formatDate value="${day}"/><br/> <%--testcontroller에서 준 day 객체 --%>
<fmt:formatDate value="${day}" type="date"/><br/> 
<fmt:formatDate value="${day}" type="time"/><br/> 
<fmt:formatDate value="${day}" type="both"/><br/> <br/> 

<%--출력 스타일을 미리 지정해놓은 옵션 
<fmt:formatDate value="${day}" type="both" dateStyle="short"/><br/>
<fmt:formatDate value="${day}" type="both" dateStyle="medium"/><br/>
<fmt:formatDate value="${day}" type="both" dateStyle="long"/><br/>
<fmt:formatDate value="${day}" type="both" dateStyle="full"/><br/><br/> 

<fmt:formatDate value="${day}" type="both" dateStyle="short" timeStyle="short"/><br/>
<fmt:formatDate value="${day}" type="both" dateStyle="medium"timeStyle="medium"/><br/>
<fmt:formatDate value="${day}" type="both" dateStyle="long"timeStyle="long"/><br/>
<fmt:formatDate value="${day}" type="both" dateStyle="full"timeStyle="full"/><br/><br/> 
--%>

<%--위처럼 만들어진 포맷 말고 내가 정한 포맷 지정 --%>
<fmt:formatDate value="${day}" pattern="yyyy년 MM월 dd일"/><br/> 

<%--2. 숫자와 관련된 --%>
<%--groupingUsed 자릿수 구별. 디폴트가 트루라서 안쓰면 자동으로 지정  --%>
<fmt:formatNumber value="1003450000" groupingUsed="true"/><br/>
<fmt:formatNumber value="1003450000" groupingUsed="false"/><br/>

<%--통화: type은 number가 default값 --%>
<fmt:formatNumber value="1000000" type="number"/><br/> 
<%--안됨..왜..?
<fmt:formatNumber value="1000000" type="currency"currencySymbol="$"/><br/> 
 --%>
<%--퍼센트 --%>
<fmt:formatNumber value="0.3" type="percent"/><br/>

<%--소숫점 자릿수 표현 지정: 반올림 --%>
<fmt:formatNumber value="1200.158" pattern=".00"/><br/>

<%--문자열을 숫자로 변환해주는 기능. var를 붙이면 변수 선언처럼 사용 가능  --%>
<fmt:parseNumber var="result" value="1000.123" integerOnly="true"/>
${result}<br/>

<%--타임존 --%>
<fmt:timeZone value="GMT">
	<fmt:formatDate value="${day}" type="both"/><br/>
</fmt:timeZone>

<%--EL --%>
<h4>${arr}</h4>
<h4>${arr[0]}</h4>

<h3>${list}</h3>
<h3>${list[0]}</h3> <%--ArrayList 배열처럼 사용가능 --%>
<h3>${list.get(0)}</h3> <%--메서드 호출해서 사용가능 --%>

${dto}<br/>
${dto.id}<br/> <%--get 메서드 호출해서 출력하는 격: 자바빈 형태 --%>
${dto.pw}<br/>




</body>
</html>

 

5. test04

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h2>test04 page</h2>
	<%--JavaBeans 규약에 맞는 클래스 타입의 매개변수는 Controller에서 자동으로 
	view까지 데이터를 전달해줌.  이때, 특별히 Model로 이름을 붙여주지 않았기 때문에
	클래스명 첫글자를 소문자로 바꿔서 자동 이름 붙여서 넘겨줌
	jsp에서 꺼낼 때 클래스 명 첫글자를 소문자로 변경하여 값 추출 가능--%>
	<h4>${testDTO.id}</h4>
	<h4>${testDTO.pw}</h4>
	<h4>${id}</h4>
	<h4>${pw}</h4>
	
	
	<h4>tv: ${tv}</h4>
	<h4>tv channel: ${tv.ch}</h4>
	<h4>tv.color: ${tv.color}</h4>
	
</body>
</html>

 

6. test05

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>test 05 page</h2>
<h4>${hello}</h4>
</body>
</html>

 

7. TestTv

package com.test.model;

import lombok.Data;

@Data
public class TestTv {
	private boolean power;
	private int vol,ch;
	private String color;
}
    'Spring' 카테고리의 다른 글
    • [Spring] Day05 (Code)
    • [Spring] Day05 (Note): MyBatis, DB 연동, 패키지 정리
    • [Spring] Day04 (Note): EL, JSTL, Model
    • [Spring] Day03 (Code)

    티스토리툴바