반응형
package org.doit.ik.controller;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.doit.ik.domain.MemberVO;
import org.doit.ik.domain.NoticeVO;
import org.doit.ik.mapper.MemberMapper;
import org.doit.ik.mapper.NoticeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
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 org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j;
@Controller
@RequestMapping("/common/*")
@Log4j
public class CommonController {
// /common/accessError.htm
@GetMapping("/accessError.htm")
public String accessDenied(Model model, Authentication auth) throws Exception{
log.info("> /common/accessError.htm... GET");
model.addAttribute("msg", "Access Denied");
return "/common/accessError";
}
} // class
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.doit.ik.domain.MemberVO;
import org.doit.ik.domain.NoticeVO;
import org.doit.ik.mapper.MemberMapper;
import org.doit.ik.mapper.NoticeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
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 org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j;
@Controller
@RequestMapping("/common/*")
@Log4j
public class CommonController {
// /common/accessError.htm
@GetMapping("/accessError.htm")
public String accessDenied(Model model, Authentication auth) throws Exception{
log.info("> /common/accessError.htm... GET");
model.addAttribute("msg", "Access Denied");
return "/common/accessError";
}
} // class
package org.doit.ik.controller;
import java.io.File;
import java.io.FileInputStream;
import java.security.Principal;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.doit.ik.domain.NoticeVO;
import org.doit.ik.mapper.NoticeMapper;
import org.doit.ik.service.MemberShipService;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
@Controller
@RequestMapping("/customer/*")
public class CustomerController {
@Autowired
private NoticeMapper noticeDao ;
@Autowired
private MemberShipService memberShipService ;
// ?dir=customer/upload&file=${ notice.filesrc }
@RequestMapping( "/customer/download.htm")
public void download(
@RequestParam("dir") String d
, @RequestParam("file") String fname
, HttpServletResponse response
, HttpServletRequest request
) throws Exception{
response.setHeader("Content-Disposition","attachment;filename="+ new String(fname.getBytes(), "ISO8859_1"));
String fullPath = request.getServletContext().getRealPath( d + "/" + fname);
FileInputStream fin = new FileInputStream(fullPath);
ServletOutputStream sout = response.getOutputStream();
byte[] buf = new byte[1024];
int size = 0;
while((size = fin.read(buf, 0, 1024)) != -1) {
sout.write(buf, 0, size);
}
fin.close();
sout.close();
}
// ?seq=1&filesrc=ojdbc6.jar
@GetMapping("/noticeDel.htm")
public String noticeDel(@RequestParam("seq") String seq
,@RequestParam("filesrc") String delFilesrc
, HttpServletRequest request) throws Exception {
// 1. 실제 업로드 경로에서 파일을 삭제
String uploadRealPath = request.getServletContext().getRealPath("/customer/upload");
File delFile = new File(uploadRealPath, delFilesrc);
if( delFile.exists() ) delFile.delete();
// 2. 테이블 레코드 삭제
int deleteCount = this.noticeDao.delete(seq);
if (deleteCount == 1) {
return "redirect:notice.htm";
} else {
return "redirect:noticeDetail.htm?seq="+ seq+"&error";
} // if
}
// Post 방식 요청 + ("/customer/noticeEdit.htm")
@RequestMapping(value = {"/customer/noticeEdit.htm"}, method = RequestMethod.POST)
public String noticeEdit(
NoticeVO notice
, @RequestParam("o_filesrc") String oFilesrc
, HttpServletRequest request
) throws Exception{
CommonsMultipartFile multiparftFile = notice.getFile();
String uploadRealPath = null;
if( !multiparftFile.isEmpty() ) {
uploadRealPath = request.getServletContext().getRealPath("/customer/upload");
File delFile = new File(uploadRealPath, oFilesrc);
if( delFile.exists()) {
delFile.delete();
}
String originalFilename = multiparftFile.getOriginalFilename();
String filesystemName = getFileNameCheck(uploadRealPath, originalFilename) ;
File dest = new File(uploadRealPath, filesystemName );
multiparftFile.transferTo(dest) ;
notice.setFilesrc(filesystemName);
} else {
notice.setFilesrc(oFilesrc);
} //
int rowCount = this.noticeDao.update(notice);
if ( rowCount == 1 ) {
return String.format( "redirect:noticeDetail.htm?seq=%s" , notice.getSeq() ) ;
} else {
return "redirect:notice.htm";
}
}
/*
@PostMapping("/noticeEdit.htm")
public String noticeEdit(
NoticeVO notice
) throws Exception {
int updateCount = this.noticeDao.update(notice);
if (updateCount == 1) {
return "redirect:noticeDetail.htm?seq=" + notice.getSeq();
} else {
return "redirect:notice.htm";
} // if
}
*/
// ?seq=1
@GetMapping("/noticeEdit.htm")
public String noticeEdit(
@RequestParam("seq") String seq
, Model model ) throws Exception {
NoticeVO notice = this.noticeDao.getNotice(seq);
model.addAttribute("notice", notice);
return "customer.noticeEdit";
}
// a_3.txt
private String getFileNameCheck(String uploadRealPath, String originalFilename) {
int index = 1;
while( true ) {
File f = new File(uploadRealPath, originalFilename);
if( !f.exists() ) return originalFilename;
// upload 폴더에 originalFilename 파일이 존재한다는 의미 a.txt (4자리)
String fileName = originalFilename.substring(0, originalFilename.length() - 4 ); // a
String ext = originalFilename.substring(originalFilename.length() - 4 ); // .txt
// asdfasf-3.txt
originalFilename = fileName+"-"+(index)+ext;
index++;
} // while
}
// p358 컨트롤러 메서드 파마라미터 ( 커맨드 객체 사용 예 )
//@RequestMapping(value = "/noticeReg.htm", method = RequestMethod.POST)
@PostMapping("/noticeReg.htm")
public String noticeReg(
NoticeVO notice
, HttpServletRequest request
, Principal principal
) throws Exception{
// 1. 첨부된 파일 유무 확인 후에 서버 파일 저장.
CommonsMultipartFile multiparftFile = notice.getFile();
// isEmpty() 첨부파일 유무
// 서버에 배포했을 때의 실제 경로
String uploadRealPath = null;
if( !multiparftFile.isEmpty() ) { // 첨부 파일 있는 경우.
// 2. 첨부 파일 저장
// uploadRealPath = request.getRealPath("/customer/upload");
uploadRealPath = request.getServletContext().getRealPath("/customer/upload");
// File saveDir = new File(uploadRealPath);
// if (!saveDir.exists()) saveDir.mkdirs();
System.out.println("> uploadRealPath : " + uploadRealPath);
// originalFilename, filesystemName
String originalFilename = multiparftFile.getOriginalFilename();
// a.txt
// a_1.txt
// a_2.txt
String filesystemName = getFileNameCheck(uploadRealPath, originalFilename) ;
File dest = new File(uploadRealPath, filesystemName );
multiparftFile.transferTo(dest); // 실제 파일 저장
// 3. notice.filesrc
// 테이블 : 원래파일이름, -1 시스템저장파일이름(O) 컬럼 생성
notice.setFilesrc(filesystemName);
} // if
// notice.setWriter("kenik");
// 로그인 인증 - 세션
notice.setWriter( principal.getName() ); // userName == id
int insertCount = this.noticeDao.insert(notice);
// this.noticeDao.insertAndPointUpOfMember(notice, "kenik");
// this.memberShipService.insertAndPointUpOfMember(notice, "kenik");
// int insertCount = 1;
if ( insertCount == 1 ) {
// redirect: == response.sendRedirect()
return "redirect:notice.htm";
} else {
return "noticeReg.jsp?error";
}
}
// notice.jsp 에서 링크태그 [글쓰기] 버튼을 클릭
//@RequestMapping(value = "/noticeReg.htm", method = RequestMethod.GET)
@GetMapping("/noticeReg.htm")
public String noticeReg() throws Exception{
return "customer.noticeReg";
}
// ?seq=10
@GetMapping("/noticeDetail.htm")
public String noticeDetail(
@RequestParam("seq") String seq
, Model model
) throws Exception {
// 조회수 1증가
this.noticeDao.hitUp(seq);
NoticeVO notice = this.noticeDao.getNotice(seq);
model.addAttribute("notice", notice);
return "customer.noticeDetail"; // *.*
}
// ?page=2&field=title&query=홍길동
@GetMapping("/notice.htm")
public String notices(
@RequestParam( value = "page" , defaultValue = "1" ) int page
, @RequestParam( value = "field" , defaultValue = "title" ) String field
, @RequestParam( value = "query" , defaultValue = "" ) String query
, Model model) throws Exception {
model.addAttribute("message", "hello world");
List<NoticeVO> list = this.noticeDao.getNotices(page, field, query);
model.addAttribute("list", list);
return "customer.notice";
}
/*
// p 356
// "컨트롤러 메서드"
//@RequestMapping(value = {"/customer/notice.htm"})
// @RequestMapping("/customer/notice.htm")
@GetMapping("/customer/notice.htm")
public ModelAndView notices(
HttpServletRequest request
, HttpServletResponse response
, Model model
, HttpSession sesion) throws Exception {
ModelAndView mav = new ModelAndView();
mav.addObject("message", "hello world");
// ?page=2&field=title&query=홍길동
String ppage = request.getParameter("page");
String pfield = request.getParameter("field");
String pquery = request.getParameter("query");
int page= 1;
String field = "title";
String query = "";
if( ppage != null && !ppage.equals("") ) { page = Integer.parseInt(ppage); }
if( pfield != null && !pfield.equals("") ) { field = pfield; }
if( pquery != null && !pquery.equals("") ) { query = pquery; }
List<NoticeVO> list = this.noticeDao.getNotices(page, field, query);
mav.addObject("list", list);
mav.setViewName("notice.jsp");
return mav;
}
*/
} // class
import java.io.File;
import java.io.FileInputStream;
import java.security.Principal;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.doit.ik.domain.NoticeVO;
import org.doit.ik.mapper.NoticeMapper;
import org.doit.ik.service.MemberShipService;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
@Controller
@RequestMapping("/customer/*")
public class CustomerController {
@Autowired
private NoticeMapper noticeDao ;
@Autowired
private MemberShipService memberShipService ;
// ?dir=customer/upload&file=${ notice.filesrc }
@RequestMapping( "/customer/download.htm")
public void download(
@RequestParam("dir") String d
, @RequestParam("file") String fname
, HttpServletResponse response
, HttpServletRequest request
) throws Exception{
response.setHeader("Content-Disposition","attachment;filename="+ new String(fname.getBytes(), "ISO8859_1"));
String fullPath = request.getServletContext().getRealPath( d + "/" + fname);
FileInputStream fin = new FileInputStream(fullPath);
ServletOutputStream sout = response.getOutputStream();
byte[] buf = new byte[1024];
int size = 0;
while((size = fin.read(buf, 0, 1024)) != -1) {
sout.write(buf, 0, size);
}
fin.close();
sout.close();
}
// ?seq=1&filesrc=ojdbc6.jar
@GetMapping("/noticeDel.htm")
public String noticeDel(@RequestParam("seq") String seq
,@RequestParam("filesrc") String delFilesrc
, HttpServletRequest request) throws Exception {
// 1. 실제 업로드 경로에서 파일을 삭제
String uploadRealPath = request.getServletContext().getRealPath("/customer/upload");
File delFile = new File(uploadRealPath, delFilesrc);
if( delFile.exists() ) delFile.delete();
// 2. 테이블 레코드 삭제
int deleteCount = this.noticeDao.delete(seq);
if (deleteCount == 1) {
return "redirect:notice.htm";
} else {
return "redirect:noticeDetail.htm?seq="+ seq+"&error";
} // if
}
// Post 방식 요청 + ("/customer/noticeEdit.htm")
@RequestMapping(value = {"/customer/noticeEdit.htm"}, method = RequestMethod.POST)
public String noticeEdit(
NoticeVO notice
, @RequestParam("o_filesrc") String oFilesrc
, HttpServletRequest request
) throws Exception{
CommonsMultipartFile multiparftFile = notice.getFile();
String uploadRealPath = null;
if( !multiparftFile.isEmpty() ) {
uploadRealPath = request.getServletContext().getRealPath("/customer/upload");
File delFile = new File(uploadRealPath, oFilesrc);
if( delFile.exists()) {
delFile.delete();
}
String originalFilename = multiparftFile.getOriginalFilename();
String filesystemName = getFileNameCheck(uploadRealPath, originalFilename) ;
File dest = new File(uploadRealPath, filesystemName );
multiparftFile.transferTo(dest) ;
notice.setFilesrc(filesystemName);
} else {
notice.setFilesrc(oFilesrc);
} //
int rowCount = this.noticeDao.update(notice);
if ( rowCount == 1 ) {
return String.format( "redirect:noticeDetail.htm?seq=%s" , notice.getSeq() ) ;
} else {
return "redirect:notice.htm";
}
}
/*
@PostMapping("/noticeEdit.htm")
public String noticeEdit(
NoticeVO notice
) throws Exception {
int updateCount = this.noticeDao.update(notice);
if (updateCount == 1) {
return "redirect:noticeDetail.htm?seq=" + notice.getSeq();
} else {
return "redirect:notice.htm";
} // if
}
*/
// ?seq=1
@GetMapping("/noticeEdit.htm")
public String noticeEdit(
@RequestParam("seq") String seq
, Model model ) throws Exception {
NoticeVO notice = this.noticeDao.getNotice(seq);
model.addAttribute("notice", notice);
return "customer.noticeEdit";
}
// a_3.txt
private String getFileNameCheck(String uploadRealPath, String originalFilename) {
int index = 1;
while( true ) {
File f = new File(uploadRealPath, originalFilename);
if( !f.exists() ) return originalFilename;
// upload 폴더에 originalFilename 파일이 존재한다는 의미 a.txt (4자리)
String fileName = originalFilename.substring(0, originalFilename.length() - 4 ); // a
String ext = originalFilename.substring(originalFilename.length() - 4 ); // .txt
// asdfasf-3.txt
originalFilename = fileName+"-"+(index)+ext;
index++;
} // while
}
// p358 컨트롤러 메서드 파마라미터 ( 커맨드 객체 사용 예 )
//@RequestMapping(value = "/noticeReg.htm", method = RequestMethod.POST)
@PostMapping("/noticeReg.htm")
public String noticeReg(
NoticeVO notice
, HttpServletRequest request
, Principal principal
) throws Exception{
// 1. 첨부된 파일 유무 확인 후에 서버 파일 저장.
CommonsMultipartFile multiparftFile = notice.getFile();
// isEmpty() 첨부파일 유무
// 서버에 배포했을 때의 실제 경로
String uploadRealPath = null;
if( !multiparftFile.isEmpty() ) { // 첨부 파일 있는 경우.
// 2. 첨부 파일 저장
// uploadRealPath = request.getRealPath("/customer/upload");
uploadRealPath = request.getServletContext().getRealPath("/customer/upload");
// File saveDir = new File(uploadRealPath);
// if (!saveDir.exists()) saveDir.mkdirs();
System.out.println("> uploadRealPath : " + uploadRealPath);
// originalFilename, filesystemName
String originalFilename = multiparftFile.getOriginalFilename();
// a.txt
// a_1.txt
// a_2.txt
String filesystemName = getFileNameCheck(uploadRealPath, originalFilename) ;
File dest = new File(uploadRealPath, filesystemName );
multiparftFile.transferTo(dest); // 실제 파일 저장
// 3. notice.filesrc
// 테이블 : 원래파일이름, -1 시스템저장파일이름(O) 컬럼 생성
notice.setFilesrc(filesystemName);
} // if
// notice.setWriter("kenik");
// 로그인 인증 - 세션
notice.setWriter( principal.getName() ); // userName == id
int insertCount = this.noticeDao.insert(notice);
// this.noticeDao.insertAndPointUpOfMember(notice, "kenik");
// this.memberShipService.insertAndPointUpOfMember(notice, "kenik");
// int insertCount = 1;
if ( insertCount == 1 ) {
// redirect: == response.sendRedirect()
return "redirect:notice.htm";
} else {
return "noticeReg.jsp?error";
}
}
// notice.jsp 에서 링크태그 [글쓰기] 버튼을 클릭
//@RequestMapping(value = "/noticeReg.htm", method = RequestMethod.GET)
@GetMapping("/noticeReg.htm")
public String noticeReg() throws Exception{
return "customer.noticeReg";
}
// ?seq=10
@GetMapping("/noticeDetail.htm")
public String noticeDetail(
@RequestParam("seq") String seq
, Model model
) throws Exception {
// 조회수 1증가
this.noticeDao.hitUp(seq);
NoticeVO notice = this.noticeDao.getNotice(seq);
model.addAttribute("notice", notice);
return "customer.noticeDetail"; // *.*
}
// ?page=2&field=title&query=홍길동
@GetMapping("/notice.htm")
public String notices(
@RequestParam( value = "page" , defaultValue = "1" ) int page
, @RequestParam( value = "field" , defaultValue = "title" ) String field
, @RequestParam( value = "query" , defaultValue = "" ) String query
, Model model) throws Exception {
model.addAttribute("message", "hello world");
List<NoticeVO> list = this.noticeDao.getNotices(page, field, query);
model.addAttribute("list", list);
return "customer.notice";
}
/*
// p 356
// "컨트롤러 메서드"
//@RequestMapping(value = {"/customer/notice.htm"})
// @RequestMapping("/customer/notice.htm")
@GetMapping("/customer/notice.htm")
public ModelAndView notices(
HttpServletRequest request
, HttpServletResponse response
, Model model
, HttpSession sesion) throws Exception {
ModelAndView mav = new ModelAndView();
mav.addObject("message", "hello world");
// ?page=2&field=title&query=홍길동
String ppage = request.getParameter("page");
String pfield = request.getParameter("field");
String pquery = request.getParameter("query");
int page= 1;
String field = "title";
String query = "";
if( ppage != null && !ppage.equals("") ) { page = Integer.parseInt(ppage); }
if( pfield != null && !pfield.equals("") ) { field = pfield; }
if( pquery != null && !pquery.equals("") ) { query = pquery; }
List<NoticeVO> list = this.noticeDao.getNotices(page, field, query);
mav.addObject("list", list);
mav.setViewName("notice.jsp");
return mav;
}
*/
} // class
package org.doit.ik.controller;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.doit.ik.domain.MemberVO;
import org.doit.ik.domain.NoticeVO;
import org.doit.ik.mapper.MemberMapper;
import org.doit.ik.mapper.NoticeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
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 org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Controller
@RequestMapping("/joinus/*")
@NoArgsConstructor
public class JoinController {
@Autowired
private MemberMapper memberDao;
@GetMapping("/login.htm")
public String login() throws Exception{
return "joinus.login"; // *.*
}
@GetMapping("/join.htm")
public String join() throws Exception{
return "joinus.join";
}
@Setter(onMethod=@__({@Autowired}))
private PasswordEncoder passwordEncoder;
// 문제) 회원가입 -> home 으로 이동
@PostMapping("/join.htm")
public String join( MemberVO member ) throws Exception{
String pwd = member.getPwd(); // 1234
member.setPwd( this.passwordEncoder.encode(pwd) );
this.memberDao.insert(member);
return "redirect:../index.htm";
}
/*
[1]
@RequestMapping( value= {"join.htm"}, method = RequestMethod.POST )
public String join( Member member , String year, String month, String day ) throws Exception{
String birth = String.format("%s-%s-%d", year, month, day);
member.setBirth(birth);
this.memberDao.insert(member);
return "redirect:../index.htm";
}
*/
} // class
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.doit.ik.domain.MemberVO;
import org.doit.ik.domain.NoticeVO;
import org.doit.ik.mapper.MemberMapper;
import org.doit.ik.mapper.NoticeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
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 org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Controller
@RequestMapping("/joinus/*")
@NoArgsConstructor
public class JoinController {
@Autowired
private MemberMapper memberDao;
@GetMapping("/login.htm")
public String login() throws Exception{
return "joinus.login"; // *.*
}
@GetMapping("/join.htm")
public String join() throws Exception{
return "joinus.join";
}
@Setter(onMethod=@__({@Autowired}))
private PasswordEncoder passwordEncoder;
// 문제) 회원가입 -> home 으로 이동
@PostMapping("/join.htm")
public String join( MemberVO member ) throws Exception{
String pwd = member.getPwd(); // 1234
member.setPwd( this.passwordEncoder.encode(pwd) );
this.memberDao.insert(member);
return "redirect:../index.htm";
}
/*
[1]
@RequestMapping( value= {"join.htm"}, method = RequestMethod.POST )
public String join( Member member , String year, String month, String day ) throws Exception{
String birth = String.format("%s-%s-%d", year, month, day);
member.setBirth(birth);
this.memberDao.insert(member);
return "redirect:../index.htm";
}
*/
} // class
//controller
package org.doit.ik.domain;
import lombok.Data;
@Data
public class AuthVO {
private String username;
private String authority;
}
import lombok.Data;
@Data
public class AuthVO {
private String username;
private String authority;
}
package org.doit.ik.domain;
import java.util.Date;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MemberVO {
// member 테이블의 컬럼과 이름을 일치.
// fields
private String id; // uid -> id 수정
private String pwd;
private String name;
private String gender;
private String birth;
private String is_lunar; // isLunar -> is_lunar 수정
private String cphone; // 수정
private String email;
private String habit;
private Date regdate; // 수정
// 트랜잭션 처리를 테스트 하기 위해 point 컬럼 추가. -> 필드, getter, setter
private int point;
// 필드 2개 추가
private boolean enabled;
private List<AuthVO> authList;
} // class
import java.util.Date;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MemberVO {
// member 테이블의 컬럼과 이름을 일치.
// fields
private String id; // uid -> id 수정
private String pwd;
private String name;
private String gender;
private String birth;
private String is_lunar; // isLunar -> is_lunar 수정
private String cphone; // 수정
private String email;
private String habit;
private Date regdate; // 수정
// 트랜잭션 처리를 테스트 하기 위해 point 컬럼 추가. -> 필드, getter, setter
private int point;
// 필드 2개 추가
private boolean enabled;
private List<AuthVO> authList;
} // class
package org.doit.ik.domain;
import java.util.Date;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class NoticeVO {
// fields
private String seq;
private String title;
private String writer;
private String content;
private Date regdate;
private int hit;
private String filesrc; // 수정
// p445 참고
// 스프링에서 지원하는 파일 업로드 기능을 (4)방법인 커맨드 객체를 이용하는 방법
// <input type="file" id="txtFile" name="file" />
private CommonsMultipartFile file;
} // clsss
import java.util.Date;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class NoticeVO {
// fields
private String seq;
private String title;
private String writer;
private String content;
private Date regdate;
private int hit;
private String filesrc; // 수정
// p445 참고
// 스프링에서 지원하는 파일 업로드 기능을 (4)방법인 커맨드 객체를 이용하는 방법
// <input type="file" id="txtFile" name="file" />
private CommonsMultipartFile file;
} // clsss
//domain
package org.doit.ik.mapper;
import java.sql.SQLException;
import org.doit.ik.domain.MemberVO;
public interface MemberMapper {
// 회원 정보 얻어오는 메서드
public MemberVO getMember(String id) throws ClassNotFoundException, SQLException;
// 회원 가입 메서드
public int insert(MemberVO member) throws ClassNotFoundException, SQLException;
// 회원 정보 + 권한정보(authList)들 얻어오는 메서드
public MemberVO read(String userid);
}
import java.sql.SQLException;
import org.doit.ik.domain.MemberVO;
public interface MemberMapper {
// 회원 정보 얻어오는 메서드
public MemberVO getMember(String id) throws ClassNotFoundException, SQLException;
// 회원 가입 메서드
public int insert(MemberVO member) throws ClassNotFoundException, SQLException;
// 회원 정보 + 권한정보(authList)들 얻어오는 메서드
public MemberVO read(String userid);
}
package org.doit.ik.mapper;
import java.sql.SQLException;
import java.util.List;
import org.doit.ik.domain.NoticeVO;
public interface NoticeMapper {
// 검색한 결과의 총레코드 수 를 반환하는 메서드
public int getCount(String field, String query) throws ClassNotFoundException, SQLException;
// 페이징 처리 + 공지사항 목록
public List<NoticeVO> getNotices(int page, String field, String query) throws ClassNotFoundException, SQLException;
// 공지사항 삭제
public int delete(String seq) throws ClassNotFoundException, SQLException;
// 공지사항 수정
public int update( NoticeVO notice ) throws ClassNotFoundException, SQLException;
// 해당 공지사항 상세보기.
public NoticeVO getNotice(String seq) throws ClassNotFoundException, SQLException;
// 공지사항 글쓰기
public int insert(NoticeVO notice) throws ClassNotFoundException, SQLException;
/*
// 트랜잭션 처리 하기 위한 메서드 추가
public void insertAndPointUpOfMember(NoticeVO notice, String id) throws ClassNotFoundException, SQLException;
*/
void hitUp(String seq);
int getHit(String seq);
} // class
import java.sql.SQLException;
import java.util.List;
import org.doit.ik.domain.NoticeVO;
public interface NoticeMapper {
// 검색한 결과의 총레코드 수 를 반환하는 메서드
public int getCount(String field, String query) throws ClassNotFoundException, SQLException;
// 페이징 처리 + 공지사항 목록
public List<NoticeVO> getNotices(int page, String field, String query) throws ClassNotFoundException, SQLException;
// 공지사항 삭제
public int delete(String seq) throws ClassNotFoundException, SQLException;
// 공지사항 수정
public int update( NoticeVO notice ) throws ClassNotFoundException, SQLException;
// 해당 공지사항 상세보기.
public NoticeVO getNotice(String seq) throws ClassNotFoundException, SQLException;
// 공지사항 글쓰기
public int insert(NoticeVO notice) throws ClassNotFoundException, SQLException;
/*
// 트랜잭션 처리 하기 위한 메서드 추가
public void insertAndPointUpOfMember(NoticeVO notice, String id) throws ClassNotFoundException, SQLException;
*/
void hitUp(String seq);
int getHit(String seq);
} // class
package org.doit.ik.mapper;
public interface SampleMapper {
String getTime();
}
public interface SampleMapper {
String getTime();
}
//mapper //interface
security
package org.doit.ik.security.damin;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.doit.ik.domain.AuthVO;
import org.doit.ik.domain.MemberVO;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import lombok.Getter;
@Getter
public class CustomUser extends User {
private static final long serialVersionUID = 8215844917794450806L;
private MemberVO member; // member 필드명 기억
public CustomUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
// 회원정보 + 권한정보(authList)
public CustomUser(MemberVO vo) {
super(
vo.getId()
, vo.getPwd()
// List<AuthVO> -> Collection<>
, vo.getAuthList().stream().map( auth->new SimpleGrantedAuthority( auth.getAuthority() ) ).collect( Collectors.toList() )
);
this.member = vo;
}
}
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.doit.ik.domain.AuthVO;
import org.doit.ik.domain.MemberVO;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import lombok.Getter;
@Getter
public class CustomUser extends User {
private static final long serialVersionUID = 8215844917794450806L;
private MemberVO member; // member 필드명 기억
public CustomUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
// 회원정보 + 권한정보(authList)
public CustomUser(MemberVO vo) {
super(
vo.getId()
, vo.getPwd()
// List<AuthVO> -> Collection<>
, vo.getAuthList().stream().map( auth->new SimpleGrantedAuthority( auth.getAuthority() ) ).collect( Collectors.toList() )
);
this.member = vo;
}
}
package org.doit.ik.security.damin;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.doit.ik.domain.AuthVO;
import org.doit.ik.domain.MemberVO;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import lombok.Getter;
@Getter
public class CustomUser extends User {
private static final long serialVersionUID = 8215844917794450806L;
private MemberVO member; // member 필드명 기억
public CustomUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
// 회원정보 + 권한정보(authList)
public CustomUser(MemberVO vo) {
super(
vo.getId()
, vo.getPwd()
// List<AuthVO> -> Collection<>
, vo.getAuthList().stream().map( auth->new SimpleGrantedAuthority( auth.getAuthority() ) ).collect( Collectors.toList() )
);
this.member = vo;
}
}
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.doit.ik.domain.AuthVO;
import org.doit.ik.domain.MemberVO;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import lombok.Getter;
@Getter
public class CustomUser extends User {
private static final long serialVersionUID = 8215844917794450806L;
private MemberVO member; // member 필드명 기억
public CustomUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
// 회원정보 + 권한정보(authList)
public CustomUser(MemberVO vo) {
super(
vo.getId()
, vo.getPwd()
// List<AuthVO> -> Collection<>
, vo.getAuthList().stream().map( auth->new SimpleGrantedAuthority( auth.getAuthority() ) ).collect( Collectors.toList() )
);
this.member = vo;
}
}
package org.doit.ik.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import lombok.extern.log4j.Log4j;
@Component("customAccessDeniedHandler")
@Log4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler{
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
log.error("> Access Denied Handler");
log.error("> Redirect...");
response.sendRedirect("/common/accessError.htm");
}
}
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import lombok.extern.log4j.Log4j;
@Component("customAccessDeniedHandler")
@Log4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler{
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
log.error("> Access Denied Handler");
log.error("> Redirect...");
response.sendRedirect("/common/accessError.htm");
}
}
package org.doit.ik.security;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import lombok.extern.log4j.Log4j;
@Component("customLoginSuccessHandler")
@Log4j
public class CustomLoginSuccessHandler
implements AuthenticationSuccessHandler{
@Override
public void onAuthenticationSuccess(
HttpServletRequest request,
HttpServletResponse response,
Authentication authentication // 인증받은 사용자의 정보(권한)
) throws IOException, ServletException {
log.warn("> Login Success...");
List<String> roleNames = new ArrayList<String>();
authentication.getAuthorities().forEach( auth -> {
roleNames.add(auth.getAuthority());
});
log.warn("> ROLE NAMES : " + roleNames );
if ( roleNames.contains("ROLE_ADMIN")) {
response.sendRedirect("/");
return;
} else if( roleNames.contains("ROLE_MANAGER")){
response.sendRedirect("/customer/notice.htm");
return;
} else if( roleNames.contains("ROLE_USER")){
response.sendRedirect("/customer/notice.htm");
return;
}
}
}
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import lombok.extern.log4j.Log4j;
@Component("customLoginSuccessHandler")
@Log4j
public class CustomLoginSuccessHandler
implements AuthenticationSuccessHandler{
@Override
public void onAuthenticationSuccess(
HttpServletRequest request,
HttpServletResponse response,
Authentication authentication // 인증받은 사용자의 정보(권한)
) throws IOException, ServletException {
log.warn("> Login Success...");
List<String> roleNames = new ArrayList<String>();
authentication.getAuthorities().forEach( auth -> {
roleNames.add(auth.getAuthority());
});
log.warn("> ROLE NAMES : " + roleNames );
if ( roleNames.contains("ROLE_ADMIN")) {
response.sendRedirect("/");
return;
} else if( roleNames.contains("ROLE_MANAGER")){
response.sendRedirect("/customer/notice.htm");
return;
} else if( roleNames.contains("ROLE_USER")){
response.sendRedirect("/customer/notice.htm");
return;
}
}
}
package org.doit.ik.security;
import org.doit.ik.domain.MemberVO;
import org.doit.ik.mapper.MemberMapper;
import org.doit.ik.security.damin.CustomUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import lombok.Setter;
import lombok.extern.log4j.Log4j;
@Component("customUserDetailsService")
@Log4j
public class CustomUserDetailsService implements UserDetailsService{
@Setter(onMethod=@__({@Autowired}))
private MemberMapper memberMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
log.warn("> Load User By UserName : " + username);
// vo 객체에는 회원정보 + 권한정보(authList)
MemberVO vo = this.memberMapper.read(username);
log.warn("> Queiried by Member mapper : " + vo);
// UserDetails <- 변환X vo
// User 구현 org.doit.ik.security.damin.CustomUser
return vo == null ? null : new CustomUser(vo);
}
}
import org.doit.ik.domain.MemberVO;
import org.doit.ik.mapper.MemberMapper;
import org.doit.ik.security.damin.CustomUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import lombok.Setter;
import lombok.extern.log4j.Log4j;
@Component("customUserDetailsService")
@Log4j
public class CustomUserDetailsService implements UserDetailsService{
@Setter(onMethod=@__({@Autowired}))
private MemberMapper memberMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
log.warn("> Load User By UserName : " + username);
// vo 객체에는 회원정보 + 권한정보(authList)
MemberVO vo = this.memberMapper.read(username);
log.warn("> Queiried by Member mapper : " + vo);
// UserDetails <- 변환X vo
// User 구현 org.doit.ik.security.damin.CustomUser
return vo == null ? null : new CustomUser(vo);
}
}
//domain
package org.doit.ik.service;
import java.sql.SQLException;
import org.doit.ik.domain.NoticeVO;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
//@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public interface MemberShipService {
void insertAndPointUpOfMember(NoticeVO notice, String id) throws ClassNotFoundException, SQLException ;
}
import java.sql.SQLException;
import org.doit.ik.domain.NoticeVO;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
//@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public interface MemberShipService {
void insertAndPointUpOfMember(NoticeVO notice, String id) throws ClassNotFoundException, SQLException ;
}
//interface
package org.doit.ik.service;
import java.sql.SQLException;
import org.doit.ik.domain.NoticeVO;
import org.doit.ik.mapper.NoticeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MemberShipServiceImpl implements MemberShipService{
@Autowired
private NoticeMapper noticeDao;
// 어노테이션 트랜잭션 처리...
@Override
//@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public void insertAndPointUpOfMember(NoticeVO notice, String id) throws ClassNotFoundException, SQLException {
noticeDao.insert(notice);
notice.setTitle( notice.getTitle() + " - 2" );
noticeDao.insert(notice);
}
}
import java.sql.SQLException;
import org.doit.ik.domain.NoticeVO;
import org.doit.ik.mapper.NoticeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MemberShipServiceImpl implements MemberShipService{
@Autowired
private NoticeMapper noticeDao;
// 어노테이션 트랜잭션 처리...
@Override
//@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public void insertAndPointUpOfMember(NoticeVO notice, String id) throws ClassNotFoundException, SQLException {
noticeDao.insert(notice);
notice.setTitle( notice.getTitle() + " - 2" );
noticeDao.insert(notice);
}
}
//membershipservice
package org.doit.ik;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 lombok.extern.log4j.Log4j;
@Controller
@Log4j
@RequestMapping("/")
public class HomeController {
public HomeController() {
super();
}
@RequestMapping("index.htm")
public String home() throws Exception{
return "home.index"; // *.*
}
}
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 lombok.extern.log4j.Log4j;
@Controller
@Log4j
@RequestMapping("/")
public class HomeController {
public HomeController() {
super();
}
@RequestMapping("index.htm")
public String home() throws Exception{
return "home.index"; // *.*
}
}
//homecontroller
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.doit.ik.mapper.MemberMapper">
<select id="getMember" resultType="org.doit.ik.domain.MemberVO">
SELECT *
FROM MEMBER2
WHERE id = #{ id }
</select>
<insert id="insert">
INSERT INTO MEMBER2
( ID, PWD, NAME, GENDER, BIRTH, IS_LUNAR, CPHONE, EMAIL, HABIT, REGDATE)
VALUES( #{id}, #{ pwd }, #{name}, #{gender}, #{birth}, #{is_lunar}, #{cphone}, #{email}, #{habit}, SYSDATE)
</insert>
<resultMap type="org.doit.ik.domain.MemberVO" id="memberMap">
<id property="id" column="id" />
<result property="id" column="id" />
<result property="pwd" column="pwd" />
<result property="name" column="name" />
<result property="regdate" column="regdate" />
<collection property="authList" resultMap="authMap"></collection>
</resultMap>
<resultMap type="org.doit.ik.domain.AuthVO" id="authMap">
<result property="username" column="username" />
<result property="authority" column="authority" />
</resultMap>
<select id="read" resultMap="memberMap">
SELECT id, pwd, name, enabled, regdate, authority
FROM member2 m LEFT JOIN member2_authorities auth ON m.id = auth.username
WHERE m.id = #{ userid }
</select>
</mapper>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.doit.ik.mapper.MemberMapper">
<select id="getMember" resultType="org.doit.ik.domain.MemberVO">
SELECT *
FROM MEMBER2
WHERE id = #{ id }
</select>
<insert id="insert">
INSERT INTO MEMBER2
( ID, PWD, NAME, GENDER, BIRTH, IS_LUNAR, CPHONE, EMAIL, HABIT, REGDATE)
VALUES( #{id}, #{ pwd }, #{name}, #{gender}, #{birth}, #{is_lunar}, #{cphone}, #{email}, #{habit}, SYSDATE)
</insert>
<resultMap type="org.doit.ik.domain.MemberVO" id="memberMap">
<id property="id" column="id" />
<result property="id" column="id" />
<result property="pwd" column="pwd" />
<result property="name" column="name" />
<result property="regdate" column="regdate" />
<collection property="authList" resultMap="authMap"></collection>
</resultMap>
<resultMap type="org.doit.ik.domain.AuthVO" id="authMap">
<result property="username" column="username" />
<result property="authority" column="authority" />
</resultMap>
<select id="read" resultMap="memberMap">
SELECT id, pwd, name, enabled, regdate, authority
FROM member2 m LEFT JOIN member2_authorities auth ON m.id = auth.username
WHERE m.id = #{ userid }
</select>
</mapper>
//membermapper
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.doit.ik.mapper.NoticeMapper">
<!-- ${전달된 값 그대로 적용} #{ 전달된 값의 자료형에 맞게 변환} -->
<select id="getCount" resultType="Integer">
SELECT COUNT(*) CNT
FROM NOTICES2
WHERE ${ param1 } LIKE '%${ param2 }%'
</select>
<select id="getNotices" resultType="org.doit.ik.domain.NoticeVO">
SELECT *
FROM (
SELECT ROWNUM NUM, N.*
FROM (
SELECT *
FROM NOTICES2
WHERE ${ param2 } LIKE '%${ param3 }%'
ORDER BY REGDATE DESC
) N
)
WHERE NUM BETWEEN (1 + ( #{param1} -1)*15) AND (15 + (#{param1} -1)*15)
</select>
<delete id="delete">
DELETE FROM NOTICES2
WHERE SEQ=#{ seq }
</delete>
<update id="update">
UPDATE NOTICES2
SET TITLE=#{title} , CONTENT=#{content}
<if test="filesrc != null">
, FILESRC=#{filesrc}
</if>
WHERE SEQ=#{seq}
</update>
<select id="getNotice" resultType="org.doit.ik.domain.NoticeVO">
SELECT *
FROM NOTICES2
WHERE SEQ= #{seq}
</select>
<insert id="insert">
<selectKey order="BEFORE" resultType="String" keyProperty="seq">
SELECT MAX(TO_NUMBER(SEQ))+1
FROM NOTICES
</selectKey>
INSERT INTO NOTICES2
( SEQ, TITLE, CONTENT, WRITER, REGDATE, HIT, FILESRC)
VALUES
( #{ seq } , #{ title } , #{ content }, #{ writer }, SYSDATE, 0, #{filesrc, javaType=String, jdbcType=VARCHAR} )
</insert>
<update id="hitUp">
UPDATE notices2
SET hit = hit + 1
WHERE seq = #{ seq }
</update>
<select id="getHit" resultType="Integer">
SELECT hit
FROM notices2
WHERE seq = #{ seq }
</select>
</mapper>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.doit.ik.mapper.NoticeMapper">
<!-- ${전달된 값 그대로 적용} #{ 전달된 값의 자료형에 맞게 변환} -->
<select id="getCount" resultType="Integer">
SELECT COUNT(*) CNT
FROM NOTICES2
WHERE ${ param1 } LIKE '%${ param2 }%'
</select>
<select id="getNotices" resultType="org.doit.ik.domain.NoticeVO">
SELECT *
FROM (
SELECT ROWNUM NUM, N.*
FROM (
SELECT *
FROM NOTICES2
WHERE ${ param2 } LIKE '%${ param3 }%'
ORDER BY REGDATE DESC
) N
)
WHERE NUM BETWEEN (1 + ( #{param1} -1)*15) AND (15 + (#{param1} -1)*15)
</select>
<delete id="delete">
DELETE FROM NOTICES2
WHERE SEQ=#{ seq }
</delete>
<update id="update">
UPDATE NOTICES2
SET TITLE=#{title} , CONTENT=#{content}
<if test="filesrc != null">
, FILESRC=#{filesrc}
</if>
WHERE SEQ=#{seq}
</update>
<select id="getNotice" resultType="org.doit.ik.domain.NoticeVO">
SELECT *
FROM NOTICES2
WHERE SEQ= #{seq}
</select>
<insert id="insert">
<selectKey order="BEFORE" resultType="String" keyProperty="seq">
SELECT MAX(TO_NUMBER(SEQ))+1
FROM NOTICES
</selectKey>
INSERT INTO NOTICES2
( SEQ, TITLE, CONTENT, WRITER, REGDATE, HIT, FILESRC)
VALUES
( #{ seq } , #{ title } , #{ content }, #{ writer }, SYSDATE, 0, #{filesrc, javaType=String, jdbcType=VARCHAR} )
</insert>
<update id="hitUp">
UPDATE notices2
SET hit = hit + 1
WHERE seq = #{ seq }
</update>
<select id="getHit" resultType="Integer">
SELECT hit
FROM notices2
WHERE seq = #{ seq }
</select>
</mapper>
//notice mapper
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.doit.ik.mapper.SampleMapper">
<select id="getTime" resultType="string">
SELECT sysdate
FROM dual
</select>
</mapper>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.doit.ik.mapper.SampleMapper">
<select id="getTime" resultType="string">
SELECT sysdate
FROM dual
</select>
</mapper>
//samplemapper
[notice.htm] 요청 URL
Ctrl + F11
[1] 실제 프로젝트
인증사용자 정보(username, passwrod) X
+ 추가정보( 이메일, 연락처, .... + 권한들 )
[2] 해결) 직접 UserDetailsService 구현하는 방법
1개의 메서드
UserDetails loadUserByUsername(String username)
[3] UserDetails 리턴타입 <- User <- MemberVO
가장 일반적으로 많이 사용되는 방법이
User 클래스를 상속하는 형태...
[4] 실습
(1) 로그인 사용자 ID로 글쓰기할 때 작성자로 설정.
noticeReg() admin -> 글쓰기
(2) org.doit.ik.domain 패키지.
ㄱ. AuthVO.java 권한 정보
ㄴ. MemberVO.java + 필드 추가.
(3) 회원 + 권한들 MemberMapper.java
// 회원 정보 + 권한정보(authList)들 얻어오는 메서드
public MemberVO read(String userid);
(4) MemberMapper.xml
(5) CustomUserDetailsService 직접 구현
org.doit.ik.security 패키지 추가
(6) 글쓰기 ( 로그인 ) 인증받은 회원정보 + 권한 정보 확인
<div>
<ol>
<li>principal : <sec:authentication property="principal"/></li>
<!-- CustomUser의 member 필드 -->
<li>MemberVO : <sec:authentication property="principal.member"/></li>
<li>사용자 ID : <sec:authentication property="principal.member.id"/></li>
<li>사용자 이름 : <sec:authentication property="principal.member.name"/></li>
<li>사용자 권한 목록 : <sec:authentication property="principal.member.authList"/></li>
</ol>
</div>
(7) 수정, 삭제는 작성자 == 로그인ID 같으면 삭제할 수 있다.
noticeDetail.jsp
Ctrl + F11
[1] 실제 프로젝트
인증사용자 정보(username, passwrod) X
+ 추가정보( 이메일, 연락처, .... + 권한들 )
[2] 해결) 직접 UserDetailsService 구현하는 방법
1개의 메서드
UserDetails loadUserByUsername(String username)
[3] UserDetails 리턴타입 <- User <- MemberVO
가장 일반적으로 많이 사용되는 방법이
User 클래스를 상속하는 형태...
[4] 실습
(1) 로그인 사용자 ID로 글쓰기할 때 작성자로 설정.
noticeReg() admin -> 글쓰기
(2) org.doit.ik.domain 패키지.
ㄱ. AuthVO.java 권한 정보
ㄴ. MemberVO.java + 필드 추가.
(3) 회원 + 권한들 MemberMapper.java
// 회원 정보 + 권한정보(authList)들 얻어오는 메서드
public MemberVO read(String userid);
(4) MemberMapper.xml
(5) CustomUserDetailsService 직접 구현
org.doit.ik.security 패키지 추가
(6) 글쓰기 ( 로그인 ) 인증받은 회원정보 + 권한 정보 확인
<div>
<ol>
<li>principal : <sec:authentication property="principal"/></li>
<!-- CustomUser의 member 필드 -->
<li>MemberVO : <sec:authentication property="principal.member"/></li>
<li>사용자 ID : <sec:authentication property="principal.member.id"/></li>
<li>사용자 이름 : <sec:authentication property="principal.member.name"/></li>
<li>사용자 권한 목록 : <sec:authentication property="principal.member.authList"/></li>
</ol>
</div>
(7) 수정, 삭제는 작성자 == 로그인ID 같으면 삭제할 수 있다.
noticeDetail.jsp
//notice.htm
'취준 note 2023 > spring' 카테고리의 다른 글
스프링AOP (0) | 2023.08.12 |
---|---|
스프링 di (0) | 2023.08.12 |
spring master - chap2 스프링빈 의존성 주입(IOC) (0) | 2023.01.23 |
코드없이 보는 스프링 부트 -페이징 정렬 처리하기 (0) | 2023.01.21 |
컨트롤러와 RESTAPI (0) | 2023.01.21 |