[Servlet] getParameter / 아주아주 간단한 회원가입, 환율계산, 구구단출력, 로그인 페이지


사용자가 입력한 데이터 가져오기 - getParameter()


HTML form

  • <form><input type="submit"...></form>를 사용해 데이터를 서버로 전송하면 해당 Servlet 파일에서 HttpServletRequest 객체를 이용해 Parameter 값을 얻을 수 있다.

    • getParameter(name) : 해당 name의 value를 리턴, 항상 String 형태로 반환

    • getParameterValues(name) : 해당 name의 value를 리턴, 값이 여러개인 것 ex) 체크박스

    • getParameterNames() : form태그에서 넘어온 name값들을 전부 배열로 리턴



회원가입 페이지 만들기


  • Join.html

      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="UTF-8">
      <title>회원가입</title>
      </head>
      <body>
          <form action="join" method="post">
              이름 : <input type="text" name="name" size=10>
                
              <br><br>
                
              아이디 : <input type="text" name="id" size=10>
                
              <br><br>
                
              비밀번호 : <input type="password" name="pw" size=10>
                
              <br><br>
                
              관심 언어 : <input type="checkbox" name="interest" value="java">JAVA
                          <input type="checkbox" name="interest" value="python">Python
                          <input type="checkbox" name="interest" value="js">JavaScript
                          <input type="checkbox" name="interest" value="c">C
                            
              <br><br>
                
              이메일 수신 여부 : <input type="radio" name="email" value="y" checked="checked"><input type="radio" name="email" value="y">아니오
                            
              <br><br>
                
              <select name="route">
                  <option value="opt1">주위의 소개</option>
                  <option value="opt2" selected="selected">인터넷 검색</option>
                  <option value="opt3">기타</option>
              </select>
                
              <br><br>
                
              <input type="submit" value="가입하기">
              <input type="reset" value="다시 입력하기">
                
          </form>
    
      </body>
      </html>
    
  • Join.java

      import java.io.IOException;
      import java.io.PrintWriter;
      import java.util.Arrays;
    
      import javax.servlet.ServletException;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
    
      @WebServlet("/join")
      public class Join extends HttpServlet {
          private static final long serialVersionUID = 1L;
            
          public Join() {
          }
    
    
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          }
    
    
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                
              request.setCharacterEncoding("UTF-8");
                
              String name = request.getParameter("name");
              String id = request.getParameter("id");
              String pw = request.getParameter("pw");
                
              String[] interest = request.getParameterValues("interest");
                
              String email = request.getParameter("email");
              String route = request.getParameter("route");
                
              response.setContentType("text/html; charset=UTF-8");
                
              PrintWriter printWriter = response.getWriter();
              printWriter.println("<html><head></head><body>");
              printWriter.println("이름 : " + name + "<br>");
              printWriter.println("아이디 : " + id + "<br>");
              printWriter.println("비밀번호 : " + pw + "<br>");
              printWriter.println("관심언어 : " + Arrays.toString(interest) + "<br>");
              printWriter.println("이메일 수신 여부 : " + email + "<br>");
              printWriter.println("가입 경로 : " + route + "<br>");
              printWriter.println("</body></html>");
                
              printWriter.close();
          }
    
      }
    
  • 실행결과



환율 계산기 만들기


  • ServletCalc.java

      import java.io.IOException;
      import java.io.PrintWriter;
    
      import javax.servlet.ServletException;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
    
    
      @WebServlet("/calc")
      public class ServletCalc extends HttpServlet {
          private static final long serialVersionUID = 1L;
            
          private static double EUR_RATE = 1356.40;
          private static double USD_RATE = 1167.00;
          private static double JPY_RATE = 1023.55;
          private static double CNY_RATE = 183.02;
    
            
          public ServletCalc() {
              super();
          }
    
    
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
              request.setCharacterEncoding("UTF-8");
                
              response.setContentType("text/html; charset=UTF-8");
                
              PrintWriter writer = response.getWriter();
    
              String won = request.getParameter("won");
              String operator = request.getParameter("operator");
              String command = request.getParameter("command");
                
              if (command != null && command.equals("calculate")) {
                    
                  String res = calculate(Double.parseDouble(won), operator);
                  writer.println("<html><h3>" + res + "</h3>");
                  writer.println("<br><a href='calc'>다시 조회하기</a></html>");
                  return;
              }
                
              writer.println("<html><head><title>환율 계산</title></head>");
              writer.println("<body><form name='calc' method='get' action='calc'>");
              writer.println("원화 : <input type='text' name='won' size=10>");
              writer.println("<select name='operator'>");
              writer.println("<option value='eur'>유로</option>");
              writer.println("<option value='usd'>달러</option>");
              writer.println("<option value='jpy'>엔</option>");
              writer.println("<option value='cny'>위안</option>");
              writer.println("</select>");
              writer.println("<input type='hidden' name='command' value='calculate'>");
              writer.println("<input type='submit' value='환율조회'>");
              writer.println("</form></body></html>");
                
          }
    
    
          private static String calculate(double won, String operator) {
                
              String res = null;
                
              if (operator.equals("eur")) {
                  res = String.format("%.2f", won / EUR_RATE);
                    
              } else if (operator.equals("usd")) {
                  res = String.format("%.2f", won / USD_RATE);
                    
              } else if (operator.equals("jpy")) {
                  res = String.format("%.2f", won / JPY_RATE);
                    
              } else if (operator.equals("cny")) {
                  res = String.format("%.2f", won / CNY_RATE);
              }
              return res;
          }
    
    
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
          }
    
      }
    
  • 실행결과



구구단 출력 페이지 만들기


  • Gugudan.html

      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="UTF-8">
      <title>구구단</title>
      </head>
      <body>
          <h3>구구단 출력하기</h3>
            
          <form action="gugudan" method="get">
              <input type="text" name="num" size=2>단 출력
              <br>	
              <br>
              <input type="submit" value="출력하기">
          </form>
      </body>
      </html>
    
  • ServletGugudan.java

      import java.io.IOException;
      import java.io.PrintWriter;
    
      import javax.servlet.ServletException;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
    
      @WebServlet("/gugudan")
      public class ServletGugudan extends HttpServlet {
          private static final long serialVersionUID = 1L;
    
          public ServletGugudan() {
              super();
          }
    
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
              request.setCharacterEncoding("UTF-8");
              response.setContentType("text/html; charset=UTF-8");
                
              PrintWriter writer = response.getWriter();
                
               // getParameter() : 리턴 타입 String
              int num = Integer.parseInt(request.getParameter("num"));
                
              if (num<2 || num>9) {
                  return;
              }
                
                
              writer.println("<table width=100>");
              writer.println("<tr align=center><td colspan=2>" + num + "단</td>");
                
              for (int i = 2; i < 10; i++) {
                    
                  if (i % 2 == 0) {
                      writer.println("<tr bgcolor='#F6EABE'>");
                  } else {
                      writer.println("<tr bgcolor='#FEF5ED'>");
                  }
                    
                  writer.println("<td width=50>" + num + "*" + i + "</td>");
                  writer.println("<td width=50>" + num*i + "</td>");
                  writer.println("</tr>");
                
              }
                
              writer.println("</table>");
              writer.close();
                
          }
    
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
          }
    
      }
    
  • 실행결과



자바스크립트를 사용해 로그인 페이지 만들기


  • login.html

      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="UTF-8">
      <title>로그인</title>
      </head>
      <body>
          <form name="loginForm" action="login" method="post" enctype="UTF-8">
            
              아이디 : <input type="text" name="uid">
                
              <br><br>
                
              비밀번호 : <input type="password" name="upw">
                
              <br><br>
                
              <input type="button" onclick="fnValidate()" value="로그인">	
              <input type="reset" value="다시입력하기">
          </form>
            
          <script src="loginVal.js"></script>
      </body>
      </html>
    
  • loginVal.js

      function fnValidate(){
            
          let loginForm = document.loginForm;
          let uid = loginForm.uid.value;
          let upw = loginForm.upw.value;
            
          if((uid.length == 0) || uid == ""){
              alert("아이디를 입력해주세요.");
          } 
            
          else if((upw.length == 0) || upw == ""){
              alert("비밀번호를 입력해주세요.");
          } 
    
          else {
              loginForm.submit();	
          }
    
      };
    
  • ServletLogin.java

      import java.io.IOException;
      import java.io.PrintWriter;
    
      import javax.servlet.ServletException;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
    
      @WebServlet("/login")
      public class ServletLogin extends HttpServlet {
          private static final long serialVersionUID = 1L;
            
    
          public ServletLogin() {
              super();
          }
    
    
          protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
          }
    
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
              request.setCharacterEncoding("UTF-8");
              response.setContentType("text/html; charset=UTF-8");
                
              PrintWriter out = response.getWriter();
              out.print("<h1>로그인 성공! 🎉</h1>");
              out.close();
          }
    
      }
    
  • 실행결과

Categories:

JSP/Servlet