파일업로드 &
-파일업로드하기
BoardVO
package com.example.domain;
import java.util.Arrays;
import java.util.Date;
public class BoardVO {
private int bno;
private String title;
private String content;
private Date regdate;
private int viewcnt;
private int replycnt;
private String[] files;
public int getBno() {
return bno;
}
public void setBno(int bno) {
this.bno = bno;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getRegdate() {
return regdate;
}
public void setRegdate(Date regdate) {
this.regdate = regdate;
}
public int getViewcnt() {
return viewcnt;
}
public void setViewcnt(int viewcnt) {
this.viewcnt = viewcnt;
}
public int getReplycnt() {
return replycnt;
}
public void setReplycnt(int replycnt) {
this.replycnt = replycnt;
}
public String[] getFiles() {
return files;
}
public void setFiles(String[] files) {
this.files = files;
}
@Override
public String toString() {
return "BoardVO [bno=" + bno + ", title=" + title + ", content=" + content + ", regdate=" + regdate
+ ", viewcnt=" + viewcnt + ", replycnt=" + replycnt + ", files=" + Arrays.toString(files) + "]";
}
}
BoardDAO
package com.example.persistence;
import java.util.List;
import com.example.domain.BoardVO;
public interface BoardDAO {
public List<BoardVO> list()throws Exception;
public BoardVO read(int bno)throws Exception;
public void update(BoardVO vo)throws Exception;
public void delete(int bno) throws Exception;
public void deleteAttach(int bno) throws Exception;
public void insertAttach(int bno,String fileName) throws Exception;
public List<String> getAttach(int bno)throws Exception;//첨부파일 읽기
}
BoardMapper
<?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="BoardMapper">
<select id="list" resultType="com.example.domain.BoardVO">
select * from tbl_board
order by bno desc
limit 0,10
</select>
<select id="read" resultType="com.example.domain.BoardVO">
select * from tbl_board
where bno=#{bno}
</select>
<update id="update">
update tbl_board set title=#{title},content=#{content}
where bno=#{bno}
</update>
<delete id="delete">
delete from tbl_board
where bno=#{bno}
</delete>
<delete id="deleteAttach">
delete from tbl_attach
where bno=#{bno}
</delete>
<insert id="insertAttach">
insert into tbl_attach(bno,fileName)
values(#{bno},#{fileName})
</insert>
<select id="getAttach" resultType="string">
select fileName from tbl_attach
where bno=#{bno}
</select>
</mapper>
BoardDAOImpl
package com.example.persistence;
import java.util.HashMap;
import java.util.List;
import javax.inject.Inject;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
import com.example.domain.BoardVO;
@Repository
public class BoardDAOImpl implements BoardDAO{
@Inject
SqlSession session;
String namespace="BoardMapper";
@Override
public List<BoardVO> list() throws Exception {
// TODO Auto-generated method stub
return session.selectList(namespace+".list");
}
@Override
public BoardVO read(int bno) throws Exception {
// TODO Auto-generated method stub
return session.selectOne(namespace+".read",bno);
}
@Override
public void update(BoardVO vo) throws Exception {
// TODO Auto-generated method stub
session.update(namespace +".update",vo);
}
@Override
public void delete(int bno) throws Exception {
// TODO Auto-generated method stub
session.delete(namespace+".delete",bno);
}
@Override
public void insertAttach(int bno, String fileName) throws Exception {
// TODO Auto-generated method stub
HashMap<String,Object> map=new HashMap<String,Object>();
map.put("bno",bno);
map.put("fileName",fileName);
session.insert(namespace+".insertAttach",map);
}
@Override
public void deleteAttach(int bno) throws Exception {
// TODO Auto-generated method stub
session.delete(namespace +".deleteAttach",bno);
}
@Override
public List<String> getAttach(int bno) throws Exception {
// TODO Auto-generated method stub
return session.selectList(namespace +".getAttach",bno);
}
}
BoardController
package com.example.web;
import java.util.List;
import javax.inject.Inject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.domain.BoardVO;
import com.example.persistence.BoardDAO;
import com.example.service.BoardService;
@Controller
public class BoardController {
@Inject
BoardDAO dao;
@Inject
BoardService service;
@RequestMapping
public String list(Model model)throws Exception{
model.addAttribute("list",dao.list());
return "list";
}
@RequestMapping("read")
public String read(Model model,int bno)throws Exception{
model.addAttribute("vo",dao.read(bno));
return "read";
}
@RequestMapping("update")
public String update(BoardVO vo)throws Exception{
System.out.println(vo.toString());
service.update(vo);
return "redirect:list"; //redirect를 안하면 list.jsp로 간다.
}
@RequestMapping(value="delete",method=RequestMethod.POST)
public String delete(BoardVO vo)throws Exception{
dao.delete(vo.getBno());
return "redirect:list"; //redirect를 안하면 list.jsp로 간다.
}
@ResponseBody
@RequestMapping("getAttach")
public List<String> getAttach(int bno)throws Exception{
return dao.getAttach(bno);
}
}
FileController
package com.example.web;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.UUID;
import javax.annotation.Resource;
import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController {
@Resource(name="uploadPath")
private String uploadPath;
//ajax으로 업로드
@ResponseBody
@RequestMapping(value="upload",method=RequestMethod.POST,produces="text/plain;charset=UTF-8")
public String upload(MultipartFile file)throws Exception{
UUID uid=UUID.randomUUID();
String savedName=uid.toString() +"_"+file.getOriginalFilename();
File target=new File(uploadPath,savedName);
FileCopyUtils.copy(file.getBytes(), target);
return savedName;
}
//이미지파일 출력
@ResponseBody
@RequestMapping("/display")
public byte[] display(String fileName)throws Exception{
InputStream in=new FileInputStream(uploadPath + "/" + fileName);
byte[] image=IOUtils.toByteArray(in);
in.close();
return image;
}
//jsp에서 파일 선택에서 출력된 이미지와 파일이름을 삭제한다.
@ResponseBody
@RequestMapping("/delete")
public void deleteFile(String fileName) throws Exception{
new File(uploadPath +"/" +fileName).delete();
}
//다운로드
@ResponseBody
@RequestMapping(value="downloadFile")
public ResponseEntity<byte[]> downloadFile(String fileName)throws Exception{
System.out.println("파일이름:" + fileName);
ResponseEntity<byte[]> entity=null;
InputStream in = null;
try{
HttpHeaders headers = new HttpHeaders();
in= new FileInputStream(uploadPath + "/" + fileName);
fileName = fileName.substring(fileName.indexOf("_") + 1);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.add("Content-Disposition", "attachment;filename=\"" +
new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + "\"");
entity = new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
}catch(Exception e){
System.out.println(e.toString());
entity= new ResponseEntity<byte[]>(HttpStatus.BAD_REQUEST);
}finally{
in.close();
}
return entity;
}
}
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>게시판 목록</h1>
<div>
<c:if test="${uid == null}">
<button onClick="location.href='login'">로그인</button>
</c:if>
<c:if test="${uid != null}">
아이디:${uid}
<button onClick="location.href='logout'">로그아웃</button>
</c:if>
</div>
<c:forEach items="${list}" var="vo">
<div>
<a href="read?bno=${vo.bno}">${vo.title}</a>
[<fmt:formatDate value="${vo.regdate}" pattern="yyyy-MM-dd"/>]
</div>
</c:forEach>
</body>
</html>
read.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.js"></script>
</head>
<body>
<h1>게시글 읽기</h1>
<form name="frm" action="update" method="post">
<input type="hidden" name="bno" value="${vo.bno}">
<div>제목:<input type="text" name="title" value="${vo.title}"></div>
<div>
내용:
<textarea rows="5" cols="80" name="content">${vo.content}</textarea>
</div>
<div>
<input type="submit" value="수정">
<input type="reset" value="취소">
<input type="button" onClick="location.href='list'" value="목록">
<input type="button" value="삭제" id="btndel">
</div>
<!--파이을 입력받겠다.-->
<div style="border:1px solid;">
<input type="file" id="file" accept=images/*>
</div>
<!-- 실제로 업로든 된 파일 목록 출력 -->
<div style="width:500px;border:1px solid;">
<ul id="uploaded"></ul>
<script id="temp" type="text/x-handlebars-template">
<li>
<a href="downloadFile?fileName={{fullName}}">
<img src="display?fileName={{fullName}}" width=50>
</a>
{{fileName}}
<a href="{{fullName}}" class="del">X</a>
<input type="hidden" name="files" value="{{fullName}}" size="5">
</li>
</script>
</div>
</form>
</body>
<script>
var bno="${vo.bno}";
getAttach();
function getAttach(){
$.ajax({
type:"get",
url:"getAttach",
data:{"bno":bno},
success:function(data){
//alert(data);
var temp=Handlebars.compile($("#temp").html());
$(data).each(function(){
var idx=this.indexOf("_")+1;
var fileName=this.substring(idx);
var tempData={"fullName":this,"fileName":fileName};
$("#uploaded").append(temp(tempData));
});
}
});
}
$("#uploaded").on("click","li .del",function(e){
e.preventDefault();
var fileName=$(this).attr("href");
//alert(fileName);
var li=$(this).parent();
$.ajax({
type:"post",
url:"deleteFile",
data:{"fileName":fileName},
success:function(){
li.remove();
}
});
});
//파일 선택하면 밑에 div에 이름과 이미지가 출력된다.
$("#file").on("change",function(){
var file=$("#file")[0].files[0];
//alert(file.name);
if(file==null) return;
var formData=new FormData();
formData.append("file",file);
$.ajax({
type:"post",
url:"upload",
data:formData,
processData:false,
contentType:false,
success:function(data){
//alert(data);
var temp=Handlebars.compile($("#temp").html());
var tempData={"fullName":data,"fileName":file.name};
$("#uploaded").append(temp(tempData));
}
});
});
$("#btndel").on("click",function(){
frm.action="delete";
frm.submit();
});
</script>
</html>
트랜젝션 &
-파일 수정하기
BoardService
package com.example.service;
import com.example.domain.BoardVO;
public interface BoardService {
public void update(BoardVO vo)throws Exception;
}
BoardServiceImpl
package com.example.service;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.domain.BoardVO;
import com.example.persistence.BoardDAO;
@Service
public class BoardServiceImpl implements BoardService{
@Inject
BoardDAO dao;
@Transactional
@Override
public void update(BoardVO vo) throws Exception {
// TODO Auto-generated method stub
dao.update(vo); //보드내용 업데이트
int bno=vo.getBno();//삭제할것
dao.deleteAttach(bno);
//인설트
//값 가져요기
String[] files=vo.getFiles();
if(files == null) {return;}
for(String fileName:files){
dao.insertAttach(bno, fileName);
}
}
}
로그인
-로그인하면 아이디가 노출되고 로그아웃하면 아이디 정보를 지워줌
UserVO
package com.example.domain;
public class UserVO {
private String uid;
private String upw;
private String uname;
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getUpw() {
return upw;
}
public void setUpw(String upw) {
this.upw = upw;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
@Override
public String toString() {
return "UserVO [uid=" + uid + ", upw=" + upw + ", uname=" + uname + "]";
}
}
UserDAO
package com.example.persistence;
import com.example.domain.UserVO;
public interface UserDAO {
public UserVO login(UserVO vo)throws Exception;
}
UserMapper
<?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="UserMapper">
<select id="login" resultType="com.example.domain.UserVO">
select * from tbl_user
where uid=#{uid} and upw=#{upw}
</select>
</mapper>
UserDAOImpl
package com.example.persistence;
import javax.inject.Inject;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Repository;
import com.example.domain.UserVO;
@Repository
public class UserDAOImpl implements UserDAO{
@Inject
SqlSession session;
String namespace="UserMapper";
@Override
public UserVO login(UserVO vo) throws Exception {
// TODO Auto-generated method stub
return session.selectOne(namespace+".login",vo);
}
}
UserController
package com.example.web;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.domain.UserVO;
import com.example.persistence.UserDAO;
@Controller
public class UserController {
@Inject
UserDAO dao;
@RequestMapping("login")
public String login(UserVO vo) throws Exception{
return "login";
}
@RequestMapping("logout")
public String logout(HttpServletRequest request) throws Exception{
//session에 저장된 정보를 삭제합니다.
HttpSession session=request.getSession();
session.removeAttribute("uid");
return "redirect:list";
}
@RequestMapping("loginPost")
public String loginPost(UserVO vo,Model model) throws Exception{
System.out.println("2.Controller에 loginPost으로 옵니다.");
model.addAttribute("user",dao.login(vo));
return "loginPost";
}
}
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>로그읺ㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎ</h1>
<form name="frm" action="loginPost" method="post">
<table border=1 width=300>
<tr>
<td colspan=2><h1>[로그인]</h1></td>
</tr>
<tr>
<td>ID</td>
<td><input type="text" name="uid"></td>
</tr>
<tr>
<td>PW</td>
<td><input type="text" name="upw"></td>
</tr>
<tr>
<td colspan=2><input type="submit" value="LOGIN"></td>
</tr>
</table>
</form>
</body>
</html>
loginPost.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>로그인한 후 ㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎㅎ</title>
<script>
location.href="list";
</script>
</head>
<body>
</body>
</html>
LoginInterceptor
package com.example.domain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
//Intercepter : 가로채기
//로그인하기 전에 가로채기
public class LoginInterceptor extends HandlerInterceptorAdapter{
@Override//재정의
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// TODO Auto-generated method stub
System.out.println("1.Logininterceptor pre로 옵니다.");
//session에 있는 내용을 지워요
//login 중인 경우
HttpSession session=request.getSession();
if(session.getAttribute("uid") != null ){
session.removeAttribute("uid");
}
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
System.out.println("3.loginInterceptor에 post로 옵니다.");
//controller에 login post에 user를 가져옴!
UserVO user=(UserVO)modelAndView.getModel().get("user");
//로그인 성공
HttpSession session=request.getSession();
if(user != null){
//session에 값을 넣어줌
session.setAttribute("uid", user.getUid());
//LOCATION.HREF랑 같은데 그거는 SCRIPT에서 사용하고 여거는 SERVLET에서 사용
response.sendRedirect("list");
}
super.postHandle(request, response, handler, modelAndView);
}
//INTERCETPOR를 SERVLET-CONTEXT에서 정의
}
servlet-context.xml
<!-- INTERCEPTOR를 정의 -->
<beans:bean id="loginInterceptor" class="com.example.domain.LoginInterceptor"></beans:bean>
<interceptors>
<interceptor>
<mapping path="/loginPost"/>
<beans:ref bean="loginInterceptor"/>
</interceptor>
</interceptors>
'spring' 카테고리의 다른 글
클로링 과 셀레니움 (0) | 2019.12.24 |
---|---|
네이버 여행 카테코리에 한 부분 셀레니움하기 (0) | 2019.12.19 |
파일 업로드 라이브러리 임포트 (0) | 2019.12.06 |
Controller Tip (0) | 2019.12.06 |
프로필 사진 수정하기 (0) | 2019.12.06 |