SOCO
입력(요청)할 내용이 많은 경우 : post 요청 본문
입력할 것이 많으면 한 번에 get요청을 하지 못하고
get요청과 post요청을 나눠서
처음에는 입력폼을 받기 위한 get요청을 하고
그 결과를 post함
*get요청 : url에 쿼리스트링이 붙어진 상태로 요청됨
*post요청 : url에 쿼리스트링이 붙지 않음 -> 정보양이 많을 때, 회원가입&로그인 등 보안
<get요청>
1. html 파일
<body>
<div>
<form action="/notice-reg"> <!--서블릿 매핑주소 -->
<div>
<label> 제목 : </label> <input name="title" type="text"> <!-- 한 줄만 쓸 수 있음 -->
</div>
<div>
<label> 내용 </label>
<textarea name="content"></textarea> <!-- 여러 줄 쓸 수 있음 -->
</div>
<div>
<input type="submit" value="등록" />
</div>
</form>
</div>
</body>
* form의 action -> 매핑된 서블릿 파일과 연결됨 (@WebServlet(""))
* input, textarea의 name이 키워드가 됨 -> 서블릿에서 getParameter과 연결됨
(name이라는 변수를 설정하는 것이 아니라 input 태그의 name 명을 정해주는 것 ! -> 서블릿은 name으로 태그를 인식함)
*html 파일 자체에서는 변수 설정할 수 없음
2. 서블릿 파일
@WebServlet("/notice-reg")
public class NoticeReg extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
//request : 입력도구, response : 출력도구
response.setCharacterEncoding("UTF-8"); //인코딩 방식 지정 (문제2 이유1 해결)
response.setContentType("text/html; charset=UTF-8"); //문제1,문제2 이유2 해결
PrintWriter out = response.getWriter();
String title = request.getParameter("title");
String content = request.getParameter("content");
out.println(title);
out.println(content);
}
}
*request : 사용자의 입력을 받는 입력도구
=> "title"이라는 키 값을 통해 입력받은 내용을 title이라는 문자열 변수로 저장
=> "content"라는 키 값을 통해 입력받은 내용을 content라는 문자열 변수로 저장
*response : 사용자에게 출력하는 출력도구
3. url이 어떻게 되는가
http://localhost:8080/notice-reg?title=%EC%9A%B0%EC%99%80+%EC%8B%A0%EA%B8%B0%ED%95%B4%EC%9A%94+&content=%EB%B0%98%EA%B0%91%EC%8A%B5%EB%8B%88%EB%8B%A4+%EB%B0%98%EA%B0%91%EC%8A%B5%EB%8B%88%EB%8B%A4
밑줄 친 부분이 모두 쿼리스트링임 (?cnt=3)
title, content => 서블릿에서 만든 쿼리스트링 키값
서블릿으로만 만든 경우 사용자가 url에 따로 ?title=~~ 쳐야함
이러한 문제를 해결하기 위해 html에서 input을 받는 것임
input의 name과 앞에서 만든 키 값이 일치하면(title, content)
사용자가 입력한 내용으로 쿼리스트링이 만들어짐
<post 요청>
4. 사용자가 장문으로 입력하는 경우 쿼리스트링을 어떻게 만들어야할까 ? : post
<body>
<div>
<form action="/notice-reg" method="post">
<div>
<label> 제목 : </label> <input name="title" type="text"> <!-- 한 줄만 쓸 수 있음 -->
</div>
<div>
<label> 내용 </label>
<textarea name="content"></textarea> <!-- 여러 줄 쓸 수 있음 -->
</div>
<div>
<input type="submit" value="등록" />
</div>
</form>
</div>
</body>
이 경우 url : http://localhost:8080/notice-reg
'백 > Servlet,JSP(잠시 pause)' 카테고리의 다른 글
서블릿 필터 (0) | 2021.07.01 |
---|---|
post요청 : 한글 입력 문제 (0) | 2021.07.01 |
get요청(쿼리스트링, 사용자 입력을 통한 get요청) (0) | 2021.07.01 |
서블릿 출력 형식의 이해 : 문서형태지정&한글출력 (0) | 2021.07.01 |
매핑 (0) | 2021.07.01 |