본문 바로가기

Learning/JSP

로그인, 회원가입, 게시판 만들기 1

  • ServletTest02 (address를 다른방식으로 표현. Controller를 하나로)

 

  • Dynamic Web Project로 ServletTest02 생성. src에 org.address.controller와 org.address.model 패키지 생성. org.address.model패키지에 SAddressDAO.java, SAddressDTO.java, ZipcodeDTO.java 파일 붙여넣기

 

  • WebContent에 detail.jsp, inser.jsp, list.jsp, zipCheck.jsp 붙여넣기

 

  • WebContent-WEB-INF-lib에 json-simple-1.1.1.jar와 jstl-1.2.jar 붙여넣기

 


  1. jsp에 action을 *.ad로 고치기

  1. org.address.controller 패키지에서 CommonController를 만들어서 *.ad로 매핑하기

  2. insert.ad=>AddrInsertAction

  3. list.ad=>AddrListAction

  4. delete.ad=>AddrDeleteAction

  5. Update.ad=>AddrUpdateAction

  6. Search.ad=>AddrSearchAction

  7. Action 인터페이스를 만들기

 

 


 

https://www.w3schools.com/bootstrap4/bootstrap_navs.asp

 

Bootstrap 4 Navs

Bootstrap 4 Navs Nav Menus Link Link Link Disabled If you want to create a simple horizontal menu, add the .nav class to a element, followed by .nav-item for each and add the .nav-link class to their links: Example

 

위 사이트에서 부트스트랩 디자인 사용하기

 


  • 로그인, 회원가입, 게시판 만들기 (Dynamic Web Project로 project01 생성)

 

  • src에는 com.member.action으로 서블릿 객체들 만들기, com.member.model로 DAO(인터페이스), DTO, DAOImpl 자바 클래스 만들기

  • WebContent에는 board, js, include, member 폴더 만들기

    • board 폴더에는 board.jsp (게시판)

    • js 폴더에는 member.js로 자바스크립트 파일 만들기 (New file에서 file 이름을 member.js로 하면 됨)

    • member 폴더에는 idCheck.jsp, join.jsp, list.jsp, login.jsp 파일을 만들기. 각각 폼 태그가 있어서 입력 양식이 됨. 

    • include에는 header와 footer jsp파일들을 만들고 폼 태그에서 그 주소로 찾아가도록 함

  • WEB-INF에 web.xml 파일을 붙여넣고 lib 폴더에 json, jstl 파일 붙여넣기

  • META-INF에 context.xml 파일 붙여넣기


 

  • 실행순서

 

  • header.jsp

  1. 부트스트랩으로 스타일을 지정한다. 

  2. 헤더의 메뉴에는 로그인, 회원가입, 게시판을 만든다.

  3. 로그인 링크는 login.me (로그인 버튼을 눌렀을때는 get방식으로 login.jsp로 넘어가고, 로그인 화면에서 로그인을 실행했을때는 post방식으로 값들을 입력할 수 있다. 회원가입과 게시판도 마찬가지로 get과 post 방식으로 분리하여 처리된다.)

  4. 회원가입 링크는 insert.me

  5. 게시판 링크는 board.me

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html lang="en">

<head>

  <title>Bootstrap Example</title>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

  <script src="/project01/js/member.js"></script>

</head>

<body>

<nav class="navbar navbar-expand-sm bg-dark navbar-dark">

  <!-- Brand/logo -->

  <a class="navbar-brand" href="#">

    <h3>LOGO</h3>

  </a>

 

  <!-- Links -->

  <ul class="navbar-nav">

    <li class="nav-item">

      <a class="nav-link" href="/project01/member/login.me">로그인</a>

    </li>

    <li class="nav-item">

      <a class="nav-link" href="/project01/member/insert.me">회원가입</a>

    </li>

    <li class="nav-item">

      <a class="nav-link" href="/project01/board/board.me">게시판</a>

    </li>

  </ul>

</nav>

 


 

  • footer.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<footer>

    <div class="jumbotron text-center" style="margin-bottom:0">

      <p>Footer</p>

    </div>

</footer>

</body>

</html>

 


  • join.jsp

  1. 상단에 include file로 header.jsp를 참조한다. 

  2. form action은 insert.me, method 방식은 post, id는 frm으로 선언

  3. 아이디, 패스워드, 이름, 이메일, 전화번호 작성란과 라디오버튼으로 회원종류를 구분한다.

  4. 하단에 include file로 footer.jsp를 참조한다.

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ include file="../include/header.jsp" %>

<div class="container">

  <form action="insert.me" method="post" id="frm">

    <div class="row">

        <div class="col">

          <label for="userid">id:</label>

          <input type="text" class="form-control" id="userid" placeholder="Enter id" name="userid" >

        </div>

        <div class="col align-self-end" >

          <button  type="button"  id="idcheck"  class="btn btn-primary">중복확인</button>

        </div>

    </div>

   

    <div class="form-group">

      <label for="name">Name:</label>

      <input type="text" class="form-control" id="name" placeholder="Enter name" name="name">

    </div>

    <div class="form-group">

      <label for="pwd">Password:</label>

      <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">

    </div>

   

    <div class="form-group">

      <label for="pwd_check">Password Confirm:</label>

      <input type="password" class="form-control" id="pwd_check" placeholder="Enter password Confirm" name="pwd_check">

    </div>

   

    <div class="form-group">

      <label for="email">Email:</label>

      <input type="text" class="form-control" id="email" placeholder="Enter Eamil" name="email">

    </div>

   

    <div class="form-group">

      <label for="phone">Phone:</label>

      <input type="text" class="form-control" id="phone" placeholder="Enter Phone" name="phone">

    </div>

   

    <div class="form-check-inline">

        <label class="form-check-label">

        <input type="radio" class="form-check-input" name="admin" value="1">관리자

        </label>

    </div>

    

    <div class="form-check-inline">

      <label class="form-check-label">

        <input type="radio" class="form-check-input" name="admin"  value="0" checked>일반회원

      </label>

    </div>

    <br/>

     <button  id="send"  class="btn btn-primary">회원가입</button>

    </form>

    </div>

<%@ include file="../include/footer.jsp" %>


 

  • join.jsp에서 action경로를 insert.me로 처리했기 때문에 그 파일이 필요하다.

  • Controller인 서블릿 MemberInsert.java를 com.member.action에 만들고 WebServlet 경로를 /member/insert.me로 잡아준다.

  • MemberInsert.java

 

package com.member.action;

import java.io.IOException;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.member.model.MemberDTO;

import com.member.model.SMemberDAOImpl;

/**

 * Servlet implementation class MemberInsert

 */

@WebServlet("/member/insert.me")

public class MemberInsert extends HttpServlet {

    private static final long serialVersionUID = 1L;

      

    /**

     * @see HttpServlet#HttpServlet()

     */

    public MemberInsert() {

        super();

        // TODO Auto-generated constructor stub

    }

    /**

     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        RequestDispatcher rd=request.getRequestDispatcher("join.jsp");

        rd.forward(request, response);

    }

    /**

     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

     */

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");

        SMemberDAOImpl dao=SMemberDAOImpl.getInstance();

        MemberDTO member=new MemberDTO();

        member.setAdmin(Integer.parseInt(request.getParameter("admin")));

        member.setEmail(request.getParameter("email"));

        member.setName(request.getParameter("name"));

        member.setPhone(request.getParameter("phone"));

        member.setPwd(request.getParameter("pwd"));

        member.setUserid(request.getParameter("userid"));

        dao.memberInsert(member);

        response.sendRedirect("login.me");

    }

}

 


 

  • member.js: 자바스크립트 파일

 

var exp= /^[0-9]{3}-[0-9]{4}-[0-9]{4}$/;

$(document).ready(function(){

    $("#send").click(function(){

        //아이디가 공백일때

        if($("#userid").val()==""){

            alert("아이디를 입력하세요");

            $("#userid").focus();

            return false;

        }

        //암호가 공백일때

        if($("#pwd").val()==""){

            alert("암호를 입력하세요");

            $("#pwd").focus();

            return false;

        }

        //암호확인이 공백일때

        if($("#pwd_check").val()==""){

            alert("암호확인 필수");

            $("#pwd_check").focus();

            return false;

        }

        //암호 일치확인

        if($("#pwd").val()!=$("#pwd_check").val()){

            alert("암호 불일치");

            $("#pwd_check").focus();

            return false;

        }

        if($("#name").val()==""){

            alert("이름을 입력하세요");

            return false;

        }

        if($("#email").val()==""){

            alert("이메일을 입력하세요");

            return false;

        }

        if($("#phone").val()==""){

            alert("전화번호를 입력하세요");

            return false;

        }

        //전화번호 확인

        if(!$("#phone").val().match(exp)){

            alert("전화번호 입력 양식이 아닙니다.");

            $("#phone").focus();

            return false;

        }

        $("#frm").submit();

    })//send

    

    //아이디 중복체크 버튼

    $("#idcheck").click(function(){

        window.open("idCheck.jsp", "", "width=600 height=500")

    }); //idcheck

    

    

});//document

 


 

  • login.jsp

  1. header.jsp와 footer.jsp파일을 include로 불러준다.

  2. 하단에 script태그를 쓰고 아이디와 암호 공백시 경고창을 띄우도록 해준다.

  3. ajax으로 login.me(post방식) url 연결하여 아이디와 비밀번호 대조하고 로그인하도록 처리한다.

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ include file="../include/header.jsp" %>

  <div class="container">

 

  <form action="login.me" method="post" id="loginFrm">

    <div class="form-group">

      <label for="userid">id:</label>

      <input type="text" class="form-control" id="userid" placeholder="Enter id" name="userid">

    </div>

    <div class="form-group">

      <label for="pwd">Password:</label>

      <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">

    </div>

    <div class="form-group form-check">

      <label class="form-check-label">

        <input class="form-check-input" type="checkbox" name="remember"> Remember me

      </label>

    </div>

    <button type="button" id="loginBtn" class="btn btn-primary">로그인</button>

  </form>

</div>

<script>

$("#loginBtn").click(function(){

    if($("#userid").val()==""){

        alert("아이디를 입력하세요");

        $("#userid").focus();

        return false;

    }

    if($("#pwd").val()==""){

        alert("암호를 입력하세요");

        $("#pwd").focus();

        return false;

    }

    $.ajax({

        type : "post",

        url  : "login.me",

        data : {"userid":$("#userid").val(), "pwd":$("#pwd").val()},

        success : function(value){

            switch(value.trim()){

            case "0" : alert("로그인 성공"); location.href="view.me"; break;

            case "1" : alert("관리자 로그인"); location.href="list.me"; break;

            case "2" : alert("비밀번호 오류"); break;

            case "-1": alert("회원이 아닙니다"); location.href="insert.me"; break;

            default: alert(value.trim());

            }

        },

        error: function(e){

            alert("error:"+e);

        }

    })

})//loginBtn

</script>

<%@ include file="../include/footer.jsp" %>


  • board.jsp: 아직 내용이 없음

 

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@ include file="../include/header.jsp" %>

<div class="container-fluid">

  <h3>게시판</h3>

</div>

<%@ include file="../include/footer.jsp" %>

 


 

  • login.jsp의 form action을 login.me로 했기 때문에 그 파일이 필요하다. 마찬가지로 Controller인 서블릿 MemberLogin.java를 생성하고 경로를 /member/login.me로 잡아준다.

  • MemberLogin.java

 

package com.member.action;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import com.member.model.SMemberDAOImpl;

/**

 * Servlet implementation class MemberLogin

 */

@WebServlet("/member/login.me")

public class MemberLogin extends HttpServlet {

    private static final long serialVersionUID = 1L;

      

    /**

     * @see HttpServlet#HttpServlet()

     */

    public MemberLogin() {

        super();

        // TODO Auto-generated constructor stub

    }

    /**

     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        RequestDispatcher rd=request.getRequestDispatcher("login.jsp");

        rd.forward(request, response);

    }

    /**

     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

     */

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");

        String userid=request.getParameter("userid");

        String pwd=request.getParameter("pwd");

        SMemberDAOImpl dao=SMemberDAOImpl.getInstance();

        int flag=dao.loginCheck(userid, pwd);

        if(flag==0 || flag==1) {

            HttpSession session=request.getSession();

            session.setAttribute("userid", userid);

        }

        response.setContentType("text/html;charset=utf-8");

        PrintWriter out = response.getWriter();

        out.println(flag);

    }

}

 


 

  • SMemberDAOImpl.java

 

package com.member.model;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.sql.DataSource;

public class SMemberDAOImpl implements MemberDAO{

    

    private static SMemberDAOImpl instance=new SMemberDAOImpl();

    public static SMemberDAOImpl getInstance() {

        return instance;

    }

    private Connection getConnection() throws Exception{

        Context initCtx=new InitialContext();

        Context envCtx=(Context) initCtx.lookup("java:comp/env");

        DataSource ds=(DataSource) envCtx.lookup("jdbc/member"); //context.xml의 name을 jdbc/member로 바꾸기

        return ds.getConnection();

    }

    

    //회원가입

    public void memberInsert(MemberDTO vo) {

        Connection con=null;

        PreparedStatement ps=null;

        

        try {

            con=getConnection();

            String sql="INSERT INTO jmember VALUES(?,?,?,?,?,?)";

            ps=con.prepareStatement(sql);

            ps.setString(1, vo.getUserid());

            ps.setString(2, vo.getName());

            ps.setString(3, vo.getPwd());

            ps.setString(4, vo.getEmail());

            ps.setString(5, vo.getPhone());

            ps.setInt(6, vo.getAdmin());

            ps.executeUpdate();

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            closeConnection(con, ps);

        }

    }

    @Override

    public ArrayList<MemberDTO> memberList() {

        // TODO Auto-generated method stub

        return null;

    }

    @Override

    public int memberUpdate(MemberDTO vo) {

        // TODO Auto-generated method stub

        return 0;

    }

    @Override

    public MemberDTO memberView(String userid) {

        // TODO Auto-generated method stub

        return null;

    }

    @Override

    public void memberDel(String userid) {

        // TODO Auto-generated method stub

        

    }

    @Override

    public String idCheck(String userid) {

        // TODO Auto-generated method stub

        return null;

    }

    //로그인체크 (비밀번호 오류: 2, 회원아님: -1, 관리자: 1, 일반회원: 0)

    public int loginCheck(String userid, String pwd) {

        Connection con=null;

        Statement st=null;

        ResultSet rs=null;

        int flag=-1;

        try {

            con=getConnection();

            String sql="select pwd, admin from jmember where userid='"+userid+"'";

            st=con.createStatement();

            rs=st.executeQuery(sql);

            if(rs.next()) { //id 맞음

                if(rs.getString("pwd").equals(pwd)) { //비번 일치

                    flag=rs.getInt("admin");

                }else { //비번 오류

                    flag=2;

                }

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            closeConnection(con, st, rs);

        }

        return flag;

    }

    

    @Override

    public int memberCount() {

        // TODO Auto-generated method stub

        return 0;

    }

    

    //닫기 closeConnection

    private void closeConnection(Connection con, PreparedStatement ps) {

        try {

            if(ps!=null) ps.close();

            if(con!=null) con.close();

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

    private void closeConnection(Connection con, Statement st, ResultSet rs) {

        try {

            if(st!=null) st.close();

            if(con!=null) con.close();

            if(rs!=null) rs.close();

        } catch (SQLException e) {

            e.printStackTrace();

        }

    }

    

}


 

  • MemberDTO.java: 객체생성 자바 빈즈

 

package com.member.model;

public class MemberDTO {

    private String name;

    private String userid;

    private String pwd;

    private String email;

    private String phone;

    private int admin;

    

    public String getName() {

        return name == null ? "" : name.trim();

    }

    public void setName(String name) {

        this.name = name;

    }

    public String getUserid() {

        return userid == null ? "" : userid.trim();

    }

    public void setUserid(String userid) {

        this.userid = userid;

    }

    public String getPwd() {

        return pwd == null ? "" : pwd.trim();

    }

    public void setPwd(String pwd) {

        this.pwd = pwd;

    }

    public String getEmail() {

        return email == null ? "" : email.trim();

    }

    public void setEmail(String email) {

        this.email = email;

    }

    public String getPhone() {

        return phone == null ? "" : phone.trim();

    }

    public void setPhone(String phone) {

        this.phone = phone;

    }

    public void setAdmin(int admin) {

        this.admin = admin;

    }

    public int getAdmin() {

        return admin;

    }

}


 

 

  • MemberDAO.java: 인터페이스 파일

 

package com.member.model;

import java.util.ArrayList;

public interface MemberDAO {

    //CRUD(create read update delete)라고 함

    //추가 (MemberVO 형의 vo 객체를 추가)

    public void memberInsert(MemberDTO vo);

    //전체보기 (전체리스트를 보려면? select에 들어가는 값 MemberVO 형의 ArrayList를 본다.)

    public ArrayList<MemberDTO>memberList();

    //수정

    public int memberUpdate(MemberDTO vo);

    //상세보기 (하나를 보려면? return값이 있다는 뜻. MemberVO형)

    public MemberDTO memberView(String userid);

    //삭제

    public void memberDel(String userid);

    //아이디 중복 체크 (리턴값은 userid)

    public String idCheck(String userid);

    //로그인 체크 (리턴값은 flag)

    public int loginCheck(String userid, String pwd);

    //전체회원 수

    public int memberCount();

}

 

'Learning > JSP' 카테고리의 다른 글

게스트북 (평가리스트) 만들기  (0) 2020.08.06
로그인, 회원가입, 게시판 만들기 2  (0) 2020.07.30
서블릿: 출력경로 통일하기  (0) 2020.07.29
서블릿으로 주소록 만들기  (0) 2020.07.28
JSTL  (0) 2020.07.27