이전글 (로그인, 회원가입)
https://amongthestar.tistory.com/148
회원가입시 admin 컬럼의 값을 무조건 0으로 주고 DB에서 관리자를 선정하여 admin 값을 1로 고친다.
이번 포스팅은 관리자가 로그인했을 경우 어떤 기능들을 수행할 수 있는지에 대한 내용이다.
관리자로 로그인을 하면 먼저 관리자 페이지로 이동한다.
<login.jsp 중 ajax 부분>
$.ajax({
type : "post",
url : "login",
data : {"userid":$("#userid").val(), "pwd":$("#pwd").val()},
success : function(value){
switch(value.trim()){
case "0" : alert("로그인 성공"); location.href="/Tutoring/index.jsp"; break;
case "1" : alert("관리자 로그인"); location.href="/Tutoring/member/Adminview"; break;
case "2" : alert("비밀번호 오류"); break;
case "-1": alert("회원이 아닙니다"); location.href="/Tutoring/member/insert"; break;
default: alert(value.trim());
}
},
error: function(e){
alert("error:"+e);
}
})
WMemberAdminViewAction.java
(관리자 화면으로 이동하는 서블릿으로 "/Tutoring/member/AdminView" 경로에 해당한다.)
package com.wmember.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 javax.servlet.http.HttpSession;
import com.wmember.model.WMemberDAO;
import com.wmember.model.WMemberDTO;
/**
* Servlet implementation class WMemberAdminViewAction
*/
@WebServlet("/member/Adminview")
public class WMemberAdminViewAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public WMemberAdminViewAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
String userid=(String)session.getAttribute("userid");
WMemberDAO dao=WMemberDAO.getInstance();
WMemberDTO dto=dao.memberView(userid);
request.setAttribute("member", dto);
RequestDispatcher rd=request.getRequestDispatcher("Adminview.jsp");
rd.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
- a href로 이동하였으므로 doGet 내에서 처리되며 doPost에는 내용이 없다.
- 로그인으로 인해 생긴 seesion userid값으로 WMemberDAO.java의 memberVIew 메소드를 실행한다.
- WMemberDTO형의 dto 객체에 member라는 이름으로 담고 AdminView.jsp로 이동한다. 자신의 회원정보를 수정할 수 있는 화면이다.
<WMemberDAO.java의 memberView 메소드)>
//회원 상세보기
public WMemberDTO memberView(String userid) {
Connection con=null;
Statement st=null;
ResultSet rs=null;
WMemberDTO dto=null;
try {
con=getConnection();
String sql="select * from wmember where userid='"+userid+"'";
st=con.createStatement();
rs=st.executeQuery(sql);
if(rs.next()) {
dto=new WMemberDTO();
dto.setNum(rs.getInt("num"));
dto.setEmail(rs.getString("email"));
dto.setName(rs.getString("name"));
dto.setPwd(rs.getString("pwd"));
dto.setUserid(rs.getString("userid"));
dto.setAddress(rs.getString("address"));
dto.setPostcode(rs.getInt("postcode"));
dto.setDetailAddress(rs.getString("detailaddress"));
dto.setExtraAddress(rs.getString("extraaddress"));
dto.setAdmin(rs.getInt("admin"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, rs);
}
return dto;
}
AdminView.jsp
회원가입할때 폼 양식과 똑같다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../include/header.jsp" %>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
a{
text-decoration: none;
}
a:hover{
text-decoration: none;
}
.back2{
margin-top: 20px;
background-color: #f8f9fa;
border-radius: 20px;
}
#frm{
margin: 0 auto;
width: 50%;
}
.button{
text-align: center;
margin: 0 auto;
padding: 20px;
}
.sidebar{
float: left;
width: 200px;
height:200px;
margin-top: 60px;
margin-left: 60px;
}
.sidebar ul{
list-style: none;
}
.sidebar ul a{
line-height: 2em;
}
</style>
<aside class="sidebar">
<ul id="menu">
<li><h5><a href="/Tutoring/class/ClassInsert.jsp"> 강의입력</a></h5></li>
<li><h5><a href="/Tutoring/class/ClassList.jsp"> 강의목록</a></h5></li>
<li><h5><a href="/Tutoring/member/Adminview"> 계정설정</a></h5></li>
</ul>
</aside>
<div class="container" id="userInfo">
<br/>
<h5>계정설정</h5>
<div class="back2">
<form action="Adminupdate" method="post" id="frm">
<br/><br/>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">아이디</span>
</div>
<input type="text" class="form-control" name="userid" id="userid" value="${member.userid}" readonly="readonly">
</div>
<br/>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">이름</span>
</div>
<input type="text" class="form-control" id="name" value="${member.name}" name="name">
</div>
<br/>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">비밀번호</span>
</div>
<input type="password" class="form-control" id="pwd" value="${member.pwd}" name="pwd">
<input type="password" class="form-control" placeholder="비밀번호 확인" id="pwd_check" name="pwd_check">
</div>
<br/>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">이메일</span>
</div>
<input type="text" class="form-control" id="email" value="${member.email}" name="email">
</div>
<br/>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">우편번호</span>
</div>
<input type="text" id="sample6_postcode" name="sample6_postcode" value="${member.postcode}" readonly="readonly" class="form-control">
<div class="col align-self-end" >
<input type="button" onclick="sample6_execDaumPostcode()" value="우편번호" class="btn btn-secondary"><br>
</div>
</div>
<br/>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">주소</span>
</div>
<input type="text" id="sample6_address" name="sample6_address" value="${member.address}" placeholder="주소" class="form-control"><br>
</div>
<div class="input-group mb-3">
<input type="text" id="sample6_detailAddress" name="sample6_detailAddress" value="${member.detailAddress}" placeholder="상세주소" class="form-control">
<input type="text" id="sample6_extraAddress" name="sample6_extraAddress" value="${member.extraAddress}" placeholder="참고항목" class="form-control">
</div>
<div class="button">
<button id="send" class="btn btn-info">저장</button>
<input type="button" class="btn btn-danger" value="회원탈퇴" onclick="delCheck('${member.userid}')">
</div>
</form>
</div>
</div>
<br/><br/>
<%@ include file="../include/footer.jsp" %>
<script>
function delCheck(userid){
if(confirm("탈퇴하시겠습니까? 삭제된 회원정보는 되돌릴 수 없습니다.")){
location.href="delete?userid="+userid;
}
}
</script>
<script src="https://t1.daumcdn.net/mapjsapi/bundle/postcode/prod/postcode.v2.js"></script>
<script>
function sample6_execDaumPostcode() {
new daum.Postcode({
oncomplete: function(data) {
// 팝업에서 검색결과 항목을 클릭했을때 실행할 코드를 작성하는 부분.
// 각 주소의 노출 규칙에 따라 주소를 조합한다.
// 내려오는 변수가 값이 없는 경우엔 공백('')값을 가지므로, 이를 참고하여 분기 한다.
var addr = ''; // 주소 변수
var extraAddr = ''; // 참고항목 변수
//사용자가 선택한 주소 타입에 따라 해당 주소 값을 가져온다.
if (data.userSelectedType === 'R') { // 사용자가 도로명 주소를 선택했을 경우
addr = data.roadAddress;
} else { // 사용자가 지번 주소를 선택했을 경우(J)
addr = data.jibunAddress;
}
// 사용자가 선택한 주소가 도로명 타입일때 참고항목을 조합한다.
if(data.userSelectedType === 'R'){
// 법정동명이 있을 경우 추가한다. (법정리는 제외)
// 법정동의 경우 마지막 문자가 "동/로/가"로 끝난다.
if(data.bname !== '' && /[동|로|가]$/g.test(data.bname)){
extraAddr += data.bname;
}
// 건물명이 있고, 공동주택일 경우 추가한다.
if(data.buildingName !== '' && data.apartment === 'Y'){
extraAddr += (extraAddr !== '' ? ', ' + data.buildingName : data.buildingName);
}
// 표시할 참고항목이 있을 경우, 괄호까지 추가한 최종 문자열을 만든다.
if(extraAddr !== ''){
extraAddr = ' (' + extraAddr + ')';
}
// 조합된 참고항목을 해당 필드에 넣는다.
document.getElementById("sample6_extraAddress").value = extraAddr;
} else {
document.getElementById("sample6_extraAddress").value = '';
}
// 우편번호와 주소 정보를 해당 필드에 넣는다.
document.getElementById('sample6_postcode').value = data.zonecode;
document.getElementById("sample6_address").value = addr;
// 커서를 상세주소 필드로 이동한다.
document.getElementById("sample6_detailAddress").focus();
}
}).open();
}
</script>
<script>
var reg_email = /^([0-9a-zA-Z_\.-]+)@([0-9a-zA-Z_-]+)(\.[0-9a-zA-Z_-]+){1,2}$/;
$(document).ready(function(){
$("#send").click(function(){
//이름이 공백일때
if($("#name").val()==""){
alert("이름을 입력하세요");
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($("#pwd").val().length<6){
alert("비밀번호는 6글자 이상이어야 합니다.");
pw1.value="";
pw1.focus();
}
//이메일이 공백일때
if($("#email").val()==""){
alert("이메일을 입력하세요");
return false;
}
//이메일 양식
if(!$("#email").val().match(reg_email)){
alert("이메일을 정확하게 입력하세요");
$("#email").focus();
return false;
}
$("#frm").submit();
})//send
});//document
</script>
- 주소를 고칠 수 있도록 다음 우편번호 API 자바스크립트 코드를 붙여넣었다.
- 저장버튼을 누르면 form이 post방식으로 Adminupdate로 이동한다.
- 삭제버튼을 누르면 자바스크립트 delCheck 함수로 이동하고 userid값을 가지고 delete로 이동한다.
WMemberAdminUpdateAction.java
("저장"버튼을 눌렀을때 회원정보 수정할 수 있는 서블릿. 경로는 "/Tutoring/member/Adminupdate"에 해당)
package com.wmember.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.wmember.model.WMemberDAO;
import com.wmember.model.WMemberDTO;
/**
* Servlet implementation class MemberUpdate
*/
@WebServlet("/member/Adminupdate")
public class WMemberUpdateAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public WMemberUpdateAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
WMemberDTO member=new WMemberDTO();
member.setName(request.getParameter("name"));
member.setUserid(request.getParameter("userid"));
member.setPwd(request.getParameter("pwd"));
member.setEmail(request.getParameter("email"));
member.setPostcode(Integer.parseInt(request.getParameter("sample6_postcode")));
member.setAddress(request.getParameter("sample6_address"));
member.setDetailAddress(request.getParameter("sample6_detailAddress"));
member.setExtraAddress(request.getParameter("sample6_extraAddress"));
WMemberDAO dao=WMemberDAO.getInstance();
int flag=dao.memberUpdate(member);
if(flag==1) {
response.sendRedirect("/Tutoring/member/Adminview");
}
}
}
- member객체에 파라미터 값으로 받아온 변수들을 저장하고 WMemberDAO.java의 memberUpdate메소드를 실행
- 업데이트가 여부에 따라 flag 변수 값을 달리하고, 업데이트가 되었다면 상세정보 화면으로 다시 이동
<WMemberDAO.java의 memberUpdate메소드>
//회원정보 수정
public int memberUpdate(WMemberDTO vo) {
Connection con=null;
PreparedStatement ps=null;
int flag=0;
try {
con=getConnection();
String sql="update wmember set name=?, pwd=?, email=?, postcode=?, address=?, detailaddress=?, extraaddress=? where userid=?";
ps=con.prepareStatement(sql);
ps.setString(1, vo.getName());
ps.setString(2, vo.getPwd());
ps.setString(3, vo.getEmail());
ps.setInt(4, vo.getPostcode());
ps.setString(5, vo.getAddress());
ps.setString(6, vo.getDetailAddress());
ps.setString(7, vo.getExtraAddress());
ps.setString(8, vo.getUserid());
flag=ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, ps);
}
return flag;
}
WMemberDeleteAction.java
("회원탈퇴"버튼을 눌렀을때 회원정보를 삭제할 수 있는 서블릿. 경로는 "/Tutoring/member/delete"에 해당)
package com.wmember.action;
import java.io.IOException;
import java.util.ArrayList;
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.wmember.model.WMemberDAO;
/**
* Servlet implementation class MemberDelete
*/
@WebServlet("/member/delete")
public class WMemberDeleteAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public WMemberDeleteAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String userid=request.getParameter("userid");
WMemberDAO dao=WMemberDAO.getInstance();
dao.memberDel(userid);
HttpSession session=request.getSession();
session.invalidate();
response.sendRedirect("login");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
- 파라미터 값으로 받아온 userid를 이용하여 WMemberDAO.java의 memberDel 메소드를 수행한다.
<WMemberDAO.java의 memberDel 메소드>
//삭제
public void memberDel(String userid) {
Connection con=null;
Statement st=null;
try {
con=getConnection();
String sql="delete from wmember where userid='"+userid+"'";
st=con.createStatement();
st.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, null);
}
}
관리자로 로그인을 하면 계정설정 외에도 강의입력과 강의목록 탭이 보인다. 각각 jsp로 링크를 걸었다.
강의에 관련된 작업은 DB의 WClass 테이블을 활용한다.
강의 DB관련 DTO (WClassDTO.java)
package com.wmember.model;
public class WClassDTO {
private String clevel;
private int classnum;
private String classname;
private int stu_num;
private String stu_regdate;
private String topic;
private String content;
private String uploadFile;
public String getUploadFile() {
return uploadFile == null ? "" : uploadFile.trim();
}
public void setUploadFile(String uploadFile) {
this.uploadFile = uploadFile;
}
public String getClevel() {
return clevel == null ? "" : clevel.trim();
}
public void setClevel(String clevel) {
this.clevel = clevel;
}
public int getClassnum() {
return classnum;
}
public void setClassnum(int classnum) {
this.classnum = classnum;
}
public String getClassname() {
return classname == null ? "" : classname.trim();
}
public void setClassname(String classname) {
this.classname = classname;
}
public int getStu_num() {
return stu_num;
}
public void setStu_num(int stu_num) {
this.stu_num = stu_num;
}
public String getStu_regdate() {
return stu_regdate == null ? "" : stu_regdate.trim();
}
public void setStu_regdate(String stu_regdate) {
this.stu_regdate = stu_regdate;
}
public String getTopic() {
return topic == null ? "" : topic.trim();
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getContent() {
return content == null ? "" : content.trim();
}
public void setContent(String content) {
this.content = content;
}
}
ClassInsert.jsp
강의 입력폼
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../include/header.jsp" %>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
a{
text-decoration: none;
}
a:hover{
text-decoration: none;
}
.back2{
margin-top: 20px;
background-color: #f8f9fa;
border-radius: 20px;
}
#frm{
margin: 0 auto;
width: 50%;
}
.button{
text-align: center;
margin: 0 auto;
padding: 20px;
}
.sidebar{
float: left;
width: 200px;
height:200px;
margin-top: 60px;
margin-left: 60px;
}
.sidebar ul{
list-style: none;
}
.sidebar ul a{
line-height: 2em;
}
.thumb-image{
float:left;
width:200px;
position:relative;
padding:5px;
}
</style>
<aside class="sidebar">
<ul id="menu">
<li><h5><a href="/Tutoring/class/ClassInsert"> 강의입력</a></h5></li>
<li><h5><a href="/Tutoring/class/ClassList.jsp"> 강의목록</a></h5></li>
<li><h5><a href="/Tutoring/member/Adminview"> 계정설정</a></h5></li>
</ul>
</aside>
<div class="container">
<br/>
<h5>강의입력</h5>
<div class="back2">
<form action="ClassInsert" method="post" id="frm" enctype="multipart/form-data">
<br/><br/>
<div id="image-holder"></div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">강의 이미지</span>
</div>
<input type="file" class="form-control" id="uploadFile" name="uploadFile"><br>
</div>
<br/>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">강의분류</span>
</div>
<select name="clevel" id="clevel" name="clevel">
<option value="basic" class="form-control">유창한 영어의 기본 요소</option>
<option value="career" class="form-control">경력 개발</option>
<option value="expression" class="form-control">자신을 표현해보세요</option>
<option value="test" class="form-control">시험 준비</option>
</select>
</div>
<br/>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">강의명</span>
</div>
<input type="text" class="form-control" id="classname" name="classname">
</div>
<br/>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">강의 주제</span>
</div>
<input type="text" class="form-control" id="topic" name="topic">
</div>
<br/>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">강의설명</span>
</div>
<textarea rows="5" cols="20" class="form-control" id="content" name="content"></textarea>
</div>
<div class="button">
<input type="reset" class="btn btn-gray" value="취소">
<button id="send" class="btn btn-primary">강의등록</button>
</div>
</form>
</div>
</div>
<br/><br/>
<%@ include file="../include/footer.jsp" %>
<script>
$(document).ready(function(){
$("#send").click(function(){
if($("#classname").val()==""){
alert("강의명을 입력하세요");
$("#classname").focus();
return false;
}
if($("#topic").val()==""){
alert("강의주제를 입력하세요");
$("#topic").focus();
return false;
}
if($("#content").val()==""){
alert("강의설명을 입력하세요");
$("#content").focus();
return false;
}
$("#frm").submit();
})//send
$("#uploadFile").on('change', function () {
if (typeof (FileReader) != "undefined") {
var image_holder = $("#image-holder");
image_holder.empty();
var reader = new FileReader();
reader.onload = function (e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[0]);
} else {
alert("이 브라우저에서 지원하지 않는 확장자 입니다.");
}
});
});//document
</script>
- 입력 후 send 버튼을 누르면 form이 ClassInsert로 이동한다.
- 강의 이미지를 넣어야하기 때문에 form태그 안에 enctype="multipart/form-data" 를 추가하였다.
- 이미지 입력 프리뷰는 javascript image preview를 구글링하여 복사 붙여넣기 했다.
(이미지는 freepic.com에서 찾았다.)
WClassInsertAction.java
(강의입력 폼에서 넘어온 서블릿. 경로는 "/Tutoring/class/ClassInsert" 이다.)
package com.wclass.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import com.wmember.model.WClassDAO;
import com.wmember.model.WClassDTO;
import com.wmember.model.WMemberDAO;
import com.wmember.model.WMemberDTO;
/**
* Servlet implementation class WClassInsertAction
*/
@WebServlet("/class/ClassInsert")
public class WClassInsertAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public WClassInsertAction() {
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("ClassInsert.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");
WClassDAO dao=WClassDAO.getInstance();
int uploadFileSizeLimit=5*1024*1024;
String encType="UTF-8";
String savePath="upload";
ServletContext context=getServletContext();
String uploadFilePath=context.getRealPath(savePath);
//multipart/form 방식은 request.getParameter로 받아올 수 없음
MultipartRequest multi=new MultipartRequest(
request, //request객체
uploadFilePath, //서버상의 실제 디렉토리
uploadFileSizeLimit, //최대 업로드 파일 크기
encType, //인코딩 방법
new DefaultFileRenamePolicy()); //동일 파일 새이름 부여
//업로드된 파일이름 구하기
String fileName=multi.getFilesystemName("uploadFile");
if(fileName==null) { //파일 업로드 안됨
System.out.println("파일 업로드 되지 않았음");
}
WClassDTO wclass=new WClassDTO();
wclass.setUploadFile(fileName);
wclass.setClassname(multi.getParameter("classname"));
wclass.setClevel(multi.getParameter("clevel"));
wclass.setContent(multi.getParameter("content"));
wclass.setTopic(multi.getParameter("topic"));
int flag=dao.classInsert(wclass);
if(flag==1) {
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<script>");
out.println("alert('강의가 등록되었습니다');");
out.println("history.back(-1);");
out.println("</script>");
}
}
}
- multipart로 값들을 받아왔기 때문에 request 파라미터로 받아올 수 없다.
- 업로드한 이미지의 파일 이름을 구하고 wclass 객체에 담는다.
- WClassDAO.java의 classInsert 메소드를 수행하고 입력이 되었다면 return 된 flag 값을 판단하여 alert창을 띄운다.
- 여기서 오류가 많이 났는데.. 이유는 WClassDTO의 객체 이름을 처음에 class로 설정했었기 때문이다. 예약어로 변수명을 설정할 수 없다.
<WClassDAO.java의 classInsert 메소드>
//디비셋팅
private static WClassDAO instance=new WClassDAO();
public static WClassDAO 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/wiser");
return ds.getConnection();
}
//강의등록
public int classInsert(WClassDTO vo) {
Connection con=null;
PreparedStatement ps=null;
int flag=0;
try {
con=getConnection();
String sql="INSERT INTO wclass(classnum, classname, stu_num, stu_regdate, topic, content, "
+ "clevel, uploadfile)"
+ "VALUES(wclass_seq.nextval,?,0,0,?,?,?,?)";
ps=con.prepareStatement(sql);
ps.setString(1, vo.getClassname());
ps.setString(2, vo.getTopic());
ps.setString(3, vo.getContent());
ps.setString(4, vo.getClevel());
ps.setString(5, vo.getUploadFile());
flag=ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, ps);
}
return flag;
}
//닫기 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();
}
}
강의목록 탭을 클릭하면 ClassList.jsp으로 이동한다.
ClassList.jsp
- 강의목록에 관련된 jsp는 ClassList.jsp와 ClassListResult.jsp로 jsp로 나뉜다.
- ClassList.jsp는 $.get 방식으로 WClassListAction.java에서 받아온 강의목록을 정해진 영역에 뿌려주는 기능과, 검색 영역을 포함하고 있다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/include/header.jsp" %>
<script>
$(document).ready(function(){
getData(1,"","");
$("#btnSearch").on("click",function(){//검색버튼 클릭
getData(1,$("#field").val(),$("#word").val());
})
})//document
function getData(pageNum, field, word){
$.get("ClassList",
{"pageNum":pageNum, "field":field, "word":word},
function(d){
$("#result").html(d);
})
}
</script>
</head>
<body>
<div id="result"></div>
<div align = "center">
<form name = "search" id = "search" class="selectpicker" data-live-search="true">
<select name = "field" id = "field">
<option value = "classname">강의명</option>
</select>
<input type = "text" name = "word" id = "word">
<input type = "button" value = "검색" id = "btnSearch">
</form>
</div>
<br/>
</body>
</html>
<%@ include file="/include/footer.jsp" %>
WClassListAction.java
(ClassList.jsp와 ClassListResult.jsp로 값을 넘기는 서블릿. 경로는 "/Tutoring/class/classList"이다.)
package com.wclass.action;
import java.io.IOException;
import java.util.ArrayList;
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.wmember.model.PageUtil;
import com.wmember.model.WClassDAO;
import com.wmember.model.WClassDTO;
/**
* Servlet implementation class WClassListAction
*/
@WebServlet("/class/ClassList")
public class WClassListAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public WClassListAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
WClassDAO dao=WClassDAO.getInstance();
String pageNum=request.getParameter("pageNum")==null? "1":request.getParameter("pageNum");
int currentPage=Integer.parseInt(pageNum);
int pageSize=5;
int startRow=(currentPage-1)*pageSize+1;
int endRow=currentPage*pageSize;
int count=0;
String field=request.getParameter("field")==null? "":request.getParameter("field");
String word=request.getParameter("word")==null? "":request.getParameter("word");
count=dao.getCount(field,word);
int totPage=(count/pageSize)+(count%pageSize==0?0:1);
int pageBlock=3;
int startPage=((currentPage-1)/pageBlock)*pageBlock+1;
int endPage=startPage+pageBlock-1;
if(endPage>totPage) endPage=totPage;
PageUtil pu=new PageUtil();
pu.setCurrentPage(currentPage);
pu.setEndPage(endPage);
pu.setField(field);
pu.setPageBlock(pageBlock);
pu.setStartPage(startPage);
pu.setTotPage(totPage);
pu.setWord(word);
ArrayList<WClassDTO> arr=null;
if(word.equals("")) {
arr=dao.classList(startRow,endRow);
}else {
arr=dao.classList(field, word, startRow, endRow);
}
int rowNo=count-((currentPage-1)*pageSize);
request.setAttribute("rowNo", rowNo);
request.setAttribute("pu", pu);
request.setAttribute("wclass", arr);
request.setAttribute("count", count);
RequestDispatcher rd=request.getRequestDispatcher("ClassListResult.jsp");
rd.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
- if else문으로 검색일때와 검색이 아닐때를 나누어서 WClassDAO.java의 classList 메소드를 수행한다.
- 페이징을 위해 PageUtil.java를 만들었다. 게터세터 생성.
- 페이징 관련 객체들, 강의 수 출력 관련 객체들, 강의목록을 request.setAttribute 메소드에 담고 ClassListResult.jsp에서 뿌려준다.
<PageUtil.java>
package com.wmember.model;
public class PageUtil {
private int currentPage;
private int endPage;
private int startPage;
private int totPage;
private int pageBlock;
private String field;
private String word;
private int classnum;
public int getClassnum() {
return classnum;
}
public void setClassnum(int classnum) {
this.classnum = classnum;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getEndPage() {
return endPage;
}
public void setEndPage(int endPage) {
this.endPage = endPage;
}
public int getStartPage() {
return startPage;
}
public void setStartPage(int startPage) {
this.startPage = startPage;
}
public int getTotPage() {
return totPage;
}
public void setTotPage(int totPage) {
this.totPage = totPage;
}
public int getPageBlock() {
return pageBlock;
}
public void setPageBlock(int pageBlock) {
this.pageBlock = pageBlock;
}
public String getField() {
return field == null ? "" : field.trim();
}
public void setField(String field) {
this.field = field;
}
public String getWord() {
return word == null ? "" : word.trim();
}
public void setWord(String word) {
this.word = word;
}
}
<WClassDAO.java의 classList 메소드> (검색 아닐때)
//검색 아닌 전체보기
public ArrayList<WClassDTO> classList(int startRow, int endRow) {
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
ArrayList<WClassDTO>arr=new ArrayList<WClassDTO>();
try {
con=getConnection();
StringBuilder sb=new StringBuilder();
sb.append("select * from");
sb.append(" (select aa.*, rownum rn from");
sb.append(" (select * from wclass order by classnum desc) aa");
sb.append(" where rownum<=?) where rn>=?");
ps=con.prepareStatement(sb.toString());
ps.setInt(1, endRow);
ps.setInt(2, startRow);
rs=ps.executeQuery();
while(rs.next()) {
WClassDTO dto=new WClassDTO();
dto.setClassnum(rs.getInt("classnum"));
dto.setClassname(rs.getString("classname"));
dto.setStu_num(rs.getInt("stu_num"));
dto.setStu_regdate(rs.getString("stu_regdate"));
dto.setTopic(rs.getString("topic"));
dto.setContent(rs.getString("content"));
dto.setClevel(rs.getString("clevel"));
dto.setUploadFile((rs.getString("uploadfile")));
arr.add(dto);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, ps, rs);
}
return arr;
}
<WClassDAO.java의 classList 메소드> (검색했을때)
//검색 전체보기
public ArrayList<WClassDTO> classList(String field, String word, int startRow, int endRow) {
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
ArrayList<WClassDTO>arr=new ArrayList<WClassDTO>();
try {
con=getConnection();
StringBuilder sb=new StringBuilder();
sb.append("select * from");
sb.append(" (select aa.*, rownum rn from");
sb.append(" (select * from wclass where upper ("+field+") like upper ('%"+word+"%')");
sb.append(" order by classnum desc) aa");
sb.append(" where rownum<=?) where rn>=?");
ps=con.prepareStatement(sb.toString());
ps.setInt(1, endRow);
ps.setInt(2, startRow);
rs=ps.executeQuery();
while(rs.next()) {
WClassDTO dto=new WClassDTO();
dto.setClassnum(rs.getInt("classnum"));
dto.setClassname(rs.getString("classname"));
dto.setStu_num(rs.getInt("stu_num"));
dto.setStu_regdate(rs.getString("stu_regdate"));
dto.setTopic(rs.getString("topic"));
dto.setContent(rs.getString("content"));
dto.setClevel(rs.getString("clevel"));
dto.setUploadFile((rs.getString("uploadfile")));
arr.add(dto);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, ps, rs);
}
return arr;
}
<WClassDAO.java의 getCount 메소드> (if else를 이용해 검색과 검색아닌 경우를 분리)
//강의수 출력
public int getCount(String field, String word) {
Connection con=null;
Statement st=null;
ResultSet rs=null;
int count=0;
String sql="";
try {
con=getConnection();
st=con.createStatement();
if(word.equals("")) {
sql="select count(*) from wclass";
}else {
sql="select count(*) from wclass where upper ("+field+") like upper ('%"+word+"%')";
}
rs=st.executeQuery(sql);
if(rs.next()) {
count=rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, rs);
}
return count;
}
ClassListResult.jsp
- ClassListResult.jsp는 WClassListAction.java에서 넘어온 강의목록과 페이징 영역을 포함하고 있다.
- 강의목록을 클릭했을때 ClassList.jsp->WClassListAction.java->ClassResult.jsp로 이동한다.
- 나중에 설명할 장바구니 cartList.jsp와는 차이점이 있다. (cartList.jsp에는 페이징과 검색기능이 없다. $.getJSON으로 cartList.java에 가고 JSONObject과 JSONArray객체를 만들어서 뿌릴 값들을 저장한다. 그다음 다시 cartList.jsp로 돌아와서 $.each로 뿌린다.)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<style>
h5 a{
text-decoration: none;
color: black;
}
.back2{
margin-top: 20px;
background-color: #f8f9fa;
}
.sidebar{
float: left;
width: 200px;
height:200px;
margin-top: 60px;
margin-left: 60px;
}
.sidebar ul{
list-style: none;
}
.sidebar ul a{
line-height: 2em;
}
</style>
</head>
<body>
<aside class="sidebar">
<ul id="menu">
<li><h5><a href="/Tutoring/class/ClassInsert"> 강의입력</a></h5></li>
<li><h5><a href="/Tutoring/class/ClassList.jsp"> 강의목록</a></h5></li>
<li><h5><a href="/Tutoring/member/Adminview"> 계정설정</a></h5></li>
</ul>
</aside>
<div class="container">
<br/>
<h5><a href="ClassList.jsp">강의목록(<span id="cntSpan">${count}</span>)</a></h5>
<div class="back2">
<table class="table table-hover">
<thead>
<tr>
<th>번호</th>
<th>강의분류</th>
<th>강의명</th>
<th>강의 주제</th>
</tr>
</thead>
<tbody>
<c:forEach items="${wclass}" var="wclass" varStatus="st">
<tr>
<td>${rowNo-st.index}</td>
<c:if test="${wclass.clevel eq 'basic'}">
<td>유창한 영어의 기본 요소</td>
</c:if>
<c:if test="${wclass.clevel eq 'career'}">
<td>경력 개발</td>
</c:if>
<c:if test="${wclass.clevel eq 'expression'}">
<td>자신을 표현해보세요</td>
</c:if>
<c:if test="${wclass.clevel eq 'test'}">
<td>시험 준비</td>
</c:if>
<td><a href="ClassDetail?num=${wclass.classnum}">${wclass.classname}</a></td>
<td>${wclass.topic}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
<div align="center" class="text-success">
<c:if test="${pu.startPage>pu.pageBlock }"> <!-- 이전 -->
<a href="javascript:getData(${pu.startPage-pu.pageBlock},'${pu.field}','${pu.word}')">[이전]</a>
</c:if>
<c:forEach begin="${pu.startPage}" end="${pu.endPage}" var="i"><!-- 페이지 출력 -->
<c:if test="${i==pu.currentPage}"> <!-- 현재 페이지 -->
<c:out value="${i}"/>
</c:if>
<c:if test="${i!=pu.currentPage}"> <!-- 현재 페이지 아닌 경우 링크 부여-->
<a href="javascript:getData(${i},'${pu.field}','${pu.word}')">${i}</a>
</c:if>
</c:forEach>
<c:if test="${pu.endPage<pu.totPage}"> <!-- 다음-->
<a href="javascript:getData(${pu.endPage+1},'${pu.field}','${pu.word}')">[다음]</a>
</c:if>
</div>
<br/>
제목을 클릭하면 다음 코드에 의해 강의 상세보기 페이지로 이동한다.
<td><a href="ClassDetail?num=${wclass.classnum}">${wclass.classname}</a></td>
WClassDetail.java
(강의 상세보기 서블릿. 경로는 "/Tutoring/class/ClassDetail")
package com.wclass.action;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import com.wmember.model.WClassDAO;
import com.wmember.model.WClassDTO;
@WebServlet("/class/ClassDetail")
public class WClassDetailAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public WClassDetailAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
WClassDAO dao=WClassDAO.getInstance();
int num=Integer.parseInt(request.getParameter("num"));
WClassDTO dto=dao.classView(num);
request.setAttribute("dto", dto);
RequestDispatcher rd=request.getRequestDispatcher("ClassDetail.jsp");
rd.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
- ClassListResult.jsp에서 받아온 num값을 이용하여 WClassDAO.java의 classView 메소드를 실행한다.
- dto객체를 dto 이름으로 저장하여 ClassDetail.jsp로 내보낸다.
<WClassDAO.java의 classView 메소드>
//강의 상세보기
public WClassDTO classView (int classnum) {
Connection con=null;
Statement st=null;
ResultSet rs=null;
WClassDTO dto=null;
try {
con=getConnection();
st=con.createStatement();
String sql="select * from wclass where classnum="+classnum;
rs=st.executeQuery(sql);
if(rs.next()) {
dto=new WClassDTO();
dto.setClassnum(rs.getInt("classnum"));
dto.setClassname(rs.getString("classname"));
dto.setClevel(rs.getString("clevel"));
dto.setContent(rs.getString("content"));
dto.setStu_num(rs.getInt("stu_num"));
dto.setStu_regdate(rs.getString("stu_regdate"));
dto.setTopic(rs.getString("topic"));
dto.setUploadFile((rs.getString("uploadfile")));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, rs);
}
return dto;
}
ClassDetail.jsp
회원정보 수정과 마찬가지로 강의를 수정하고 삭제할 수 있는 폼을 포함하고 있다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../include/header.jsp" %>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
a{
text-decoration: none;
}
a:hover{
text-decoration: none;
}
.back2{
margin-top: 20px;
background-color: #f8f9fa;
border-radius: 20px;
}
#frm{
margin: 0 auto;
width: 50%;
}
.button{
text-align: center;
margin: 0 auto;
padding: 20px;
}
.sidebar{
float: left;
width: 200px;
height:200px;
margin-top: 60px;
margin-left: 60px;
}
.sidebar ul{
list-style: none;
}
.sidebar ul a{
line-height: 2em;
}
.thumb-image{
float:left;
width:200px;
position:relative;
padding:5px;
}
img{
width:200px;
}
</style>
<aside class="sidebar">
<ul id="menu">
<li><h5><a href="/Tutoring/class/ClassInsert.jsp"> 강의입력</a></h5></li>
<li><h5><a href="/Tutoring/class/ClassList.jsp"> 강의목록</a></h5></li>
<li><h5><a href="/Tutoring/member/Adminview"> 계정설정</a></h5></li>
</ul>
</aside>
<div class="container">
<br/>
<h5>강의입력</h5>
<div class="back2">
<form action="ClassUpdate" method="post" id="frm" enctype="multipart/form-data">
<br/><br/>
<div id="image-holder"></div>
<img src="/Tutoring/upload/${dto.uploadFile}">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">강의 이미지</span>
</div>
<input type="file" class="form-control" id="uploadFile" name="uploadFile">
<input type="text" class="form-control" value="${dto.uploadFile}">
</div>
<br/>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">강의분류</span>
</div>
<select name="clevel" id="clevel" name="clevel">
<option value="basic" class="form-control" >유창한 영어의 기본 요소</option>
<option value="career" class="form-control">경력 개발</option>
<option value="expression" class="form-control">자신을 표현해보세요</option>
<option value="test" class="form-control">시험 준비</option>
</select>
</div>
<br/>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">강의명</span>
</div>
<input type="text" class="form-control" id="classname" name="classname" value="${dto.classname}">
</div>
<br/>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">강의 주제</span>
</div>
<input type="text" class="form-control" id="topic" name="topic" value="${dto.topic}">
</div>
<br/>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">강의설명</span>
</div>
<textarea rows="5" cols="20" class="form-control" id="content" name="content">${dto.content}</textarea>
</div>
<br/>
<div class="button">
<button id="send" class="btn btn-info">저장</button>
<input type="button" class="btn btn-danger" value="강의삭제" onclick="delClassCheck('${dto.classnum}')">
</div>
<input type="hidden" id="classnum" name="classnum" value="${dto.classnum}">
</form>
</div>
</div>
<br/><br/>
<%@ include file="../include/footer.jsp" %>
<script>
$("select[name=clevel] option").each(function(){
if($(this).val()=='${dto.clevel}'){
$(this).prop("selected", true);
}
});
function delClassCheck(classnum){
if(confirm("삭제하시겠습니까? 삭제된 강의정보는 되돌릴 수 없습니다.")){
location.href="delete?classnum="+classnum;
}
}
$(document).ready(function(){
$("#send").click(function(){
if($("#classname").val()==""){
alert("강의명을 입력하세요");
$("#classname").focus();
return false;
}
if($("#topic").val()==""){
alert("강의주제를 입력하세요");
$("#topic").focus();
return false;
}
if($("#content").val()==""){
alert("강의설명을 입력하세요");
$("#content").focus();
return false;
}
$("#frm").submit();
})//send
$("#uploadFile").on('change', function () {
if (typeof (FileReader) != "undefined") {
var image_holder = $("#image-holder");
image_holder.empty();
var reader = new FileReader();
reader.onload = function (e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[0]);
} else {
alert("이 브라우저에서 지원하지 않는 확장자 입니다.");
}
});
});//document
</script>
- send버튼을 누르면 ClassUpdate로 post방식으로 넘어간다. 강의 이미지를 포함하고 있기 때문에 form 태그 안에 enctype="multipart/form-data"를 포함하고 있다.
WClassUpdate.java
(ClassDetail.jsp에서 넘어온 서블릿. 경로는 "/Tutoring/class/ClassUpdate"이다.)
package com.wclass.action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import com.wmember.model.WClassDAO;
import com.wmember.model.WClassDTO;
/**
* Servlet implementation class MemberUpdate
*/
@WebServlet("/class/ClassUpdate")
public class WClassUpdateAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public WClassUpdateAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
WClassDAO dao=WClassDAO.getInstance();
int uploadFileSizeLimit=5*1024*1024;
String encType="UTF-8";
String savePath="upload";
ServletContext context=getServletContext();
String uploadFilePath=context.getRealPath(savePath);
//multipart/form 방식은 request.getParameter로 받아올 수 없음
MultipartRequest multi=new MultipartRequest(
request, //request객체
uploadFilePath, //서버상의 실제 디렉토리
uploadFileSizeLimit, //최대 업로드 파일 크기
encType, //인코딩 방법
new DefaultFileRenamePolicy()); //동일 파일 새이름 부여
//업로드된 파일이름 구하기
String fileName=multi.getFilesystemName("uploadFile");
if(fileName==null) { //파일 업로드 안됨
System.out.println("파일 업로드 되지 않았음");
}
WClassDTO wclass=new WClassDTO();
wclass.setUploadFile(fileName);
wclass.setClassname(multi.getParameter("classname"));
wclass.setClevel(multi.getParameter("clevel"));
wclass.setContent(multi.getParameter("content"));
wclass.setTopic(multi.getParameter("topic"));
int classnum=Integer.parseInt(multi.getParameter("classnum"));
wclass.setClassnum(classnum);
int flag=dao.classUpdate(wclass);
if(flag==1) {
response.setContentType("text/html; charset=euc-kr");
PrintWriter out = response.getWriter();
out.println("<script>");
out.println("alert('강의정보가 수정되었습니다');");
out.println("history.back(-1);");
out.println("</script>");
}
}
}
- ClassInsert와 마찬가지로 MultipartRequest 메소드를 이용하여 객체를 선언한다.
- WClassDAO.java의 classUpdate 메소드를 수행하고 return 값이 있으면 alert 창을 띄운다.
<WClassDAO.java의 classUpdate 메소드>
//강의정보 수정
public int classUpdate(WClassDTO vo) {
Connection con=null;
PreparedStatement ps=null;
int flag=0;
try {
con=getConnection();
String sql="update wclass set classname=?, topic=?, content=?, clevel=?, uploadfile=? where classnum=?";
ps=con.prepareStatement(sql);
ps.setString(1, vo.getClassname());
ps.setString(2, vo.getTopic());
ps.setString(3, vo.getContent());
ps.setString(4, vo.getClevel());
ps.setString(5, vo.getUploadFile());
ps.setInt(6, vo.getClassnum());
flag=ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, ps);
}
return flag;
}
강의 상세보기(ClassDetail.jsp)에서 강의삭제 버튼을 누르면 자바스크립트의 delClassCheck로 강의번호를 들고 넘어간다.
function delClassCheck(classnum){
if(confirm("삭제하시겠습니까? 삭제된 강의정보는 되돌릴 수 없습니다.")){
location.href="delete?classnum="+classnum;
}
}
WClassDeleteAction.java
(강의 삭제 서블릿. 경로는 "/Tutoring/class/delete"이다.)
package com.wclass.action;
import java.io.IOException;
import javax.servlet.ServletContext;
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.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import com.wmember.model.WClassDAO;
/**
* Servlet implementation class WClassDeleteAction
*/
@WebServlet("/class/delete")
public class WClassDeleteAction extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public WClassDeleteAction() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
WClassDAO dao=WClassDAO.getInstance();
int classnum=Integer.parseInt(request.getParameter("classnum"));
dao.classDel(classnum);
response.sendRedirect("ClassList.jsp");
}
}
- 파라미터 값으로 받아온 classnum(강의번호)을 들고 WClassDAO.java의 classDel메소드를 수행한다.
- 삭제하고 난 뒤에는 ClassList.jsp로 다시 이동한다.
<WClassDAO.java의 classDel 메소드>
//삭제
public void classDel(int classnum) {
Connection con=null;
Statement st=null;
try {
con=getConnection();
String sql="delete from wclass where classnum='"+classnum+"'";
st=con.createStatement();
st.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(con, st, null);
}
}
WMemberLogout.java
(로그아웃 기능을 구현하는 서블릿. 경로는 "/Tutoring/member/logout"이다.)
package com.wmember.action;
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;
/**
* Servlet implementation class MemberLogout
*/
@WebServlet("/member/logout")
public class WMemberLogout extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public WMemberLogout() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
session.invalidate();
response.sendRedirect("login");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
https://github.com/kkj0712/JspProject_Tutoring
'Learning > JSP' 카테고리의 다른 글
JSP 개인프로젝트-영어 학습 사이트 만들기 (수강후기 게시판 전체보기, 게시글 입력) (0) | 2020.08.18 |
---|---|
JSP 개인프로젝트-영어 학습 사이트 만들기 (강의목록 전체보기, 상세보기) (0) | 2020.08.18 |
JSP 개인프로젝트-영어 학습 사이트 만들기 (로그인, 회원가입) (0) | 2020.08.18 |
파일 전송 (0) | 2020.08.06 |
게스트북 (평가리스트) 만들기 (0) | 2020.08.06 |