프로그래밍 언어/자바 & 코틀린
[JSP] form태그 이용해서 데이터 주고 받기
희랍인 조르바
2018. 3. 3. 17:19
회사에서 개발할 때 form태그보다는 처음부터 페이지를 띄울 때 값을 심어주거나
ajax를 통해서 데이터를 불러온다.
DB에 더미 데이터를 만들어야했는데 일일이 쿼리문을 치고 있는 시간보다 하나 개발하는게
더 빠를 거 같아서 페이지 하나를 개발했다. 그때 form 태그를 이용했다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>request parameter</title> </head> <body> <div> <form action="/blog/formTag.do" method="post"> <input type="text" name="title" placeholder="제목" value=""/> <input type="text" name="content" placeholder="내용" value=""/> <input type="submit" value="전송"/> </form> </div> </body> </html> | cs |
form 태그를 간단하게 만들면 이런 화면이 나온다.
컨트롤러에서 httpServletRequest를 파라미터로 받아줘야한다.
거기서 getParameter 메서드를 이용해 form태그에서 넘겼던 데이터를 조회한다.
getParameter의 return 타입은 String이다.
request.getParameter('name 태그의 값')로 받으면 된다.
컨트롤러를 아래와 같이 만들면 된다.
1 2 3 4 5 6 7 8 9 10 11 | @RequestMapping(value="/formTag.do") public ModelAndView formTag(HttpServletRequest request){ ModelAndView mv = new ModelAndView(); String title = request.getParameter("title"); String content = request.getParameter("content"); logger.info("title은? {}", title); logger.info("content은? {}", content); return mv; } | cs |
테스트로 제목에는 title test를 내용 부분에는 content test라고 입력했다.
그리고 전송버튼을 누르면,
아래와 같은 결과가 나온다.
다시말해, form 태그로 데이터를 넘길 때 method="post"를 선언해준다.
둘째, controller에서 HttpServletReqeust를 파라미터로 받아준다.
셋째, HttpServletReqeust의 getParameter 메서드를 이용해 form 태그에 있던 input 태그의 name을 입력해준다.
그럼 form태그로 데이터 이동 성공!