<button type="button" class="btn btn-primary" onclick="location.href='${root}/login/form'" style="float: right;">로그인</button>
<body>
<div class="layout">
<div class="title">
<tiles:insertAttribute name="title"/>
</div>
<div class="menu">
<tiles:insertAttribute name="menu2"/>
</div>
<div class="main">
<tiles:insertAttribute name="main"/>
</div>
</div>
</body>
@Controller
public class LoginController {
@GetMapping("/login/form")
public String loginform() {
return "/sub2/login/loginform";
}
}
<!-- #layout3 -->
<definition name="layout3" template="/WEB-INF/layout/layout3.jsp">
<put-attribute name="title" value="/WEB-INF/layout/title.jsp"/>
<put-attribute name="menu2" value="/WEB-INF/layout/menu2.jsp" />
<put-attribute name="main" value="/WEB-INF/login/loginform.jsp"/>
</definition>
<!-- wild card#3 -->
<definition name="/sub2/*/*" extends="layout3">
<put-attribute name="main" value="/WEB-INF/{1}/{2}.jsp"></put-attribute>
</definition>
실행해보면 title 부분의 로그인 버튼을 눌렀을 때 새로운 레이아웃으로 뜬다.
<form action="update" method="post" enctype="multipart/form-data">
<input type="hidden" name="num" value="${dto.num }">
<table class="table table-bordered" style="width: 1000px; margin: 50px 50px;">
<caption><h3>상품 수정</h3></caption>
<tr bgcolor="pink">
<th style="width: 150px;">상품명</th>
<th style="width: 100px;">단가</th>
<th style="width: 250px;">이미지</th>
<th style="width: 350px;">미리보기</th>
</tr>
<tr>
<td>
<input type="text" class="form-control" name="sangpum" required="required" value="${dto.sangpum }">
</td>
<td>
<input type="text" class="form-control" name="price" required="required" value="${dto.price }">
</td>
<td>
<input type="file" class="form-control" name="upload" onchange="readURL(this);">
</td>
<td>
<div style="margin: 20px 20px;">
<img id="uploadimg" src="../photo/${dto.photoname }" alt="상품 이미지를 등록해주세요" style="width: 150px; height: 150px;" />
</div>
</td>
</tr>
<tr>
<td colspan="5" align="center">
<button type="submit" class="btn btn-primary">등록하기</button>
<button type="button" class="btn btn-seconday" onclick="location.href='list'">목록으로</button>
</td>
</tr>
</table>
</form>
public BootShopDto getData(String num);
public void updateBootShop(BootShopDto dto);
<select id="getData" resultType="bsdto" parameterType="String">
select * from bootshop where num = #{num}
</select>
<update id="updateBootShop" parameterType="String">
update bootshop set sangpum=#{sangpum}, price=#{price}
<if test="photoname!=null">
, photoname=#{photoname}
</if>
where num=#{num}
</update>
//updateform으로
@GetMapping("/bootshop/updateform")
public String uform(@RequestParam String num, Model model) {
BootShopDto dto = mapper.getData(num);
model.addAttribute("dto", dto);
return "/bootshop/updateform";
}
//update
@PostMapping("/bootshop/update")
public String update(@ModelAttribute BootShopDto dto,
@RequestParam MultipartFile upload,
HttpSession session) {
String path = session.getServletContext().getRealPath("/photo");
System.out.println(path);
//기존 사진 파일명
String oldfilename = mapper.getData(dto.getNum()).getPhotoname();
if(upload.getOriginalFilename().equals(""))
dto.setPhotoname(oldfilename);
else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String newfilename="f_"+sdf.format(new Date())+upload.getOriginalFilename();
dto.setPhotoname(newfilename);
deleteFile(path, oldfilename);
try {
upload.transferTo(new File(path+"/"+newfilename));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//update
mapper.updateBootShop(dto);
return "redirect:list";
}
//이미지 파일 삭제 메서드
public void deleteFile(String path, String fileName) {
File file = new File(path+"\\"+fileName);
if(file.exists()) { //해당 경로에 파일이 있는 경우 true 값 반환
file.delete();
System.out.println("파일 삭제 완료");
}
}
public void deleteBootShop(String num);
<delete id="deleteBootShop" parameterType="String">
delete from bootshop where num = #{num}
</delete>
//delete
@GetMapping("/bootshop/delete")
public String delete(@RequestParam String num,
HttpServletRequest request) {
String path = request.getServletContext().getRealPath("/save");
String filename = mapper.getData(num).getPhotoname();
//사진 삭제
deleteFile(path, filename);
//db에서도 삭제
mapper.deleteBootShop(num);
return "redirect:list";
}
//이미지 파일 삭제 메서드
public void deleteFile(String path, String fileName) {
File file = new File(path+"\\"+fileName);
if(file.exists()) { //해당 경로에 파일이 있는 경우 true 값 반환
file.delete();
System.out.println("파일 삭제 완료");
}
}
테이블 만들기:
create table bootmember (num smallint primary key auto_increment,
name varchar(20),
id varchar(20),
pass varchar(20),
photo varchar(100),
hp varchar(30),
addr varchar(100),
email varchar(50),
gaipday datetime)
package mini.data.dto;
import java.sql.Timestamp;
import org.apache.ibatis.type.Alias;
import lombok.Data;
@Data
@Alias("member")
public class MemberDto {
private String num;
private String name;
private String id;
private String pass;
private String photo;
private String hp;
private String addr;
private String email;
private Timestamp gaipday;
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mini.data.mapper.MemberMapperInter">
</mapper>
@Mapper
public interface MemberMapperInter {
public void insertMember(MemberDto dto);
public List<MemberDto> getAllMembers();
public int getSearchId(String id); //아이디 중복 체크
}
public interface MemberServiceInter {
public void insertMember(MemberDto dto);
public List<MemberDto> getAllMembers();
public int getSearchId(String id); //아이디 중복 체크
}
<mapper namespace="mini.data.mapper.MemberMapperInter">
<insert id="insertMember" parameterType="member">
insert into bootmember (name, id, pass, photo, hp, addr, email, gaipday) values(#{name},#{id},#{pass},#{photo},#{hp},#{addr},#{email},now())
</insert>
<select id="getAllMembers" resultType="member">
select * from bootmember order by num desc
</select>
<select id="getSearchId" parameterType="String" resultType="int">
select count(*) from bootmember where id=#{id}
</select>
</mapper>
@Service
public class MemberService implements MemberServiceInter {
@Autowired
MemberMapperInter mapperInter;
@Override
public void insertMember(MemberDto dto) {
// TODO Auto-generated method stub
mapperInter.insertMember(dto);
}
@Override
public List<MemberDto> getAllMembers() {
// TODO Auto-generated method stub
return mapperInter.getAllMembers();
}
@Override
public int getSearchId(String id) {
// TODO Auto-generated method stub
return mapperInter.getSearchId(id);
}
}
<script type="text/javascript">
$(function(){
//사진 선택 버튼 클릭시 파일 선택창 열기
$("#btnphoto").click(function(){
$("#myphoto").trigger("click");
});
//사진 선택하면 이미지 미리보기
$("#myphoto").change(function(){
if ($(this)[0].files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#showimg').attr('src', e.target.result);
}
reader.readAsDataURL($(this)[0].files[0]);
}
});
//2번째 비밀번호 입력시 체크
$("#pass2").keyup(function(){
var p1 = $("#pass").val();
var p2 = $(this).val();
if(p1==p2){
$("span.passsuccess").text("ok");
}else{
$("span.passsuccess").text("");
}
});
});
//submit 전에 호출하는 함수
function check(){
//사진
if($("#myphoto").val()==""){
alert("사진을 선택해주세요!");
return false;
}
//중복체크
if($("span.idsuccess").text()!="ok"){
alert("id 중복 체크를 해주세요!");
return false;
}
//비밀번호
if($("span.passsuccess").text()!="ok"){
alert("비밀번호를 확인해주세요!");
return false;
}
}
</script>
<form action="insert" method="post" enctype="multipart/form-data" onsubmit="return check()">
<table class="table table-bordered" style="width: 600px;">
<caption align="top"><h4 class="alert alert-danger"><b>회원가입</b></h4></caption>
<tr>
<td style="width: 250px;" rowspan="6" align="center">
<input type="file" name="myphoto" id="myphoto" style="display: none;">
<img alt="" src="" id="showimg">
<br><br>
<button type="button" id="btnphoto" class="btn btn-info">파일 선택</button>
</td>
<td>
<div class="form-inline">
<input type="text" placeholder="아이디 입력" id="id" name="id" class="form-control" style="width: 120px;" required="required">
<button type="button" class="btn btn-danger btn-sm" id="btnidcheck">중복 체크</button>
<span class="idsuccess" style="width: 60px; color: gray;"></span>
</div>
</td>
</tr>
<tr>
<td>
<div class="form-inline">
<input type="password" style="width: 120px;" class="form-control" name="pass" id="pass" placeholder="숫자 4자리" required="required">
<input type="password" style="width: 120px;" class="form-control" id="pass2" placeholder="비밀번호 확인" required="required">
<span class="passsuccess" style="width: 60px; color: gray;"></span>
</div>
</td>
</tr>
<tr>
<td>
<input type="text" name="name" class="form-control" style="width: 150px;" placeholder="이름을 입력하세요" required="required">
</td>
</tr>
<tr>
<td>
<input type="text" name="email" class="form-control" style="width: 200px;" placeholder="이메일을 입력하세요" required="required">
</td>
</tr>
<tr>
<td>
<input type="text" name="hp" class="form-control" style="width: 220px;" placeholder="(-)없이 핸드폰 번호만 입력하세요" required="required">
</td>
</tr>
<tr>
<td>
<input type="text" name="addr" class="form-control" style="width: 220px;" placeholder="주소를 입력하세요" required="required">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit" class="btn btn-success">가입</button>
<button type="button" class="btn btn-default" onclick="location.href='list'">목록</button>
</td>
</tr>
</table>
</form>
@Controller
public class MemberController {
@Autowired
MemberService service;
@GetMapping("/member/form")
public String form() {
return "/member/memberform";
}
@GetMapping("/member/list")
public String list(Model model) {
List<MemberDto> list = service.getAllMembers();
model.addAttribute("list", list);
model.addAttribute("totalCount", list.size());
return "/member/memberlist";
}
//id 중복 체크
@GetMapping("/member/idcheck")
@ResponseBody //json 반환에 필요 (@restController이면 필요없음)
public Map<String, Integer> idCheckProcess(String id){
Map<String , Integer> map = new HashMap<>();
//중복 체크하려는 id 갯수 찾기(1 or 0)
int count = service.getSearchId(id);
map.put("count", count); //count는 1 or 0의 값을 갖는다. -> {"count":0} or {"count":1}
return map;
}
//중복체크 버튼시 아이디 체크
$("#btnidcheck").click(function(){
$.ajax({
url:"idcheck",
type:"get",
data:{"id":$("#id").val()},
dataType:"json",
success: function(res){
if(res.count==0){
$("span.idsuccess").text("ok");
}else{
$("span.idsuccess").text("fail");
}
}
});
});
//아이디 입력시 idsuccess 값 지움
$("#id").keyup(function(){
$("span.idsuccess").text("");
});
멤버 폼에서 아이디 중복 체크, 비밀번호 입력 확인, 사진 첨부 확인까지 해놨으니 insert를 해준다.
//insert
@PostMapping("/member/insert")
public String insert(@ModelAttribute MemberDto dto,
@RequestParam MultipartFile myphoto, //파일 여러개 업로드의 경우 arraylist Multi~
HttpSession session) {
//업로드 될 실제 경로
String realPath=session.getServletContext().getRealPath("/photo");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String uploadname="p_"+sdf.format(new Date())+myphoto.getOriginalFilename();
dto.setPhoto(uploadname);
//실제 업로드
try {
myphoto.transferTo(new File(realPath+"\\"+uploadname));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//db에 저장
service.insertMember(dto);
return "redirect:list";
}
@GetMapping("/member/myinfo")
public String myinfo(Model model) {
List<MemberDto> list = service.getAllMembers();
model.addAttribute("list", list);
return "/member/myinfo";
}
이제 등록해놓은 것들은 조회해보자
<body>
<h2 class="alert alert-info">${totalCount }명의 회원이 가입되어 있습니다.</h2>
<hr>
<table class="table table-bordered" style="width: 1000px;">
<tr>
<th style="width: 50px;">번호</th>
<th style="width: 100px;">이름</th>
<th style="width: 100px;">아이디</th>
<th style="width: 120px;">연락처</th>
<th style="width: 150px;">이메일</th>
<th style="width: 120px;">주소</th>
<th style="width: 100px;">가입일</th>
<th style="width: 60px;"><input type="checkbox"> 삭제</th>
</tr>
<c:forEach var="dto" items="${list }" varStatus="i">
<tr>
<td>${i.count}</td>
<td><img alt="" src="../photo/${dto.photo }" style="width: 30px; height: 30px;"> ${dto.name }</td>
<td>${dto.id }</td>
<td>${dto.hp}</td>
<td>${dto.email }</td>
<td>${dto.addr }</td>
<td><fmt:formatDate value="${dto.gaipday }" pattern="yyyy-MM-dd"/> </td>
<td><input type="checkbox"></td>
</tr>
</c:forEach>
</table>
<button type="button" class="btn btn-danger" style="float: right;">삭제</button>
</body>
마이페이지 눌렀을 때 myinfo.jsp로 이동하게(일단은 getAllMembers로 조회해주고 로그인 조건에 맞춰서 데이터가 나오게 조절)
@GetMapping("/member/myinfo")
public String myinfo(Model model) {
List<MemberDto> list = service.getAllMembers();
model.addAttribute("list", list);
return "/member/myinfo";
}
<table class="table table-bordered" style="width: 700px;">
<c:forEach var="dto" items="${list }">
<tr>
<td style="width: 200px;" align="center" rowspan="5">
<img alt="" src="../photo/${dto.photo}" width="180" height="240" border="1">
</td>
<td style="width: 250px;">이름: ${dto.name }</td>
<td rowspan="5" align="center" width="200">
<button type="button" class="btn btn-warning">수정</button>
<button type="button" class="btn btn-danger">삭제</button>
</td>
</tr>
<tr>
<td>
아이디: ${dto.id }
</td>
</tr>
<tr>
<td>
이메일: ${dto.email }
</td>
</tr>
<tr>
<td>
연락처: ${dto.hp }
</td>
</tr>
<tr>
<td>
주소: ${dto.addr }
</td>
</tr>
</c:forEach>
</table>