# File Size
servlet:
multipart:
max-file-size: 100MB
max-request-size: 10MB
<a href="/upLoadFormStart">파일업로드</a><p>
//upLoadForm 시작화면
@RequestMapping(value = "/upLoadFormStart")
private String upLoadForm(Model model) {
System.out.println("/upLoadFormStart Start **************");
return "upLoadFormStart";
}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
UpLoad Image : <img alt="UpLoad Image" src="${pageContext.request.contextPath}/upload/${savedName}">
<form id="form1" action="uploadForm" method="post" enctype="multipart/form-data" >
<input type="file" name="file1"> <p>
<input type="text" name="title"> <p>
<input type="submit">
</form>
<a href="uploadFileDelete">upLoad삭제Test</a>
</body>
</html>
// 이미지 업로드
@PostMapping(value = "uploadForm")
public String uploadForm(HttpServletRequest request, MultipartFile file1, Model model) throws IOException, Exception {
// Servlet 상속 받지 못했을 때 realPath 불러 오는 방법
String uploadPath = request.getSession().getServletContext().getRealPath("/upload/");
log.info("uploadForm POST Start...");
log.info("originalName: {}", file1.getOriginalFilename());
log.info("size: {}", file1.getSize());
log.info("contentType: {}", file1.getContentType());
log.info("uploadPath: {}", uploadPath);
//밑에서 리턴시킨 파일을 받음
String savedName = uploadFile(file1.getOriginalFilename(), file1.getBytes(), uploadPath);
log.info("savedName: {}", savedName);
//저장이름을 올려놓고
model.addAttribute("savedName", savedName);
// uploadResult 로 이동 -끝
return "uploadResult";
}
// 이미지 업로드 메서드
private String uploadFile(String originalName, byte[] fileData, String uploadPath) throws Exception {
// universally unique identifier (UUID).( 국제적으로 유일한 구별자 )
UUID uid = UUID.randomUUID(); //랜덤한 아이디를 뽑고 싶을때 uuid를 뽑음 ->똑같은 사진올릴때 파일명이 중첩되지 않음
// requestPath = requestPath + "/resources/image";
log.info("uploadPath->{}",uploadPath);
// Directory 생성
File fileDirectory = new File(uploadPath); //파일 업로드가져온거를 만듬
if (!fileDirectory.exists()) { //존재하지 않는다면
fileDirectory.mkdir(); // mkdir 신규 폴더 생성 //mkdirs(make)라는 메소드 제공 --> 파일을 알아서 만듬(-> uploadPath)
log.info("업로드용 폴더 생성 : {}", uploadPath);
}
String savedName = uid.toString() + "_" + originalName; //두번올려도 계속 파일은 올라감
log.info("savedName: {}", savedName);
File target = new File(uploadPath, savedName); //폴더명하고 파일명을 합쳐서 target만들어줌
// File target = new File(requestPath, savedName);
// File Upload -> uplaodPath / UUID+_+originalName
FileCopyUtils.copy(fileData, target); // org.springframework.util.FileCopyUtils
//파일의크기를 타겟에다가 복사해서 알아서 업로드해줌
return savedName; //올려준 파일이름을 리턴시킴
}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
KKK : ${kkk} <p>
Image : ${savedName} <p>
UpLoad Image : <img alt="UpLoad Image" src="${pageContext.request.contextPath}/upload/${savedName}">
</body>
</html>
// 이미지 삭제
@GetMapping(value = "uploadFileDelete")
public String uploadFileDelete(HttpServletRequest request, Model model) throws Exception {
String uploadPath = request.getSession().getServletContext().getRealPath("/upload/");
String deleteFile = uploadPath + "2e924e93-02c4-4128-a700-85219c80fa07_0833ce60-3c1a-43c2-acd5-925ce2b51753_1.gif";
log.info("deleteFile: {}", deleteFile);
log.info("uploadFileDelete Start...");
int delResult = upFileDelete(deleteFile);
log.info("deleteFile result -> {}", delResult);
model.addAttribute("deleteFile", deleteFile);
model.addAttribute("delResult", delResult);
return "uploadResult";
}
// 이미지 삭제 메서드
private int upFileDelete(String deleteFileName) throws Exception {
int result = 0;
log.info("upFileDelete result->{}", deleteFileName);
File file = new File(deleteFileName);
if(file.exists()) {
if(file.delete()) {
log.info("파일 삭제 성공");
result = 1;
}
else {
log.info("파일 삭제 실패");
result = 0;
}
}
else {
log.info("파일이 존재하지 않습니다.");
result = -1;
}
return result;
}
🔽업로드하면 업로드되어지고 파일이름 올려놓으면 삭제 됨
@Entity
@Data
@Table(name = "member3")
public class Member {
@Id
private Long id;
private String name;
private String password;
private Date reg_date;
}
인터페이스
public interface MemberJpaRepository {
Member save(Member member);
List<Member> findAll();
}
MemberJpaRepository 상속받음
package com.oracle.oBootMybatis01.repository;
import java.util.List;
import javax.persistence.EntityManager;
import org.springframework.stereotype.Repository;
import com.oracle.oBootMybatis01.domain.Member;
import lombok.RequiredArgsConstructor;
@Repository
@RequiredArgsConstructor
public class MemberJpaRepositoryImpl implements MemberJpaRepository {
private final EntityManager em;
@Override
public Member save(Member member) {
// TODO Auto-generated method stub
System.out.println("MemberJpaRepositoryImpl save START /. . . ");
em.persist(member);
return member;
}
@Override
public List<Member> findAll() {
System.out.println("MemberJpaRepositoryImpl findAll START /. . . ");
List<Member> memberList = em.createQuery("select m from Member m", Member.class)
.getResultList();
return memberList;
}
}
package com.oracle.oBootMybatis01.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.oracle.oBootMybatis01.domain.Member;
import com.oracle.oBootMybatis01.repository.MemberJpaRepository;
import lombok.RequiredArgsConstructor;
@Service
@Transactional
@RequiredArgsConstructor
public class MemberJpaService {
private final MemberJpaRepository memberJpaRepository;
//jpa회원가입
public Long join(Member member) {
System.out.println("MemberJpaService join member.getId() -> "+ member.getId());
memberJpaRepository.save(member);
return member.getId();
}
//전체회원 조회
public List<Member> getListAllMember() {
List<Member> listMember = memberJpaRepository.findAll();
System.out.println(" memJpaSerbice getListMember listMember.size()-> "+listMember.size() );
return listMember ;
}
}
package com.oracle.oBootMybatis01.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import com.oracle.oBootMybatis01.domain.Member;
import com.oracle.oBootMybatis01.service.MemberJpaService;
import lombok.RequiredArgsConstructor;
@Controller
@RequiredArgsConstructor
public class MemberJpaController {
private final MemberJpaService memJpaService;
@GetMapping(value = "/memberJpa/new")
public String createForm() {
System.out.println(" MemberJpaController/memberJpa/new ");
return "memberJpa/createMemberForm" ;
}
@PostMapping(value = "/memberJpa/save")
public String create(Member member ) {
System.out.println(" MemberJpaController/memberJpa/new ");
System.out.println("member.getId()"+member.getId() );
System.out.println("member.getName()"+member.getName());
memJpaService.join(member);
return "memberJpa/createMemberForm" ;
}
@GetMapping(value = "/members")
public String listMember(Model model) {
System.out.println(" MemberJpaController listMember start . . . ");
List<Member> memberList = memJpaService.getListAllMember();
model.addAttribute("members", memberList);
return "memberJpa/memberList" ;
}
}
<title>Mybatis JPA 회원 등록</title>
</head>
<%
String context = request.getContextPath();
%>
<body>
<h1>Mybatis JPA 회원 등록</h1>
<div class="container">
<form action="<%=context%>/memberJpa/save" method="post">
ID : <input type="text" id="id" name="id" required="required"><p>
이름 : <input type="text" id="name" name="name" placeholder="이름을 입력하세요">
<button type="submit">등록</button>
</form>
</div> <!-- /container -->
</body>
//회원정보수정화면
@GetMapping(value = "/memberJpa/memberUpdateForm")
public String memberUpdateForm(Long id, Model model) {
// TODO Auto-generated method stub
Member member = null;
String rtnJsp = "";
//목적 : 객체가 null check 용이
//아마도 맴버가 존재할수도 있고 안할수도있다
Optional<Member> maybeMember = memJpaService.findById(id);
if(maybeMember.isPresent()) { //존재한다면 여기로 보냄
System.out.println(" MemberJpaController memberUpdateFor maybeMember Is not null ");
member = maybeMember.get();
model.addAttribute("member", member);
rtnJsp = "memberJpa/memberModify";
}else {
model.addAttribute("message", "member가 존재하지 않으니 입력부터 수행해주세요 ");
rtnJsp = "forward:/members";
}
return rtnJsp;
}
//회원정보수정
@GetMapping(value ="/memberJpa/memberUpdate" )
public String memberUpdate(Member member , Model model) {
System.out.println("MemberController memberUpdate id-> "+member.getId());
System.out.println("MemberController memberUpdate member.getName-> "+member.getName());
memJpaService.memberUpdate(member);
return "redirect:/members";
}
}
//회원수정화면
public Optional<Member> findById(Long memberId) {
System.out.println("MemberJpaService findById start . . . ");
Optional<Member> member = memberJpaRepository.findById(memberId);
return member;
}
//회원수정
public void memberUpdate(Member member) {
System.out.println("memberUpdate member.getId()->" +member.getId() );
memberJpaRepository.updateByMember(member);
return;
}
Optional<Member> findById(Long memberId);
void updateByMember(Member member);
1.영속성 관리 x ---> setter 저장불가
2.merge(실무 거의 x) -->현재 setting 된것만 수정, 나머지는null
@Override
public Optional<Member> findById(Long memberId) {
Member member = em.find(Member.class, memberId);
// TODO Auto-generated method stubmemberId
return Optional.ofNullable(member); //널도 가능함
}
@Override
public void updateByMember(Member member) {
em.merge(member);
return;
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../header.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<%
String context = request.getContextPath();
%>
<body>
<h2>회원정보(JPA) 수정</h2>
<form action="<%=context%>/memberJpa/memberUpdate" method="get">
<input type="hidden" name="id" value="${member.id }">
<table>
<tr><th>회원번호</th><td>${member.id }</td></tr>
<tr><th>이름</th><td>
<input type="text" name="name"
required="required" value="${member.name }" ></td></tr>
<tr><td colspan="2">
<input type="submit" value="확인">
</td>
</tr>
</table>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="../header.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>JPA 직원(member) 목록</h2><a href="memberJpa/new">입력</a>
<c:set var="num" value="1"></c:set>
<table>
<tr><th >번호</th><th>사번</th><th>이름</th></tr>
<c:forEach var="member" items="${members }">
<tr><td>${num }</td><td>${member.id }</td>
<td><a href="memberJpa/memberUpdateForm?id=${member.id}">${member.name}</a></td>
<c:set var="num" value="${num + 1 }"></c:set>
</c:forEach>
</table>
</body>
</html>
index.xml
<a href="/ajaxForm">Ajax Form Test</a><p>
ajaxForm.jsp
<H1>다양한 Ajax test </H1>
<a href="/helloText">helloText</a><p>
<a href="/sample/sendVO2">sample/sendVO2</a><p>
<a href="/sendVO3?deptno=123">sendVO3</a><p>
@Data
public class SampleVO {
private Integer mno;
private String firstName;
private String lastName;
}
//ajaxForm Test 입력화면
@RequestMapping(value = "/ajaxForm")
public String ajaxForm(Model model) {
System.out.println("/ajaxForm start . . ");
return "ajaxForm";
}
package com.oracle.oBootMybatis01.controller;
import java.util.List;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.oracle.oBootMybatis01.model.Dept;
import com.oracle.oBootMybatis01.model.SampleVO;
import com.oracle.oBootMybatis01.service.EmpService;
import lombok.RequiredArgsConstructor;
//@Controller + @ResponseBody
@RestController
@RequiredArgsConstructor
public class EmpRestController {
private final EmpService es;
//바로 텍스트 조회
@RequestMapping("/helloText")
public String helloText() {
System.out.println("EmpRestController helloText start. . .");
String hello ="안녕";
return hello;
}
//직원번호를 가져와서 조회
// http://jsonviewer.stack.hu/
@RequestMapping("/sample/sendVO2")
public SampleVO sendVo2(int deptno) {
System.out.println("@RestController deptno->"+deptno);
SampleVO vo = new SampleVO();
vo.setFirstName("길동");
vo.setLastName("홍");
vo.setMno(deptno);
return vo;
}
//회원목록조회
@RequestMapping("/sendVO3")
public List<Dept> sendVO03(){
System.out.println(" @RestController sendVO03 START . . .");
List<Dept> deptList = es.deptSelect();
return deptList;
}
}
JSONVue
🔽3가지 완
🔽 restController 안가고 바로 controller에서 호출
a href="/getDeptName?deptno=456">getDeptName(Controller) /a
@ResponseBody //이거 달아주면 restController와 똑같이 반응함
@RequestMapping(value = "/getDeptName")
public String getDeptName(String deptno, Model model) {
System.out.println("deptno->"+deptno);
return deptno;
}
a href="/listEmpAjaxForm">/listEmpAjaxForm(aJax Jsp 연동)</a
@ResponseBody //이거 달아주면 restController와 똑같이 반응함
@RequestMapping(value = "/getDeptName")
public String getDeptName(int deptno, Model model) {
System.out.println("deptno->"+deptno);
String deptName = es.deptName(deptno);
System.out.println("deptName->"+deptName);
return deptName;
}
//Ajax List Test
@RequestMapping(value = "/listEmpAjaxForm")
public String listEmpAjaxForm(Model model) {
//parameter emp --> 페이지만 추가 (setting)
Emp emp = new Emp();
emp.setStart(1); //시작시 1
emp.setEnd(10); //시작시 10
System.out.println(" Ajax List Test ");
List<Emp> listEmp = es.listEmp(emp);
System.out.println("listEmpAjaxForm listEmp.size()-> "+ listEmp.size());
model.addAttribute("result","kkk");
model.addAttribute( "listEmp" , listEmp);
return "listEmpAjaxForm" ;
}
}
```java
String deptName(String deptno);
```
@Override
public String deptName(String deptno) {
System.out.println("EmpServiceImpl deptName Start" );
return ed.deptName(deptno);
}
String deptName(int deptno);
@Override
public String deptName(int deptno) {
System.out.println("EmpDaoImpl deptName start. . . ");
String resultStr = "";
try {
resultStr = session.selectOne("tkDeptName", deptno);
System.out.println("EmpDaoImpl deptName resultStr-> "+resultStr);
} catch (Exception e) {
System.out.println("EmpDaoImpl deptName Exception-> "+e.getMessage());
}
return resultStr;
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="header.jsp" %>
<!DOCTYPE html>
<%
String context = request.getContextPath();
%>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function getDeptName(vDeptno) {
console.log(vDeptno);
// alert("vDeptno->"+vDeptno);
// 행동강령: Ajax로 부서번호 보내고 부서명 받음
$.ajax(
{
url:"<%=context%>/getDeptName",
data:{deptno : vDeptno},
dataType:'text',
success:function(data){
alert("success ajax Data -> "+data);
$('#deptName').val(data); /* input Tag */
$('#msg').html(data); /* span id Tag */
}
}
);
}
</script>
</head>
<body>
<h2>회원 정보</h2>
<table>
<tr><th>사번</th><th>이름</th><th>업무</th><th>부서</th><th>근무지</th></tr>
<c:forEach var="emp" items="${listEmp}">
<tr><td>${emp.empno }</td><td>${emp.ename }</td>
<td>${emp.job }</td>
<td>${emp.deptno} <!-- 마우스를가져다되면 사번이 계속나온다 -->
<input type="button" id="btn_idCheck" value="부서명" onmouseover="getDeptName(${emp.deptno })">
</td>
<td>${empDept.loc }</td>
</tr>
</c:forEach>
</table>
deptName: <input type="text" id="deptName" readonly="readonly"><p>
Message : <span id="msg"></span><p>
</body>
</html>