스프링02_데이터 받는 여러 방법, 필터, 데베

charl hi·2022년 1월 14일
0

Spring

목록 보기
3/25

✨✨평가받고 알게 된 것

setter명이 잘못되면 데배에 저장 ㄴㄴ

<beans:property>

  • ✨✨getter, setter 활용

<beans:constructor-arg>

  • ✨✨생성자 활용


getter명이 잘못되면 #{변수명}에 데이터를 넣어주지 못한다.

  • mapper안의 ID = #{id}

???맞나




데이터 받기

방법 1) req.getParameter()

package com.kh.app05.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/member")
public class MemberController {

	//get일 때만 처리하게끔 아래처럼
//	@RequestMapping(value = "/join", method = RequestMethod.GET)
	@GetMapping("/join")
	public String join() {
		System.out.println("join get 요청 처리함");
		// get+post해서, 구분을 안해놔서 두번 나옴
		// 페이지 로딩할때, submit할 때
		return "member/join";
	}
	
	//post일 때만 처리하게끔 아래처럼
//	@RequestMapping(value = "/join", method = RequestMethod.POST)
	@PostMapping("/join")
	public String join2(HttpServletRequest req) {
		System.out.println("join post 요청 처리함");
		
		String id = req.getParameter("id");
		String pwd = req.getParameter("pwd");
		String nick = req.getParameter("nick");
		
		System.out.println("id : "+id);
		System.out.println("pwd : "+pwd);
		System.out.println("nick : "+nick);
		
//		회원가입 성공하면 아래로
		return "member/join_result";
	}
}
  • http://127.0.0.1:8888/app05/member/join



방법 2) 메소드 자체의 파라미터

	@PostMapping("/join")
	public String join2(String id, String pwd, String nick) {
		System.out.println("join post 요청 처리함");
		
		//방법 2 : 메소드 자체의 파라미터
		
		System.out.println("id : "+id);
		System.out.println("pwd : "+pwd);
		System.out.println("nick : "+nick);
		
//		회원가입 성공하면 아래로
		return "member/join_result";
	}


방법 2-1) @RequestParam

	@PostMapping("/join")
	public String join2(@RequestParam String id, @RequestParam String pwd, @RequestParam String nick) {
		System.out.println("join post 요청 처리함");
		
		//방법 2 : 메소드 자체의 파라미터
		
		System.out.println("id : "+id);
		System.out.println("pwd : "+pwd);
		System.out.println("nick : "+nick);
		
//		회원가입 성공하면 아래로
		return "member/join_result";
	}
}

@RequestParam 의 옵션

  • required = true/false : 없는 name을 가져오면 에러남, 디폴트 / 없는 name을 가져와도 에러 안나게

  • defaultValue = "~~~" : 입력안하면 디폴트값으로 지정

  • @RequestParam(name = "id") String memberId / @RequestParam(value = "id") String memberId
    -> jsp에서 name이 id인 값을 가져오는데, 그게 memberId
    -> 아래에 출력할 때는 memberId로 바꿔서



방법 3) @ModelAttribute

	@PostMapping("/join")
		public String join2(@ModelAttribute MemberVo m) {
		System.out.println("join post 요청 처리함");
		
		//방법 3 : @ModelAttribute
		
		System.out.println("id : "+m.getId());
		System.out.println("pwd : "+m.getPwd());
		System.out.println("nick : "+m.getNick());
		System.out.println("age : "+m.getAge());
		
//		회원가입 성공하면 아래로
		return "member/join_result";
	}
}



리다이렉트

BoardController

package com.kh.app05.board.controller;

import org.springframework.stereotype.Controller;
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 com.kh.app05.board.model.vo.BoardVo;

@Controller
@RequestMapping("/board")
public class BoardController {

	@GetMapping("/insert")
	public String show() {
		System.out.println("board show~!");
		return "board/insert";
	}
	
	@PostMapping("/insert")
	public String insert(@ModelAttribute BoardVo b) {
		System.out.println("board insert~!");
		
		System.out.println("title : "+b.getTitle());
		System.out.println("content : "+b.getContent());
		
		//리다이렉트! 절대경로로?
		return "redirect:/board/insert_result";
	}
	
	@GetMapping("/insert_result")
	public String insert_result() {
		return "board/insert_result";
	}
}


insert.jsp

<%@ 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>
	<h1>board insert page</h1>
	
	<form action="insert" method="post">
		title : <input type="text" name="title"><br>
		content : <input type="text" name="content"><br>
		<input type="submit" name="등록"><br>
	
	</form>
</body>
</html>



다중 파라미터 처리

2) 파라미터 : (String[] 타입)

	@PostMapping("/select_color")
	public String selectColor(String[] color) {
		//다중 파라미터 처리
//		1) req.getParameterValues();
//		String[] colors = req.getParameterValues("color");
//		for(String s : colors) {
//			System.out.println(s);
//		}
		
//		2) 파라미터(String[] 타입)
		for(String s : color) {
			System.out.println(s);
		}
		return "redirect:/color/select_color";
	}


2-1) @ModelAttribute

	@PostMapping("/select_color")
	public String selectColor(@ModelAttribute ColorVo c) {
		//다중 파라미터 처리
		
//		2) 파라미터(String[] 타입)
		
		String[] colors = c.getColor();
		
		for(String s : colors) {
			System.out.println(s);
		}
		
		return "redirect:/color/select_color";
	}


ColorVo c

package com.kh.app05.color.model.vo;

import java.util.List;

public class ColorVo {
	
	private String[] color;

	public String[] getColor() {
		return color;
	}
	public void setColor(String[] color) {
		this.color = color;
	}
}


3) @RequestParam List<String>

	@PostMapping("/select_color")
	public String selectColor(@RequestParam List<String> color) {
		//다중 파라미터 처리
		
//		3) @RequestParam List<String>
		for(String s : color) {
			System.out.println(s);
		}
		return "redirect:/color/select_color";
	}
}


3-1) @ModelAttribute

	@PostMapping("/select_color")
	public String selectColor(@ModelAttribute ColorVo c) {
		//다중 파라미터 처리
//		3) 		
		List<String> colors = c.getColor();
		
		for(String s : colors) {
			System.out.println(s);
		}

		return "redirect:/color/select_color";
	}


ColorVo c

package com.kh.app05.color.model.vo;

import java.util.List;

public class ColorVo {
	
	private List<String> color;

	public List<String> getColor() {
		return color;
	}

	public void setColor(List<String> color) {
		this.color = color;
	}
	
}



인코딩 - 필터로 처리

  • 4개의 생성자 중에서 아래 둘을 사용

  • 위를 사용할 예정

✨✨ web.xml

  • 아래를 추가
	<!-- 인코딩 필터 -->	
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>


FoodController

package com.kh.app06.food.controller;

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

@Controller
public class FoodController {

	@GetMapping("/food")
	public String food() {
		return "food";
	}
	
	@PostMapping("/food")
	public String food(String food, String price) {
		System.out.println("food : "+food);
		System.out.println("price : "+price);
		
		return "food";
	}
}


food.jsp

<%@ 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>
	<h1>hi food</h1>
	
	<form action="food" method="post">
		이름 : <input type="text" name="food"><br>
		가격 : <input type="text" name="price"><br>
		<input type="submit" value="제출">
	</form>
</body>
</html>




데이터베이스

✨✨ pom.xml

  • Test 아래에 추가
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>     
		
		<!-- DB -->
		<!-- ojdbc8 -->
		<dependency>
		    <groupId>com.oracle.database.jdbc</groupId>
		    <artifactId>ojdbc8</artifactId>
		    <version>21.1.0.0</version>
		</dependency>   
	</dependencies>

  • 이렇게 추가됨!!


TestController

package com.kh.app07.controller;

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

@Controller
public class TestController {

	@GetMapping("/test")
	public String test() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {
			System.out.println("fail...");
			e.printStackTrace();
		}
		System.out.println("success");
		
		return "redirect:/";
	}
}
  • http://localhost:8888/app07/test



0개의 댓글