JSP & HTML input 입력값 받아서 출력하기

728x90

input - 입력값 얻어와서 출력하기

input은 HTML의 태그 중 하나인데, 사용자의 값을 받아와서 요청(request)해주는 기능을 가지고 있는 태그이다.

 

input의 사용법은 아래와 같다.

<%@ page contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
</style>
<title> title </title>
</head>
<body>
    <div>
        <form action="PW">
            <div>
                패스워드 입력창
            </div>
            <div>
                <input type="password" name="pwd">
                <input type="submit" name="subm">
            </div>
        </form>
    </div>
</body>
</html>

 

복잡해 보이지만 이해를 하면 별거 아니다! 하나씩 뜯어보자.

 

  • input을 사용하기 전에 form 태그로 감싸줘야 한다. form action = ""에 연산을 도와줄 Servlet 클래스의 이름을 넣으면 그 servlet 클래스로 이동하여 값이 연산된다. 말 그대로 action(행동)을 지정 Servlet에서 한다는 의미
  • input의 기능은 사용자의 값을 입력받아 서버로 요청해줄 수 있는 기능이다.
  • input type = "password"의 의미는 사용자가 입력하는 type이 password 타입으로만 입력할 수 있다는 의미이다.
  • name의 지정값은 나중에 servlet으로 getParameter 메서드를 사용해 parameter을 받아올 때 사용되는 변수의 값인데, 만약 servlet이 연산하는데 사용하는 변수값과 name값이 다르면 servlet이 연산을 하지 못한다.

 

아래는 "PW" Servlet의 코드 - getParameter로 받아온 값과 JSP의 name값이 같은 것을 볼 수 있다.

@WebServlet("/PW")
public class PW extends HttpServlet {

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset = utf-8");
		PrintWriter out = response.getWriter();
		
		String pw = "12345";
		String tmpPW = request.getParameter("pwd");
		
		if(tmpPW.equals(pw)){
			tmpPW.trim();
			out.print("정답!");
		}
		else{
			out.print("틀림!");
		}
	}
}

input의 type 속성

input이 어떻게 동작할 것인가를 정해준다 i.e) <input type = "button" name = "b">

 

728x90