1. MVC2패턴
- 기본 파일에 있는 내용 header, footer 분리
- index, member, user_join, header, footer, usercontroller, maincontroller
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file = "include/header.jsp" %>
<div class="container">
<div class="row ">
<div class="box">
<div class="col-lg-6 text-center">
<h2>coding404</h2>
<p>강의가 궁금하다면?</p>
<hr>
<h3><a href="https://www.youtube.com/channel/UCXiyuCYo4dUqM556XpgqAcQ">둘러보기</a></h3>
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel"><!-- data-ride="carousel" 자동 슬라이드 기능 -->
<ol class="carousel-indicators hidden-xs">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="item active">
<img class="img-responsive img-full" src="img/1.png">
</div>
<div class="item">
<img class="img-responsive img-full" src="img/2.png"> <!-- img-full 옵션 class -->
</div>
<div class="item">
<img class="img-responsive img-full" src="img/3.png">
</div>
</div>
<a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
<span class="icon-prev"></span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
<span class="icon-next"></span>
</a>
</div>
</div>
<div class="col-lg-6 text-center" >
<h2>hello world</h2>
<p>
깜빡하신게 있는것 같아요!
</p>
<hr>
<h3>구독과 좋아요</h3>
<iframe width="100%" height="351px" src="https://www.youtube.com/embed/nOTpuof2YG8?list=PLK7AWkPYwus6SdPJyhK9SNnKJybIC5qCs" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</div>
</div>
<div class="row">
<div class="box">
<div class="col-lg-12">
<hr>
<h2 class="intro-text text-center">hello World
<strong>유의 사항!</strong>
</h2>
<hr>
<div class="inner" align="center">
<img class="img-responsive img-center" src="img/intro.png" alt=""><!-- img-border -->
<hr class="visible-xs">
<p>1. 모든 자료는 회원 가입 후에 이용하실 수 있습니다.</p>
<p>2. ------------------------------------------------------</p>
<p>3. ------------------------------------------------------</p>
</div>
</div>
</div>
</div>
<!-- /.container -->
</div>
<%@ include file = "include/footer.jsp"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../include/header.jsp" %>
<div class="container">
<div class="row">
<div class="box">
<div class="col-lg-12">
<hr>
<h2 class="intro-text text-center">
<strong>Profile</strong>
</h2>
<hr>
</div>
<div class="col-sm-4 text-center">
<img class="img-responsive" src="../img/member7.jpg" alt="">
<h3>Actor
<small>한지민</small>
</h3>
</div>
<div class="col-sm-4 text-center">
</div>
<div class="col-sm-4 text-center">
<img class="img-responsive" src="../img/member8.jpg" alt="">
<h3>Age
<small>37</small>
</h3>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="row">
<div class="box">
<div class="col-lg-12">
<hr>
<h2 class="intro-text text-center">
<strong>화보</strong>
</h2>
<hr>
</div>
<div class="col-sm-4 text-center">
<img class="img-responsive" src="../img/member1.jpg" alt="">
<h3>
<small></small>
</h3>
</div>
<div class="col-sm-4 text-center">
<img class="img-responsive" src="../img/member2.jpg" alt="">
<h3>
<small></small>
</h3>
</div>
<div class="col-sm-4 text-center">
<img class="img-responsive" src="../img/member3.jpg" alt="">
<h3>
<small></small>
</h3>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="row">
<div class="box">
<div class="col-sm-4 text-center">
<img class="img-responsive" src="../img/member4.jpg" alt="">
<h3>
<small></small>
</h3>
</div>
<div class="col-sm-4 text-center">
<img class="img-responsive" src="../img/member5.jpg" alt="">
<h3>
<small></small>
</h3>
</div>
<div class="col-sm-4 text-center">
<img class="img-responsive" src="../img/member6.jpg" alt="">
<h3>
<small></small>
</h3>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
<!-- /.container -->
<%@ include file="../include/footer.jsp" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file = "../include/header.jsp" %>
<%@ include file = "../include/footer.jsp" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-idth, initial-scale=1">
<title>Welcome to MyWorld</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/business-casual.css" rel="stylesheet">
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Josefin+Slab:100,300,400,600,700,100italic,300italic,400italic,600italic,700italic" rel="stylesheet" type="text/css">
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<script>
$('.carousel').carousel({
interval: 2000 //changes the speed
})
</script>
<style>
.abc {
position: sticky;
top: 0px;
width: 100%;
z-index: 10;
}
</style>
</head>
<body>
<!-- header -->
<div class="brand">My Web</div>
<div class="address-bar">Welcome to MyWorld</div>
<nav class="navbar navbar-default abc" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/hong">My First Web</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
<a href="${pageContext.request.contextPath }/index.main">HOME</a>
</li>
<li>
<a href="${pageContext.request.contextPath }/member/member.main">Member</a>
</li>
<li>
<a href="">BOARD</a>
</li>
<li>
<a href="">LOGIN</a>
</li>
<li>
<a href="${pageContext.request.contextPath }/" style="color:red">JOIN</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- end header -->
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<footer>
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<p>Copyright © By Park 2018.XX.XX~</p>
</div>
</div>
</div>
</footer>
package com.example.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;
@WebServlet("*.user")
public class UserController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doAction(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doAction(request, response);
}
//get, post 하나로 묶음
protected void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//한글 처리
request.setCharacterEncoding("utf-8");
//요청 분기
String uri = request.getRequestURI();
String path = request.getContextPath();
String command = uri.substring(path.length() );
System.out.println("요청 경로:" + command);
switch (command) {
case "/user/user_join.user":
request.getRequestDispatcher("user_join.jsp").forward(request, response);
break;
default:
break;
}
}
}
package com.example.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;
@WebServlet("*.main")
public class MainController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doAction(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doAction(request, response);
}
protected void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//main 화면
//and
//member 화면
request.setCharacterEncoding("utf-8");
String uri = request.getRequestURI();
String path = request.getContextPath();
String command = uri.substring(path.length() );
System.out.println("요청 경로:" + command);
switch (command) {
//index.main으로 들어오면 index.jsp로 나감
case "/index.main":
request.getRequestDispatcher("index.jsp").forward(request, response);
break;
case "/member/member.main":
request.getRequestDispatcher("member.jsp").forward(request, response);
break;
default:
break;
}
}
}
2. userDAO, userVO 만들기
- sql
- 오라클 관리자에서 jsp 계정 생성
create user jsp identified by jsp;
grant resource, connect to jsp;
alter user jsp default tablespace users quota unlimited on users;
- table user 생성
create table users (
id varchar2(30) primary key,
pw varchar2(30) not null,
name varchar2(30) not null,
email varchar2(30) unique,
gender char(1) check (gender in ('f', 'm'))
);
- UserDAO, UserVO
package com.example.user.model;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.example.util.JDBCUtil;
public class UserDAO {
//UserDAO는 불필요하게 여러개 만들어질 필요가 없기 때문에
//한개의 객체만 만들어지도록 Singleton 형식으로 설계합니다.
//1. 나 자신의 객체를 생성해서 1개로 제한합니다.
private static UserDAO instance = new UserDAO();
//2. 직접 객체를 생성할 수 없도록 생성자에 private
private UserDAO() {
//드라이버 클래스 로드
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("드라이버 클래스 로드 에러");
}
}
//3. 외부에서 객체 생성을 요구할 때 getter 메서드를 통해 1번의 객체를 반환
public static UserDAO getInstance() {
return instance;
}
//4. 필요한 데이터 베이스 변수 선언
public String URL = "jdbc:oracle:thin:@localhost:1521:xe";
public String UID = "jsp";
public String UPW = "jsp";
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
//5. 메서드
public int idCheck(String id, String email) {
int result = 0;
String sql = "select count(*) as total from users where id = ? or email = ?";
try {
//1. conn 객체
conn = DriverManager.getConnection(URL, UID, UPW);
//2. pstmt
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
pstmt.setString(2, email);
//3. 실행
rs = pstmt.executeQuery();
if(rs.next()) {
result = rs.getInt("total");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtil.close(conn, pstmt, rs);
}
return result;
}
//회원가입
public void join(UserVO vo) {
String sql = "insert into users values(?, ?, ?, ?, ?)";
try {
conn = DriverManager.getConnection(URL, UID, UPW);
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, vo.getId());
pstmt.setString(2, vo.getPw());
pstmt.setString(3, vo.getName());
pstmt.setString(4, vo.getEmail());
pstmt.setString(5, vo.getGender());
pstmt.executeUpdate(); //실행(성공시 1 반환, 실패시 0 반환)
} catch (Exception e) {
} finally {
JDBCUtil.close(conn, pstmt, rs);
}
}
//로그인
public UserVO login(String id, String pw) {
UserVO vo = null;
String sql = "select * from users where id = ? and pw = ?";
try {
conn = DriverManager.getConnection(URL, UID, UPW);
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
pstmt.setString(2, pw);
rs = pstmt.executeQuery();
//로그인이 되면 vo객체가 들어감
if(rs.next()) { //로그인 성공 후 vo에 회원정보 저장
String id2 = rs.getString("id"); //id
String name = rs.getString("name");
String email = rs.getString("email");
String gender = rs.getString("gender");
vo = new UserVO(id2, null, name, email, gender);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtil.close(conn, pstmt, rs);
}
return vo;
}
}
package com.example.user.model;
public class UserVO {
//화면 and 데이터베이스 컬럼과 동일한 멤버변수를 가집니다
private String id;
private String pw;
private String name;
private String email;
private String gender;
public UserVO() {
}
public UserVO(String id, String pw, String name, String email, String gender) {
super();
this.id = id;
this.pw = pw;
this.name = name;
this.email = email;
this.gender = gender;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
- user_join, user_login, user_mypage
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file = "../include/header.jsp" %>
<section>
<div align = "center">
<h3>회원 가입 연습</h3>
<!--
태그에서 제공하는 인풋 유효성 검사
pattern = "JS정규표현식"
required = "required"
정규 표현식에 일치하지 않으면 submit 불가
공백을 허용하지 않음
라디오 or 체크박스 미리 선택
checked = "checked"
셀렉트 박스 미리 선택
selected = "selected"
인풋 태그의 수정 불가(읽기 전용)-태그 값을 못 바꿈
readonly = "readonly"
인풋 태그 사용 안하기
disabled = "disabled"
-->
<form action = "joinForm.user" method = "post">
<span style = "color: red;">${msg }</span>
<table>
<tr>
<td>아이디</td>
<td><input type = "text" name = "id" placeholder = "4~8글자 영문자 숫자" pattern = "\w{4,8}" required="required"></td>
</tr>
<tr>
<td>비밀번호</td>
<td><input type = "password" name = "pw" placeholder = "4~8글자 영문자 숫자" pattern = "\w{4,8}" required="required"></td>
</tr>
<tr>
<td>이름</td>
<td><input type = "text" name = "name" pattern = "[가-힣]{3,}"></td>
</tr>
<tr>
<td>이메일</td>
<td><input type = "email" name = "email"></td>
</tr>
<tr>
<td>성별</td>
<td>
<input type = "radio" name = "gender" value = "f" checked = "checked"> 여자
<input type = "radio" name = "gender" value = "m"> 남자
</td>
</tr>
</table>
<input type = "submit" value = "가입">
<!--
js로 기능을 붙임
onclick = "location.href='경로'
-->
<input type = "button" value = "로그인 하기" onclick="location.href='user_login.user' ">
</form>
</div>
</section>
<!-- 화면에서 사용할 JS -->
<script>
var msg = '${msg}';
if(msg != ''){
alert(msg);
}
</script>
<%@ include file = "../include/footer.jsp" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file = "../include/header.jsp" %>
<section>
<div align = "center">
<form action = "loginForm.user" method = "post">
<h3>로그인 연습</h3>
<input type = "text" name = "id" placeholder = "아이디" ><br>
<input type = "password" name = "pw" placeholder = "비밀번호"><br>
<input type = "submit" value = "로그인" class = "btn btn-default">
</form>
</div>
</section>
<%@ include file = "../include/footer.jsp" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file = "../include/header.jsp" %>
<section>
<div align = "center">
${sessionScope.user_id }
<b>(${sessionScope.user_name })</b>님 환영합니다
</div>
</section>
<%@ include file = "../include/footer.jsp" %>
- UserService, UserServiceimpl
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file = "../include/header.jsp" %>
<section>
<div align = "center">
${sessionScope.user_id }
<b>(${sessionScope.user_name })</b>님 환영합니다
</div>
</section>
<%@ include file = "../include/footer.jsp" %>
package com.example.user.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.example.user.model.UserDAO;
import com.example.user.model.UserVO;
public class UserServiceImpl implements UserService {
//컨트롤러의 역할을 분담
//가입 처리
public int join(HttpServletRequest request, HttpServletResponse response) {
String id = request.getParameter("id");
String pw = request.getParameter("pw");
String name = request.getParameter("name");
String email = request.getParameter("email");
String gender = request.getParameter("gender");
//아이디 or email 중복 검사 → 가입
UserDAO dao = UserDAO.getInstance();
int result = dao.idCheck(id, email);
if(result >= 1) { //중복
return 1; //중복의 의미 반환
} else { //중복 x → 가입
UserVO vo = new UserVO(id, pw, name, email, gender);
dao.join(vo); //성공의 의미 반환
}
return result;
}
@Override
public UserVO login(HttpServletRequest request, HttpServletResponse response) {
String id = request.getParameter("id");
String pw = request.getParameter("pw");
UserDAO dao = UserDAO.getInstance();
UserVO vo = dao.login(id, pw);
return vo;
}
}
- JDBCUtil, UserController
package com.example.util;
import java.sql.*;
public class JDBCUtil {
public static void close(Connection conn,
PreparedStatement pstmt,
ResultSet rs) {
try {
if(conn != null) conn.close();
if(pstmt != null) pstmt.close();
if(rs != null) rs.close();
} catch (Exception e2) {
System.out.println("close 에러");
}
}
}
package com.example.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 com.example.user.model.UserVO;
import com.example.user.service.UserServiceImpl;
import oracle.net.aso.l;
@WebServlet("*.user")
public class UserController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doAction(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doAction(request, response);
}
//get, post 하나로 묶음
protected void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//한글 처리
request.setCharacterEncoding("utf-8");
//요청 분기
String uri = request.getRequestURI();
String path = request.getContextPath();
String command = uri.substring(path.length() );
System.out.println("요청 경로:" + command);
//서비스 영역
UserServiceImpl service = new UserServiceImpl();
switch (command) {
case "/user/user_join.user":
request.getRequestDispatcher("user_join.jsp").forward(request, response);
break;
case "/user/joinForm.user": //회원 가입 기능
int result = service.join(request, response);
if(result >= 1) { //아이디 중복
//메시지
request.setAttribute("msg", "아이디 or email이 중복입니다");
request.getRequestDispatcher("user_join.jsp").forward(request, response);
} else { //가입 성공
//mvc2에서 리다이렉트는 다시 컨트롤러를 태우는 요청
//request.getRequestDispatcher("user_login.jsp").forward(request, response);
response.sendRedirect("user_login.user");
}
break;
case "/user/user_login.user" : //로그인 페이지
request.getRequestDispatcher("user_login.jsp").forward(request, response);
break;
case "/user/loginForm.user": //로그인 요청
UserVO vo = service.login(request, response);
if(vo == null) { //로그인 실패
request.setAttribute("msg", "아이디 비밀번호를 확인하세요");
request.getRequestDispatcher("user_login.jsp").forward(request, response);
} else { //로그인 성공
//세션에 아이디, 이름을 저장
HttpSession session = request.getSession(); //자바에서 현재 세션 얻는 방법
session.setAttribute("user_id", vo.getId());
session.setAttribute("user_name", vo.getName());
//마이페이지
response.sendRedirect("user_mypage.user");
}
break;
case "/user/user_mypage.user": //마이페이지
request.getRequestDispatcher("user_mypage.jsp").forward(request, response);
break;
default:
break;
}
}
}