public class PhotoDto {
private String name;
private String photo;
//getter,setter생략
public PhotoDto(String name,String photo) {
super(); //생략가능,하지만 위치는 맨위에
this.name=name;
this.photo=photo;
}
}
@Controller
public class JsonTestController {
@GetMapping("/list3")
public @ResponseBody List<PhotoDto> list3(){
List<PhotoDto> list=new ArrayList<PhotoDto>();
list.add(new PhotoDto("카톡임티1", "b1.png"));
list.add(new PhotoDto("카톡임티2", "b3.png"));
list.add(new PhotoDto("카톡임티3", "b5.png"));
list.add(new PhotoDto("카톡임티4", "b7.png"));
list.add(new PhotoDto("카톡임티5", "b9.png"));
return list;
}
}
<body>
<!--ex3번 예제-->
<button type="button" id="btn3">list3 json 배열</button>
<div id="out3"></div>
<script type="text/javascript">
$("#btn3").click(function(){
$.ajax({
type:"get",
url:"list3",
dataType:"json",
success:function(data){
var s="";
$.each(data,function(i,elt){
s+="<figure>";
s+="<img src='image/avata/"+elt.photo+"' width=100>";
s+="<figcaption><b>";
s+=elt.name;
s+="</b></figcaption>";
s+="</figure>";
});
$("#out3").html(s);
}
});
});
</script>
</body>
public class JsonTest2Controller {
@GetMapping("/list4")
public Map<String, Object> list4(@RequestParam String name){
Map<String, Object>map=new HashMap<String, Object>();
List<PhotoDto> list=new ArrayList<PhotoDto>();
list.add(new PhotoDto("카톡임티1", "b1.png"));
list.add(new PhotoDto("카톡임티2", "b3.png"));
list.add(new PhotoDto("카톡임티3", "b5.png"));
list.add(new PhotoDto("카톡임티4", "b7.png"));
list.add(new PhotoDto("카톡임티5", "b9.png"));
map.put("name", "없는 이름");
map.put("photo", "no.png");
for(PhotoDto dto:list) {
if(name.equals(dto.getName())) {
map.put("name", dto.getName());
map.put("photo", dto.getPhoto());
}
}
return map;
}
}
<body>
<!--Ex4번 예제-->
<h4>메뉴명을 입력후 엔터를 쳐주세요</h4>
<input type="text" id="search" class="form-control">
<h2 id="fname"></h2>
<img alt="" src="" id="photo">
<script type="text/javascript">
$("#search").keydown(function(e) {
if(e.keyCode&&e.keyCode==13) {
var name=$(this).val();
$.ajax({
type:"get",
url:"list4",
dataType:"json",
data:{"name":name},
success:function(data){
$("#photo").attr("src","image/avata/"+data.photo);
$("#fname").html(data.name);
}
});
}
});
</script>
</body>
public class InfoDto {
private String num;
private String name;
private String driver;
private String addr;
private String photo;
private Timestamp gaipday;
//getter,setter생략
}
public interface InfoInter {
public int getTotalCount();
public void insertMyInfo(InfoDto dto);
public List<InfoDto> getAllDatas();
public InfoDto getData(String num);
public void updateMyifo(InfoDto dto);
public void deleteMyInfo(String num);
}
@Repository
public class InfoDao implements InfoInter {
@Autowired
SqlSession session;
@Override
public int getTotalCount() {
return session.selectOne("selectTotalCountOfMyInfo");
}
@Override
public void insertMyInfo(InfoDto dto) {
session.insert("insertOfmyInfo",dto);
}
@Override
public List<InfoDto> getAllDatas() {
return session.selectList("selectAllOfMyInfo");
}
@Override
public InfoDto getData(String num) {
return session.selectOne("getDataOfMyInfo", num);
}
@Override
public void updateMyifo(InfoDto dto) {
session.update("updateOfMyInfo",dto);
}
@Override
public void deleteMyInfo(String num) {
session.delete("deleteOfMyInfo",num);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="idto" type="spring.mvc.friday.InfoDto"/>
</typeAliases>
</configuration>
<?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="spring.mvc.friday.InfoDao">
<!--일반적 sql문은 기존과 동일하게 작성 : 생략-->
<!--조건에 따른 sql문 작성-->
<update id="updateOfMyInfo" parameterType="idto">
update myinfo set name=#{name},driver=#{driver},addr=#{addr}
<if test="photo!=null">
,photo=#{photo}
</if>
where num=#{num}
</update>
</mapper>
@Controller
public class InfoController {
@Autowired
InfoInter inter;
//메서드는 후술
}
@Controller
public class InfoController {
//이후로 InfoInter 호출 생략
@GetMapping("/info/list")
public String list(Model model) {
int count=inter.getTotalCount();
List<InfoDto>list=inter.getAllDatas();
model.addAttribute("list",list);
model.addAttribute("count", count);
return "info/infoList";
}
@GetMapping("/info/addform")
public String add() {
return "info/addForm";
}
@GetMapping("/info/updateform")
public String updateForm(Model model,@RequestParam String num) {
InfoDto dto=inter.getData(num);
model.addAttribute("dto",dto);
return "info/updateForm";
}
}
@Controller
public class InfoController {
@PostMapping("/info/insert")
public String insert(@ModelAttribute InfoDto dto,
@RequestParam MultipartFile upload,
HttpSession session) {
String path=session.getServletContext().getRealPath("/resources/image/");
System.out.println(path);
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
String photo="";
//사진선택을 안했을경우 no..
if(upload.getOriginalFilename().equals("")) {
photo="no";
}else {
String fName=upload.getOriginalFilename();
fName=sdf.format(new Date())+"_"+fName;
photo=fName;
//업로드 슬래쉬는 1개 역슬래쉬는 2개
try {
upload.transferTo(new File(path+"/"+photo));
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//dto에 photo 넣기
dto.setPhoto(photo);
//insert
inter.insertMyInfo(dto);
return "redirect:list";
}
}
미업로드 예외 처리 : 조건문을 통해 미업로드 시 DB에 저장될 값 지정 / try ~ catch문 이용
중복 업로드 생략 처리 : 업로드 시간을 파일명에 추가
→ 처리된 파일명으로 DTO 멤버 값 변경 후 insert
@Controller
public class InfoController {
@PostMapping("info/update")
public String update(@ModelAttribute("dto")InfoDto dto,
@RequestParam MultipartFile upload,
HttpSession session) {
String photo=inter.getData(dto.getNum()).getPhoto();
System.out.println(photo);
if(!photo.equals("no")) {
String path=session.getServletContext().getRealPath("/resources/image/");
File file=new File(path+"/"+photo);
file.delete();
}
String path=session.getServletContext().getRealPath("/resources/image/");
System.out.println(path);
String photoName;
if(upload.getOriginalFilename().equals("")) {
photoName=null;
}else {
photoName=upload.getOriginalFilename();
try {
upload.transferTo(new File(path+"/"+photoName));
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//dto의 photo에 업로드한 photoname 넣어주기
dto.setPhoto(photoName);
inter.updateMyifo(dto);
return "redirect:list";
}
}
@Controller
public class InfoController {
@GetMapping("info/delete")
public String delete(@RequestParam String num,HttpSession session) {
String photo=inter.getData(num).getPhoto();
if(!photo.equals("no")) {
String path=session.getServletContext().getRealPath("/resources/image/");
File file=new File(path+"/"+photo);
file.delete();
}
inter.deleteMyInfo(num);
return "redirect:list";
}
}
<form action="insert" method="post" enctype="multipart/form-data">
<table>
<!-- text 업로드 생략 -->
<tr>
<th>사진</th>
<td>
<input type="file" name="upload" style="width: 250px;" class="form-control">
</td>
</tr>
<tr>
<th>운전면허</th>
<td>
<input type="radio" name="driver" value="있음">있음
<input type="radio" name="driver" value="없음" checked>없음
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit">DB저장</button>
<button type="button" onclick="location.href='list'">목록</button>
</td>
</tr>
</table>
</form>
<form action="update" method="post" enctype="multipart/form-data">
<input type="hidden" name="num" value="${dto.num }">
<table>
<tr>
<th>사진</th>
<td>
<input type="file" name="upload" style="width: 250px;" class="form-control">
</td>
</tr>
<tr>
<th>운전면허</th>
<td>
<input type="radio" name="driver" value="있음" ${dto.driver=="있음"?"checked":"" }>있음
<input type="radio" name="driver" value="없음" ${dto.driver=="없음"?"checked":"" }>없음
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit">DB저장</button>
<button type="button" onclick="location.href='list'">목록</button>
</td>
</tr>
</table>
</form>
<!-- 일반적인 방법 이용 -->