본문 바로가기
개발 수업/Spring

[spring] 파라미터 값 받기

by 오늘 하루s 2023. 8. 7.
728x90
더보기

Day70. 230807

http://localhost:8081/app/ 주소로 요청하면

컨트롤러에 입력한 name값의 홍GD와 현재시간이 페이지에 표시된다.

 


 

http://localhost:8081/app/test?id=hongid&age=12실행하면

콘솔창에 파라미터 id인 hongid와 age 11이 찍힌다.

 

 


여러 개의 파라미터 값 받기

 

컨트롤러 요청주소에 따라 http://localhost:8081/app/form01

을 요청하면 이름과 관심사를 전송한다.

관심사의 경우 여러 값을 전송하므로 hobbies를 배열로 받으면 여러 값을 전송할 수 있다.

 

 

 


HomeController.java>

package com.mycom.app;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	//요청주소  http://localhost:8081/app/test?id=hongid&age=12
	@RequestMapping(value = "/test", method = RequestMethod.GET)
	public String home(Locale locale, Model model,
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam("id") String rpid,
			@RequestParam("age") int rpage) {
		logger.info("Welcome home! The client locale is {}.", locale);
		//1.파라미터받기- 기존의 방식을 이용
		/*String 변수명 = request.getParameter("파라미터명");
		  리턴유형이 String이었으므로 필요시 형변환을 해야했다.*/
		String id = request.getParameter("id");
		int age = Integer.parseInt(request.getParameter("age"));
		System.out.println("syso 파라미터id="+id);
		System.out.println("syso 파라미터age="+(age-1));
		
		//1.파라미터-요청메서드안의 매개변수로 @RequestParam("파라미터명") 타입  매개변수명
		//매개변수의 타입을 자유롭게 지정할 수 있어 편리하다
		//@RequestParam("age") int rpage는 ?age=12라는 파라미터명이 age인 값을 받아서 int타입 변수 rpage에 저장
		logger.info("@RequestParam(id)는 {}",rpid); //콘솔
		logger.info("@RequestParam(age)는 {}",rpage-1);//콘솔
		
		//2.비즈니스로직
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		//3.Model
		response.setCharacterEncoding("UTF-8");
		request.setAttribute("name", "홍GD");
		
		//org.springframework.ui패키지의 Model이용
		model.addAttribute("serverTime", formattedDate );
		
		//4.view
		return "home";
	}
	
	//요청주소  http://localhost:포트번호/컨페/form01
	//요청주소  http://localhost:8081/app/form01
	//view  /WEB-INF/views/form01.jsp
	@RequestMapping("/form01")
	public String form01() {
		//1.파라미터받기
		//2.비즈니스로직
		//3.Model
		//4.View
		return "form01";
	}
	
	//요청방식  post
	//요청주소  http://localhost:8081/app/form01Result
	//view  /WEB-INF/views/form01Result.jsp
	@RequestMapping(value="/form01Result",method=RequestMethod.POST)
	public String form01Result(
			@RequestParam String userName,
			@RequestParam("hobby") String[]  hobbies) {
		//1.파라미터받기
		logger.info("이름:{}", userName);//콘솔
		logger.info("관심사:{}", hobbies);//콘솔
		for( String h: hobbies) {
			System.out.println(h);
		}
		//2.비즈니스로직
		//3.Model
		//4.View
		return "form01Result"; //   WEB-INF/views폴더안에  form01Result.jsp를 만들지 않았으므로 404에러가 뜬다
	}
	
}

 

home.jsp>

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<!DOCTYPE html>
<head>
	<title>Home</title>
</head>
<body>
<h1>
	Hello world!  
</h1>

<p>request.setAttribute("name") name:${name}</p>
<P>model.addAttribute("serverTime") 현재시간:${serverTime}. </P>

</body>
</html>

 

 

form01.jsp>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>요청 파라미터 관련 메서드</title>
</head>
<body>
 <h2>스프링에서의 파라미터받기</h2>
 현재주소 http://localhost:8081/app/form01
 <form id="frm1" action="form01Result" method="post">
 	*이름: 
 	<input type="text"  name="userName"        id="userName" 
	   	   size="10"    autofocus="autofocus"  placeholder="이름입력하세요"/>
 	<br/>
 	
 	*관심사(취미): <%-- hobby=coffee&hobby=movie&hobby=darama --%>
    <input type="checkbox" name="hobby" id="h0" value="coffee"  checked="checked"/><label for="h0">커피내리기</label>
    <input type="checkbox" name="hobby" id="h1" value="movie"/><label for="h1">영화감상</label>
    <input type="checkbox" name="hobby" id="h2" value="darama"/><label for="h2">드라마보기</label>
    <input type="checkbox" name="hobby" id="h3" value="toon"/><label for="h3">웹툰보기</label> 
    <input type="checkbox" name="hobby" id="h4" value="music"/><label for="h4">음악감상</label>  
    <input type="checkbox" name="hobby" id="h5" value="book"/><label for="h5">독서</label>
	<br/>
	
	<input type="submit" value="전송" />
	<input type="reset"  value="취소" />
 </form>
 
 
 <pre>
 
 

 
 
 
 
*form요소의  속성
 -action: 서버(server)측 페이지
 -method: get(기본값) | post

*GET에 대한 참고 사항:
 -양식 데이터를 이름/값 쌍으로 URL에 추가합니다.
 -GET을 사용하여 민감한 데이터를 보내지 마십시오! (제출된 양식 데이터는 URL에서 볼 수 있습니다!)
 -URL의 길이는 제한되어 있습니다(2048자).
 -사용자가 결과를 북마크하려는 양식 제출에 유용합니다.
 -GET은 Google의 쿼리 문자열과 같은 비보안 데이터에 적합합니다.

*POST에 대한 참고 사항:
 -HTTP 요청 본문 내부에 양식 데이터를 추가합니다(제출된 양식 데이터는 URL에 표시되지 않음).
 -POST는 크기 제한이 없으며 많은 양의 데이터를 보내는 데 사용할 수 있습니다.
 -POST를 사용한 양식 제출은 북마크할 수 없습니다.
</pre>	
</body>
</html>

 

 

728x90