login.java 파일 생성
MySQL 테이블 생성
test
LoginDAO dao = new LoginDAOImple();
Login login = new Login();
login.setEmail("dm1234dms@gmail.com");
login.setPassword("1234");
System.out.println(dao.loginCheck(login));
LoginDAO(인터페이스) 파일 및 인터페이스 구현할 LoginDAOImple 파일 생성
LoginDAO
package webapp.dao;
import webapp.model.Login;
public interface LoginDAO {
//로그인 체크
String loginCheck(Login loginbean);
}
LoginDAOImple
package webapp.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import webapp.model.Login;
import webapp.util.DBConn;
public class LoginDAOImple implements LoginDAO {
//add
@Override
public String loginCheck(Login loginbean) {
String sql = "SELECT * FROM login WHERE email=? and password=?";
try {
Connection conn = DBConn.getConnection();// db 연결
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, loginbean.getEmail());
ps.setString(2, loginbean.getPassword());
ResultSet rs = ps.executeQuery();
// 이메일과 패스워드가 있으면 "true" 없으면 "false"리턴
if (rs.next()) {
return "true";
} else {
return "false";
}
} catch (Exception e) {
e.printStackTrace();
}
return "error";// catch문에서 나오면 "error"로 리턴
}
}
LoginController
package webapp.controller;
import java.io.IOException;
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 webapp.dao.LoginDAO;
import webapp.dao.LoginDAOImple;
import webapp.model.Login;
//주소변경
@WebServlet("/loginprocess")
public class LoginController extends HttpServlet {
private static final long serialVersionUID = 1L;
LoginDAO loginDAO = null;
public LoginController() {
loginDAO = new LoginDAOImple(); // 처음만 객체 생성하면되므로
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Login login = new Login();
login.setEmail(request.getParameter("email"));
login.setPassword(request.getParameter("password"));
String result = loginDAO.loginCheck(login);
if(result.equals("true")) {
session.setAttribute("email", login.getEmail());
response.sendRedirect("EmployeeController?action=LIST");
}
if(result.equals("false")) {
response.sendRedirect("index.jsp?status=false");
}
if(request.equals("error")) {
response.sendRedirect("index.jsp?status=error");
}
}
}
index.jsp
<html>
<head>
<title>Login System</title>
</head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<body>
<%
String email=(String)session.getAttribute("email");
//redirect user to home page if already logged in
if(email!=null){
response.sendRedirect("EmployeeController?action=LIST");
}
String status=request.getParameter("status");
if(status!=null){
if(status.equals("false")){
out.print("Incorrect login details!");
}
else{
out.print("Some error occurred!");
}
}
%>
<div class="container">
<form action="loginprocess" method="post">
<div class="card">
<div class="card-header text-left font-weight-bold">
Login
</div>
<div class="card-body">
<div class="form-group">
<input type="text" name="email" required class="form-control" placeholder="Enter Email"/>
</div>
<div class="form-group">
<input type="password" name="password" required class="form-control" placeholder="Enter password"/>
</div>
</div>
<div class="card-footer text-left">
<input type="submit" value="Login" class="btn btn-primary"/>
</div>
</div>
</form>
</div>
</body>
</html>
logout.jsp
<%
session.invalidate();
response.sendRedirect("index.jsp");
%>
xml 기본 페이지 수정
-> index.jsp로
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
<display-name>DATABASE</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 한글설정 필터추가 -->
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 한글설정 END -->
</web-app>
.
employee-list.jsp 수정
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<title>Employee Directory</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
//로그아웃 스타일 추가
<style>
.logout{
display: flex;
justify-content: space-between;
}
</style>
</head>
<body>
//추가되는 부분
<%
String email = (String) session.getAttribute("email");
if (email == null) {
response.sendRedirect("index.jsp");
}
%>
<div class="container">
<h1>Employee Directory</h1>
<hr />
<p>${NOTIFICATION}</p>
<p class="logout">
<button class="btn btn-primary"
onclick="window.location.href = 'views/employee-form.jsp'">직원
추가</button>
<a href="logout.jsp">로그아웃</a> //로그아웃 버튼 추가
</p>
<table class="table table-striped table-bordered">
<tr class="thead-dark">
<th>Name</th>
<th>Department</th>
<th>Date of birth</th>
<th>Actions</th>
</tr>
<c:forEach items="${list}" var="employee">
<tr>
<td>${employee.name}</td>
<td>${employee.department}</td>
<td>${employee.dob}</td>
<td><a
href="${pageContext.request.contextPath}/EmployeeController?action=EDIT&id=${employee.id}">Edit</a>
| <a onclick="return confirm('삭제하겠습니까?')"
href="${pageContext.request.contextPath}/EmployeeController?action=DELETE&id=${employee.id}">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
로그아웃 버튼 누를 시
데이터 테이블
만약 데이터가 많이 쌓이게되면 아래로 길어지게된다.
그래서
한페이지에 5개씩만 들어갈 수 있도록 데이터 테이블을 만들어준다.
https://datatables.net/manual/installation
employee-list.jsp 수정
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<title>Employee Directory</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- 데이터 테이블 -->
<link rel="stylesheet"
href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.css" />
<style>
.logout {
display: flex;
justify-content: space-between;
}
</style>
</head>
<body>
<%
String email = (String) session.getAttribute("email");
if (email == null) {
response.sendRedirect("index.jsp");
}
%>
<div class="container">
<h1>Employee Directory</h1>
<hr />
<p>${NOTIFICATION}</p>
<p class="logout">
<button class="btn btn-primary"
onclick="window.location.href = 'views/employee-form.jsp'">직원
추가</button>
<a href="logout.jsp">로그아웃</a>
</p>
<table id="datatable" class="table table-striped table-bordered">
<thead>
<tr class="thead-dark">
<th>Name</th>
<th>Department</th>
<th>Date of birth</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<c:forEach items="${list}" var="employee">
<tr>
<td>${employee.name}</td>
<td>${employee.department}</td>
<td>${employee.dob}</td>
<td><a class="btn btn-info"
href="${pageContext.request.contextPath}/EmployeeController?action=EDIT&id=${employee.id}">Edit</a>
| <a class="btn btn-danger" onclick="return confirm('삭제하겠습니까?')"
href="${pageContext.request.contextPath}/EmployeeController?action=DELETE&id=${employee.id}">Delete</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<!-- 스크립트 추가 -->
<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
$("#datatable").DataTable({
'language' : {
'lengthMenu' : '표시할 줄수 선택 _MENU_',
'search' : '검색',
'paginate' : {
'previous' : '이전',
'next' : '다음'
},
"info" : "페이지 _PAGE_ / _PAGES_",
'infoEmpty' : '데이터가 없습니다.',
"infoFiltered" : "(전체 페이지 _MAX_ 에서 검색)",
'thousands' : ','
},
'lengthMenu' : [ 5, 10, 25 ],
'pageLength' : 5,
'ordering' : false,
'stateSave' : true
});
})
</script>
</body>
</html>
'DB > MySQL' 카테고리의 다른 글
데이터베이스 (스키마) 한 파일로 묶어 내보내기 export (0) | 2023.09.27 |
---|---|
Simple DB 프로젝트-2 (0) | 2023.09.21 |
Simple DB 프로젝트 (0) | 2023.09.21 |