2021-05-17(월) kosta - 스프링수업 8일차(금요일에 했던 loginform보완)
아래는 원래 있었던 loginform.jsp이다.
오늘은 checkbox를 클릭하고 표시되는 것들에 대해 나머지도 모두 ajax로 아래에 표시되도록 만들어보겠다.
지금부터 수정해보도록 하겠다.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <style> .deactive{display:none;} ..active{display:block;} </style> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script> $(function(){ $("input[name='jobSelect']").on("change",function(){ var _this = $(this).val(); $("div[class]").each(function(index,item){ if($(item).attr("id") == _this){ $(item).removeClass("deactive"); $(item).addClass("active"); }else{ $(item).removeClass("active"); $(item).addClass("deactive"); } }); }) }); </script> <script> $(function(){ $("#loginButton").click(function(){ var obj = {"userid":$("#userid").val(), "userpass":$("#userpw").val(), "address":$("#address").val(), "phone":$("#phone").val() }; alert(JSON.stringify(obj)); /* $.ajax({ url:"${pageContext.request.contextPath}/emp2/login3.do", type:"post", data: JSON.stringify(obj), contentType:"application/json;charset=utf-8", success:function(responseData){ console.log(responseData); $("#here").html(JSON.stringify(responseData)); } });*/ var param = jQuery("#userid").val()+"/"; param += jQuery("#userpw").val()+"/"; param += jQuery("#address").val()+"/"; param += jQuery("#phone").val()+""; alert(param); $.ajax({ url:"${pageContext.request.contextPath}/emp2/login3.do/"+param, type:"get", success:function(responseData){ console.log(responseData); var display = "<ul>"+ "<li>직원번호:"+responseData["employee_id"]+"</li>"+ "<li>이름:"+responseData["first_name"]+"</li>"+ "<li>email:"+responseData["email"]+"</li>"+ "<li>job_id:"+responseData["job_id"]+"</li></ul>"; $("#here").html(display); } }); }); }); </script> <script> $(function(){ $("#hiredateButton").click(function(){ var obj = {"sdate":$("#sdate").val(), "edate":$("#edate").val(), }; alert(JSON.stringify(obj)); var param = jQuery("#sdate").val()+"/"; param += jQuery("#edate").val()+""; alert(param); $.ajax({ url:"${pageContext.request.contextPath}/emp2/date.do/"+param, type:"get", success:function(responseData){ console.log(responseData); var display = "<ul>"+ "<li>직원번호:"+responseData["employee_id"]+"</li>"+ $("#here").html(display); } }); }); }); </script> </head> <body> <div> <fieldset> <legend>여러가지 작업들</legend> <input type="radio" name="jobSelect" value="login">로그인하기 <input type="radio" name="jobSelect" value="dept">부서로조회하기 <input type="radio" name="jobSelect" value="salary">급여로조회하기 <input type="radio" name="jobSelect" value="hiredate">입사일로하기(String) <input type="radio" name="jobSelect" value="hiredate2">입사일로하기(Date) <input type="radio" name="jobSelect" value="dynamic">동적조회하기 </fieldset> </div> <div id="login" class="active"> <h1>로그인하기</h1> <form> 아이디:<input type="text" name="userid" id = "userid" value=102><br> 비밀번호:<input type="password" name="userpw" id = "userpw" value="LDEHAAN"><br> <input type="hidden" name = "address" id = "address" value="안산시 단원구"> <input type="hidden" name = "phone" id = "phone" value="010"> <input type="button" value="로그인" id="loginButton"> </form> </div> <c:set var="cpath" value="${pageContext.request.contextPath}"/> <div id="hiredate" class="deactive"> <h1>일자로 조회하기 String타입</h1> <form> 시작일 : <input type="date" name="sdate" value="2005-01-01"> 종료일 : <input type="date" name="edate" value="2005-12-31"> <input type="button" value="일자로조회" id="hiredateButton"> </form> </div> <div id="hiredate2" class="deactive"> <h1>일자로 조회하기2 Date타입</h1> <form action="${cpath}/emp/selectByHiredate2.do"> 시작일 : <input type="date" name="sdate" value="2005-01-01"> 종료일 : <input type="date" name="edate" value="2005-12-31"> <input type="submit" value="일자로조회"> </form> </div> <div id="dept" class="deactive"> <h1>부서로 조회하기</h1> <form action="${cpath}/emp/selectByDept.do"> 부서 : <input type="number" name="deptid" value="10"> <input type="submit" value="부서로조회"> </form> </div> <div id="salary" class="deactive"> <h1>부서로 조회하기</h1> <form action="${cpath}/emp/selectBySalary.do"> <input type="number" name="minsal" value="15000"> <input type="number" name="maxsal" value="20000"> <input type="submit" value="급여로조회"> </form> </div> <div id="dynamic" class="deactive"> <h1>동적으로 조회하기</h1> <form action="${cpath}/emp/selectByCondition.do"> 부서:<input type="number" name="deptid" value="60"><br> 직책:<input type="text" name="jobid" value="IT_PROG"><br> 급여:<input type="number" name="sal" value="10000"><br> 시작날짜: <input type="date" name="hdate" value="2005-01-01"><br> 일자조회여부<input type="checkbox" name="chk" checked="checked" /> <input type="submit" value="동적 조회"> </form> </div> <div id="here">여기</div> </body> </html>
결과적으로 EmpTestRestController.java는 아래와같이 만들어졌다.
EmpTestRestController.java의 전체코드는 아래와 같다.
package com.kosta.controller; import java.sql.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.kosta.business.EmpService; import com.kosta.model.EmpVO; import com.kosta.model.UserVO2; import com.kosta.util.ConvertUtil; @RestController //@Controller + @ResponseBody @RequestMapping("/emp2/*") public class EmpTestRestController { @Autowired EmpService empService; Logger logger = LoggerFactory.getLogger(EmpTestRestController.class); @RequestMapping(value = "/emplist.do", produces = {"text/html;charset=UTF-8"}) //Content-type, MIMETYPE:text/html, text/plain public String test1() { return "<h1>직원리스트입니다ㅎㅎ</h1>"; } //JSON(JavaScript Object Notation):JavaScript Object형태의 문자열{"키":"값"} @RequestMapping(value = "/emp.do") public EmpVO test2() { EmpVO emp = empService.selectById(101); return emp; } @RequestMapping(value = "/emplist3.do") public List<EmpVO> test3() { List<EmpVO> emplist = empService.selectAll(); return emplist; } @RequestMapping(value = "/emplist4.do") public Map<Integer, EmpVO> test4() { List<EmpVO> emplist = empService.selectAll(); Map<Integer, EmpVO> map = new HashMap<Integer, EmpVO>(); emplist.forEach(emp->{map.put(emp.getEmployee_id(), emp);}); return map; } @RequestMapping(value = "/emp5.do/{empid}", method=RequestMethod.GET) public EmpVO test5(@PathVariable("empid") int empid) { EmpVO emp = empService.selectById(empid); return emp; } /* 5월 14일 금요일 점심시간 전까지 아래 내용들을 학습하였다. */ //Jackson라이브러리: //@ResponseBody보내기,@RequestBody로 받기 //@ResponseBody생략대신에 @RestController사용한다. Java Object ->JSON변경 //@RequestBody는 JSON받을때 사용 @RequestMapping(value = "/empinsert.do",produces="text/plain;charset=utf-8", method=RequestMethod.POST) public String test5(@RequestBody EmpVO emp) { logger.info(emp.toString()); int result = empService.insertemp(emp); return result>0?"입력성공":"입력실패"; } @RequestMapping(value = "/login3.do/{userid}/{userpw}/{address}/{phone}", produces = "application/json;charset=utf-8", method = RequestMethod.GET ) public EmpVO login(@PathVariable("userid") int userid, @PathVariable String userpw, @PathVariable String address, @PathVariable String phone) { logger.info("아이디는{} 비밀번호는{}",userid,userpw); logger.info("주소는{} 전화번호{}",address,phone); EmpVO emp = empService.loginChk(userid, userpw); return emp; } @RequestMapping(value = "/empDelete.do/{userid}", method = RequestMethod.DELETE, produces = "text/plain;charset=utf-8") public String login(@PathVariable("userid") int userid){ logger.info("아이디는{}",userid); int result = empService.deleteEmp(userid); return result>0?"삭제성공":"삭제실패"; } /* //목적 : GET,POST,PUT,DELETE //GET : URL이 자동 Encoding //POST : URL에 정보노출안함, 요청문서의 BODY부분에 encoding없이 간다. @RequestMapping(value = "/login3.do", method= RequestMethod.POST, produces = "application/json;charset=utf-8" ) public EmpVO login(@RequestBody UserVO2 user) { logger.info("user:{}",user.toString()); EmpVO emp = empService.loginChk(user.getUserid(),user.getUserpass()); return emp; } */ @RequestMapping(value = "/empUpdate.do",produces="text/plain;charset=utf-8", method=RequestMethod.PUT) public String test6(@RequestBody EmpVO emp) { logger.info(emp.toString()); int result = empService.updateEmp(emp); return result>0?"update성공":"update실패"; } @RequestMapping(value = "/date.do/{sdate}/{edate}", produces = "application/json;charset=utf-8", method = RequestMethod.GET ) public List<EmpVO> test7( @PathVariable String sdate, @PathVariable String edate) { logger.info("시작날짜{} 종료날짜{}",sdate,edate); List<EmpVO> emplist = empService.selectByHiredate(sdate, edate); return emplist; } /* 2021년 5월 17일 오전 9시 여기서부터 만들었다. */ @RequestMapping("/empByDept.do/{did}") //@PathVariable("")안에 이름이 있다면 이름 적어주면 된다. public List<EmpVO> empByDept(@PathVariable int did) { logger.info(did+""); List<EmpVO> emplist = empService.selectByDept(did); logger.info(emplist.size()+"건 조회됨"); return emplist; } @RequestMapping("/empBySal.do/{minsal}/{maxsal}") //@PathVariable("")안에 이름이 있다면 이름 적어주면 된다. public List<EmpVO> empBySal(@PathVariable int minsal,@PathVariable int maxsal) { logger.info(minsal+"-------"+maxsal); List<EmpVO> emplist = empService.selectBySalary(minsal,maxsal); logger.info(emplist.size()+"건 조회됨"); return emplist; } @RequestMapping("/empByDate.do/{startdate}/{enddate}") //@PathVariable("")안에 이름이 있다면 이름 적어주면 된다. public List<EmpVO> empByDate(@PathVariable String startdate,@PathVariable String enddate) { logger.info(startdate+"-------"+enddate); List<EmpVO> emplist = empService.selectByHiredate(startdate,enddate); logger.info(emplist.size()+"건 조회됨"); return emplist; } @RequestMapping("/empByDate2.do/{startdate}/{enddate}") //@PathVariable("")안에 이름이 있다면 이름 적어주면 된다. public List<EmpVO> empByDate2(@PathVariable Date startdate,@PathVariable Date enddate) { logger.info(startdate+"-------"+enddate); List<EmpVO> emplist = empService.selectByHiredate2(startdate,enddate); logger.info(emplist.size()+"건 조회됨"); return emplist; } @RequestMapping("/empByConditon.do/{deptid}/{jobid}/{sal}/{hdate}/{chk}") //@PathVariable("")안에 이름이 있다면 이름 적어주면 된다. public List<EmpVO> empByConditon( @PathVariable int deptid,@PathVariable String jobid, @PathVariable int sal,@PathVariable Date hdate, @PathVariable Boolean chk) { logger.info(deptid+"--"+jobid+"--"+sal+"--"+hdate+"--"+chk); if(!chk) hdate=null; if(jobid.equals("null")) jobid = null; List<EmpVO> emplist = empService.selectByCondition(deptid,jobid,sal,hdate); logger.info(emplist.size()+"건 조회됨"); return emplist; } }
그리고 loginForm.jsp는 아래와 같이 코드되었다.
loginform.jsp의 전체 코드는 아래와 같다. 모두 button의 형태로 만들어주었고 버튼 클릭시 ajax가 되게 코드를 하였다.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <style> .deactive{display:none;} ..active{display:block;} </style> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script> $(function(){ $("input[name='jobSelect']").on("change",function(){ var _this = $(this).val(); $("div[class]").each(function(index,item){ if($(item).attr("id") == _this){ $(item).removeClass("deactive"); $(item).addClass("active"); }else{ $(item).removeClass("active"); $(item).addClass("deactive"); } }); }) }); </script> <script> $(function(){ $("#loginButton").click(function(){ var obj = {"userid":$("#userid").val(), "userpass":$("#userpw").val(), "address":$("#address").val(), "phone":$("#phone").val() }; alert(JSON.stringify(obj)); /* $.ajax({ url:"${pageContext.request.contextPath}/emp2/login3.do", type:"post", data: JSON.stringify(obj), contentType:"application/json;charset=utf-8", success:function(responseData){ console.log(responseData); $("#here").html(JSON.stringify(responseData)); } });*/ var param = jQuery("#userid").val()+"/"; param += jQuery("#userpw").val()+"/"; param += jQuery("#address").val()+"/"; param += jQuery("#phone").val()+""; alert(param); $.ajax({ url:"${pageContext.request.contextPath}/emp2/login3.do/"+param, type:"get", success:function(responseData){ console.log(responseData); var display = "<ul>"+ "<li>직원번호:"+responseData["employee_id"]+"</li>"+ "<li>이름:"+responseData["first_name"]+"</li>"+ "<li>email:"+responseData["email"]+"</li>"+ "<li>job_id:"+responseData["job_id"]+"</li></ul>"; $("#here").html(display); } }); }); }); </script> <script> $(function(){ $("#hiredateButton").click(function(){ var obj = {"sdate":$("#sdate").val(), "edate":$("#edate").val(), }; alert(JSON.stringify(obj)); var param = jQuery("#sdate").val()+"/"; param += jQuery("#edate").val()+""; alert(param); $.ajax({ url:"${pageContext.request.contextPath}/emp2/date.do/"+param, type:"get", success:function(responseData){ console.log(responseData); var display = "<ul>"+ "<li>직원번호:"+responseData["employee_id"]+"</li>"+ $("#here").html(display); } }); }); }); </script> <script> function resultPrint(responseData){ var output = "<ul>"; $.each(responseData, function(index, item){ output += "<li>"+item["first_name"]+"-->"+new Date(item["hire_date"])+"</li>"; }); output +="</ul>"; $("#here").html(output); } $(function(){ $("#dynamicBtn").click(function(){ var deptid = $("#deptid2").val(); if(deptid=="") deptid=0; var jobid = $("#jobid").val(); if(jobid=="") jobid=null; var sal = $("#sal").val(); if(sal=="") sal=0; var hdate = $("#hdate").val(); var chk = $("#chk").is(":checked"); //후승작품...boolean(true,false) //var chk = $("#chk:checked").val(); //상혁작품...string(on,undefined) alert(deptid+":"+jobid+":"+sal+":"+hdate+":"+chk); $.ajax({ url:"${pageContext.request.contextPath}/emp2/empByConditon.do/"+deptid+"/"+jobid+"/"+sal+"/"+hdate+"/"+chk, type:"get", success:resultPrint }); }); $("#btnDate2").click(function(){ var sdate = $("#sdate2").val(); var edate = $("#edate2").val(); //alert(minsal+":"+maxsal); $.ajax({ url:"${pageContext.request.contextPath}/emp2/empByDate2.do/"+sdate+"/"+edate, type:"get", success:resultPrint }); }); $("#btnDate").click(function(){ var sdate = $("#sdate").val(); var edate = $("#edate").val(); //alert(minsal+":"+maxsal); $.ajax({ url:"${pageContext.request.contextPath}/emp2/empByDate.do/"+sdate+"/"+edate, type:"get", success:resultPrint }); }); $("#btnSal").click(function(){ var minsal = $("#minsal").val(); var maxsal = $("#maxsal").val(); //alert(minsal+":"+maxsal); $.ajax({ url:"${pageContext.request.contextPath}/emp2/empBySal.do/"+minsal+"/"+maxsal, type:"get", success:function(responseData){ /* responsedata가 jackson으로 온다. */ console.log(responseData); var output = "<ul>"; $.each(responseData, function(index, item){ output += "<li>"+item["first_name"]+"</li>"; }); output +="</ul>"; $("#here").html(output); } }); }); $("#deptButton").click(function(){ var deptid = $("input[name='deptid']").first().val(); //alert(deptid); $.ajax({ url:"${pageContext.request.contextPath}/emp2/empByDept.do/"+deptid, type:"get", success:function(responseData){ /* responsedata가 jackson으로 온다. */ console.log(responseData); resultPrint(responseData); } }); }); }); </script> </head> <body> <div> <fieldset> <legend>여러가지 작업들</legend> <input type="radio" name="jobSelect" value="login">로그인하기 <input type="radio" name="jobSelect" value="dept">부서로조회하기 <input type="radio" name="jobSelect" value="salary">급여로조회하기 <input type="radio" name="jobSelect" value="hiredate">입사일로하기(String) <input type="radio" name="jobSelect" value="hiredate2">입사일로하기(Date) <input type="radio" name="jobSelect" value="dynamic">동적조회하기 </fieldset> </div> <div id="login" class="active"> <h1>로그인하기</h1> <form> 아이디:<input type="text" name="userid" id = "userid" value=102><br> 비밀번호:<input type="password" name="userpw" id = "userpw" value="LDEHAAN"><br> <input type="hidden" name = "address" id = "address" value="안산시 단원구"> <input type="hidden" name = "phone" id = "phone" value="010"> <input type="button" value="로그인" id="loginButton"> </form> </div> <c:set var="cpath" value="${pageContext.request.contextPath}"/> <div id="hiredate" class="deactive"> <h1>일자로 조회하기 String타입</h1> <form> 시작일 : <input type="date" id="sdate" value="2005-01-01"> 종료일 : <input type="date" id="edate" value="2005-12-31"> <input type="button" value="일자로조회" id="btnDate"> </form> </div> <div id="hiredate2" class="deactive"> <h1>일자로 조회하기2 Date타입</h1> <form> 시작일 : <input type="date" id="sdate2" value="2005-01-01"> 종료일 : <input type="date" id="edate2" value="2005-12-31"> <input type="button" value="일자로조회2" id="btnDate2"> </form> </div> <div id="dept" class="deactive"> <h1>부서로 조회하기</h1> <form> 부서 : <input type="number" name="deptid" value="10"> <input type="button" id="deptButton" value="부서로조회"> </form> </div> <div id="salary" class="deactive"> <h1>급여로조회하기</h1> <form> <input type="number" id="minsal" value="15000"> <input type="number" id="maxsal" value="20000"> <input type="button" id="btnSal" value="급여로조회"> </form> </div> <div id="dynamic" class="deactive"> <h1>동적으로 조회하기</h1> <form> 부서:<input type="number" id="deptid2" value="60"><br> 직책:<input type="text" id="jobid" value="IT_PROG"><br> 급여:<input type="number" id="sal" value="10000"><br> 시작날짜: <input type="date" id="hdate" value="2005-01-01"><br> <input type="checkbox" id="chk" checked="checked"/> 일자조회여부 <br> <input type="button" id="dynamicBtn" value="동적 조회"> </form> </div> <div id="here">여기</div> </body> </html>
자 이번에는 이미지를 넣어보도록하겠다. 이미를 넣기 위해서 먼저 resources밑에 폴더들을 만들어 주었다.
EmpInsert.jsp으로 가보자. Emp를 신규등록하면서 사진도 같이 넣도록 해보겠다. 그러기 위해서 enctype을 multipart로 바꿔주어야한다.
그리고 사진을 넣기 위해서 input type=file을 넣어주었다.
긜고 파일 업로드를 위한 dependency를 pom.xml에 추가해주었다.
emp/empInsert.do를 살펴보면 emp를 파마미터로 받아오는데 현재 우리가 만든 empvo에는 사진을 위한 필드가 없다. 그래서 사진을 위한 필드를 empvo에 만들어주도록 하자.
신규로 emp를 등록하면서 파일이 저장될 위치도 아래처럼 설정해주었다.
EmpVO에 uploadfile필드를 만들었다.
servlet-context.xml에 아래 bean도 추가해주었다. 그래야 된다.
그러면 이미지가 잘 들어간 것 을 확인할 수 있다.
직원 신규등록할때 이미지를 넣으면
이미지를 넣었던 6을 눌러보면
아래처럼 상세보기에 이미지가 잘 들어가는것을 볼수있다.
upload라는 폴더도 resources안에 넣어주었다.
그리고 오후에는 2차 팀프로젝트한 것을 Spring으로 바꿔주는 것을 했다. Mybatis만드는 것과 mapper만드는데 시간이 다갔다. 우리팀 DAO중 동적으로 sql문 만들어야 하는게 있는데 좀 더 공부해봐야겠다.