SPRING - SPRING FRAMEWORK 3 db fileupload

최성현·2023년 10월 16일
0

SPRING FRAMEWORK 3

목록 보기
7/10

설정

  • pom.xml 아래 dependecy 추가
		<!-- mysql 연결 작업 -->
		
		
		<!-- mysql-connector-java -->
		<dependency>
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		    <version>8.0.30</version>
		</dependency>

		
		<!-- mybatis/mybatis -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.5.9</version>
		</dependency>
				
				
		<!-- mybatis-spring -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-spring</artifactId>
		    <version>2.0.7</version>
		</dependency>
		
		<!-- springframework/spring-jdbc -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-jdbc</artifactId>
		    <version>${org.springframework-version}</version>
		</dependency>
				
		<!-- add 파일 업로드 2개 -->
		
		<!-- commons-io -->
		<dependency>
		    <groupId>commons-io</groupId>
		    <artifactId>commons-io</artifactId>
		    <version>2.4</version>
		</dependency>
				
		<!-- commons-fileupload -->
		<dependency>
		    <groupId>commons-fileupload</groupId>
		    <artifactId>commons-fileupload</artifactId>
		    <version>1.3.1</version>
		</dependency>	
  • servlet-context.xml
    파일 업로드 설정
	<!-- 위치 상관 x
		 file_upload setting
		 class multipartresolver 자동완성해서 불러온 후 id 하면 자동완성 -->
	<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- encoding -->
		<beans:property name="defaultEncoding" value="utf-8"/>
		<!-- 파일크기 설정 3000000->3mb -->
		<beans:property name="maxUploadSize" value="3000000"/>
	</beans:bean>
  • root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
      <property name="url" value="jdbc:mysql://localhost:3306/coffee?serverTimezone=Asia/Seoul"></property>
      <property name="username" value="tjdgus"></property> 
      <property name="password" value="1234"></property> 
   </bean>
   
   
   <!-- sqlSessionFactory Autowired받아서 안에 있는 메소드를 사용한다 -->
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource"/>
      <property name="configLocation"  value="classpath:mybatis-config.xml"/>
      <property name="mapperLocations" value="classpath:mapper/*Mapper.xml"/>
   </bean>


   <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
      <constructor-arg ref="sqlSessionFactory"/>
   </bean>
   
   <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource" ref="dataSource"/>
   </bean>

</beans>

-mybatis-config.xml
dto 등록

<?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="indto" type="spring.mvc.friday.InfoDto"/>
		<typeAlias alias="bdto" type="spring.mvc.reboard.BoardDto"/>
	</typeAliases>
</configuration>
  • infoMapper.xml
    DOCTYPE 설정
<?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">

Dto

package spring.mvc.friday;

import java.sql.Timestamp;

public class InfoDto {

	private String num;
	private String name;
	private String driver;
	private String addr;
	private String photo;
	private Timestamp gaipday;
	
	public String getNum() {
		return num;
	}
	public void setNum(String num) {
		this.num = num;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDriver() {
		return driver;
	}
	public void setDriver(String driver) {
		this.driver = driver;
	}
	public String getAddr() {
		return addr;
	}
	public void setAddr(String addr) {
		this.addr = addr;
	}
	public String getPhoto() {
		return photo;
	}
	public void setPhoto(String photo) {
		this.photo = photo;
	}
	public Timestamp getGaipday() {
		return gaipday;
	}
	public void setGaipday(Timestamp gaipday) {
		this.gaipday = gaipday;
	}
	
	
}

총 갯수 뽑기

  • infoMapper.xml
	<select id="selectTotalCountOfMyInfo" resultType="int">
		select count(*) from myinfo
	</select>
  • InfoInter.java
public int getTotalCount();
  • InfoDao.java
	@Override
	public int getTotalCount() {
		// TODO Auto-generated method stub
		return session.selectOne("selectTotalCountOfMyInfo");
	}
  • InfoController.java
	@GetMapping("/info/list")
	public String list(Model model,
	{
		int count=dao.getTotalCount();
	
		model.addAttribute("count", count);
		
		return "info/infolist";
	}
  • infolist.jsp
	<h3 class="alert alert-warning">${count }</h3>

insert

infoMapper.xml

	<insert id="insertOfMyInfo" parameterType="indto">
		insert into myinfo (name,driver,addr,photo,gaipday) values(#{name},#{driver},#{addr},#{photo},now())
	</insert>

InfoInter.java

	public void insertMyInfo(InfoDto dto);

InfoDao.java

	@Override
	public void insertMyInfo(InfoDto dto) {
		// TODO Auto-generated method stub
		session.insert("insertOfMyInfo", dto);
	}

InfoController.java

인자값

realPath를 사용하기 위해서 -> HttpSession session

	@PostMapping("/info/insert")
	public String insert(@ModelAttribute InfoDto dto,
			@RequestParam MultipartFile upload,
			//realPath를 사용하기 위해서
			HttpSession session)

photo - 빈문자열 테스트

빈문자열도 들어가는지 테스트하기 위해서 photo변수를 줬다 ... 실제 db에 넣는 값이 빈값
밑에 조건문을 주기 위해서는 빈문자열이 편하기 때문에 비워둔것

String photo="";

사진 선택 조건

사진선택을 안했을 경우 no...

  • if
		if(upload.getOriginalFilename().equals(""))
			photo="no"; //photo=null; -> null로 넣어주고 싶을 경우
  • else
		else {
			String fName=upload.getOriginalFilename();
			fName=sdf.format(new Date())+"_"+fName;
			photo=fName;
			
			//실제 업로드
			try {
				upload.transferTo(new File(path+"/"+photo));
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

dto에 photo 넣기

dto의 photo에 업로드한 것들을 넣어줘야한다

dto.setPhoto(photo);

마지막으로 insert

dao.insertMyInfo(dto);

InfoController.java

	@GetMapping("/info/addform")
	public String form()
	{
		return "info/addform";
	}
	
	@PostMapping("/info/insert")
	public String insert(@ModelAttribute InfoDto dto,
			@RequestParam MultipartFile upload,
			//realPath를 사용하기 위해서
			HttpSession session)
	{
		String path=session.getServletContext().getRealPath("/resources/image");
		System.out.println(path);
		
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		
		//빈문자열도 들어가는지 테스트하기 위해서 photo변수를 줬다 ... 실제 db에 넣는 값이 빈값
		String photo=""; //밑에 조건문을 주기 위해서는 빈문자열이 편하기 때문에 비워둔것

		//사진선택을 안했을 경우 no...
		if(upload.getOriginalFilename().equals(""))
			photo="no"; //photo=null; -> null로 넣어주고 싶을 경우
		else {
			String fName=upload.getOriginalFilename();
			fName=sdf.format(new Date())+"_"+fName;
			photo=fName;
			
			//실제 업로드
			try {
				upload.transferTo(new File(path+"/"+photo));
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		//dto의 photo에 업로드한 것들을 넣어줘야한다
		dto.setPhoto(photo);
		
		//마지막으로 insert
		dao.insertMyInfo(dto);
		
		return "redirect:list";
	}

addform.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>
<html>
<head>
<meta charset="UTF-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Cute+Font&family=Diphylleia&family=Dokdo&family=Nanum+Brush+Script&family=Nanum+Gothic+Coding&family=Noto+Sans+KR&display=swap" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
<title>Insert title here</title>
</head>
<body>
	<form action="insert" method="post" enctype="multipart/form-data">
 		<table class="table table-bordered" style="width: 400px;">
 			<caption align="top"><b>개인정보 입력</b></caption>
 			<tr>
 				<th>이름</th>
 				<td>
 					<input type="text" name="name" class="form-control"
 					style="width: 120px;" required="required">
 				</td>
 			</tr>
 			
 			<tr>
 				<th>주소</th>
 				<td>
 					<input type="text" name="addr" class="form-control"
 					style="width: 250px;" required="required">
 				</td>
 			</tr>
 			
 			<tr>
 				<th>사진</th>
 				<td>
 					<!-- dto와 이름이 같으면 오류남 -->
 					<input type="file" name="upload" class="form-control" style="width: 200px;">
 				</td>
 			</tr>
 			
 			<tr>
 				<th>운전면허</th>
 				<td>
 					<input type="radio" name="driver" value="있음">있음
 					<input type="radio" name="driver" value="없음" checked="checked">없음
 				</td>
 			</tr>
 			
 			<tr>
 				<td colspan="2" align="center">
 					<button type="submit" class="btn btn-outline-info">저장</button>
 					
 					<button type="button" class="btn btn-outline-success"
 					onclick="location.href='list'">목록</button>
 				</td>
 			</tr>
 		</table>
	</form>
</body>
</html>

update

infoMapper.xml

조건

photo!='no' 조건이 no일 경우 / 두가지 경우 모두 no나 null이 아닐경우 즉 사진이 있는 경우만 수정해준다는 조건
이렇게 조건 주면 기존 사진을 수정폼에 불러오지 않고 수정을 안해도 기존 사진이 남아있을 수 있다

		<if test="photo!=null"> <!-- photo!='no' 조건이 no일 경우 / 두가지 경우 모두 no나 null이 아닐경우 즉 사진이 있는 경우만 수정해준다는 조건
									 이렇게 조건 주면 기존 사진을 수정폼에 불러오지 않고 수정을 안해도 기존 사진이 남아있을 수 있다 -->
		,photo=#{photo}
		</if>
	<select id="selectOneOfMyInfo" resultType="indto" parameterType="String">
		select * from myinfo where num=#{num}
	</select>
	<update id="updateOfMyInfo" parameterType="indto">
		update myinfo set name=#{name},driver=#{driver},addr=#{addr}
		<if test="photo!=null"> <!-- photo!='no' 조건이 no일 경우 / 두가지 경우 모두 no나 null이 아닐경우 즉 사진이 있는 경우만 수정해준다는 조건
									 이렇게 조건 주면 기존 사진을 수정폼에 불러오지 않고 수정을 안해도 기존 사진이 남아있을 수 있다 -->
		,photo=#{photo}
		</if>
		where num=#{num}
	</update>

InfoInter.java

	public InfoDto getDataInfo(String num);
	public void updateMyInfo(InfoDto dto);

InfoDao.java

	@Override
	public InfoDto getDataInfo(String num) {
		// TODO Auto-generated method stub
		return session.selectOne("selectOneOfMyInfo", num);
	}

	@Override
	public void updateMyInfo(InfoDto dto) {
		// TODO Auto-generated method stub
		session.update("updateOfMyInfo", dto);
	}

InfoController.java

업데이트시 기존 사진 파일 삭제 및 수정한 파일 업로드

업데이트 할때 기존 사진을 바꾼다면 기존 사진파일 지우고 새로 업데이트한 사진을 생성하기 위해 @RequestParam String num 추가

	@PostMapping("/info/update")
	//업데이트 할때 기존 사진을 바꾼다면 기존 사진파일 지우고 새로 업데이트한 사진을 생성하기 위해 @RequestParam String num 추가 
	public String update(@ModelAttribute InfoDto dto,
			@RequestParam String num,
			@RequestParam MultipartFile upload,
			HttpSession session)
  • 해당 num값의 사진파일을 지우기 위해 해당 num의 photo값을 가져와서 변수에 넣어줌
String photo=dao.getDataInfo(num).getPhoto();
  • dto에 담을 변수
String photoname;
  • if - 사진 선택 안할 경우 null
		if(upload.getOriginalFilename().equals(""))
			photoname=null;
  • else
		else
		{
			photoname=upload.getOriginalFilename();
			photoname=sdf.format(new Date())+"_"+photoname;
			
			//실제 업로드
			try {
				upload.transferTo(new File(path+"/"+photoname));
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			//파일을 생성하는데 해당경로에 num에 해당하는 사진파일만
			File file=new File(path+"/"+photo);
			//기존 사진 파일 삭제
			file.delete();
		}
  • else안 기존사진파일 삭제
			//파일을 생성하는데 해당경로에 num에 해당하는 사진파일만
			File file=new File(path+"/"+photo);
			//기존 사진 파일 삭제
			file.delete();
  • dto의 photo에 업로드한 photoname 넣어주기 (수정한 사진 업로드) 및 업데이트
dto.setPhoto(photoname);

update
dao.updateMyInfo(dto);

InfoController.java

	@GetMapping("/info/uform")
	public String uform(@RequestParam String num,Model model)
	{
		InfoDto dto=dao.getDataInfo(num);
		
		model.addAttribute("dto", dto);
		
		return "/info/updateform";
	}
	
	@PostMapping("/info/update")
	//업데이트 할때 기존 사진을 바꾼다면 기존 사진파일 지우고 새로 업데이트한 사진을 생성하기 위해 @RequestParam String num 추가 
	public String update(@ModelAttribute InfoDto dto,
			@RequestParam String num,
			@RequestParam MultipartFile upload,
			HttpSession session)
	{
		String path=session.getServletContext().getRealPath("/resources/image/");
		System.out.println(path);
		
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		
		//해당 num값의 사진파일을 지우기 위해 해당 num의 photo값을 가져와서 변수에 넣어줌
		String photo=dao.getDataInfo(num).getPhoto();
		
		String photoname; //dto에 담을 변수
		
		//사진 선택 안할 경우 null
		if(upload.getOriginalFilename().equals(""))
			photoname=null;
		else
		{
			photoname=upload.getOriginalFilename();
			photoname=sdf.format(new Date())+"_"+photoname;
			
			//실제 업로드
			try {
				upload.transferTo(new File(path+"/"+photoname));
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			//파일을 생성하는데 해당경로에 num에 해당하는 사진파일만
			File file=new File(path+"/"+photo);
			//기존 사진 파일 삭제
			file.delete();
		}
		
		//dto의 photo에 업로드한 photoname 넣어주기
		dto.setPhoto(photoname);
		
		//update
		dao.updateMyInfo(dto);
		
		return "redirect:list";
	}

updateform.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>
<html>
<head>
<meta charset="UTF-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Cute+Font&family=Diphylleia&family=Dokdo&family=Nanum+Brush+Script&family=Nanum+Gothic+Coding&family=Noto+Sans+KR&display=swap" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
<title>Insert title here</title>
</head>
<body>
	<form action="update" method="post" enctype="multipart/form-data">
	<input type="hidden" name="num" value="${dto.num }">
 		<table class="table table-bordered" style="width: 400px;">
 			<caption align="top"><b>개인정보 수정</b></caption>
 			<tr>
 				<th>이름</th>
 				<td>
 					<input type="text" name="name" class="form-control"
 					style="width: 120px;" required="required" value="${dto.name }">
 				</td>
 			</tr>
 			
 			<tr>
 				<th>주소</th>
 				<td>
 					<input type="text" name="addr" class="form-control"
 					style="width: 250px;" required="required" value="${dto.addr }">
 				</td>
 			</tr>
 			
 			<tr>
 				<th>사진</th>
 				<td>
 					<!-- dto와 이름이 같으면 오류남 -->
 					<input type="file" name="upload" class="form-control" style="width: 200px;">
 				</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" class="btn btn-outline-warning">수정</button>
 					
 					<button type="button" class="btn btn-outline-success"
 					onclick="location.href='list'">목록</button>
 				</td>
 			</tr>
 		</table>
	</form>
</body>
</html>

delete

infoMapper.xml

	<delete id="deleteOfMyInfo" parameterType="String">
		delete from myinfo where num=#{num}
	</delete>

InfoInter.java

	public void deleteMyInfo(String num);

InfoDao.java

	@Override
	public void deleteMyInfo(String num) {
		// TODO Auto-generated method stub
		session.delete("deleteOfMyInfo", num);
	}

InfoController.java

num 인자값

해당 num의 사진파일만 지우기 위해서 필요함...그냥 삭제하면 db에서만 지워지고 사진파일은 남아있기 때문에 같이 지워줘야함

	public String delete(@RequestParam String num,
			//해당 num의 사진파일만 지우기 위해서 필요함...그냥 삭제하면 db에서만 지워지고 사진파일은 남아있기 때문에 같이 지워줘야함
			HttpSession session)

num에 해당한 photo 가져오기

해당 num의 정보 중 photo만 가져옴

String photo=dao.getDataInfo(num).getPhoto();

photo.equals("no")

photo가 no이면 삭제할 필요가 없음 (업로드한 사진파일이 없기 때문)

		if(!photo.equals("no"))
		{
			String path=session.getServletContext().getRealPath("/resources/image/");
			
			//파일을 생성하는데 해당경로에 num에 해당하는 사진파일만
			File file=new File(path+"/"+photo);
			//그 사진 파일 삭제
			file.delete();
		}

db 삭제

dao.deleteMyInfo(num);

InfoController.java

	@GetMapping("/info/delete")
	public String delete(@RequestParam String num,
			//해당 num의 사진파일만 지우기 위해서 필요함...그냥 삭제하면 db에서만 지워지고 사진파일은 남아있기 때문에 같이 지워줘야함
			HttpSession session)
	{
		//해당 num의 정보 중 photo만 가져옴
		String photo=dao.getDataInfo(num).getPhoto();
		
		//photo가 no이면 삭제할 필요가 없음 (업로드한 사진파일이 없기 때문)
		if(!photo.equals("no"))
		{
			String path=session.getServletContext().getRealPath("/resources/image/");
			
			//파일을 생성하는데 해당경로에 num에 해당하는 사진파일만
			File file=new File(path+"/"+photo);
			//그 사진 파일 삭제
			file.delete();
		}
		
		//db삭제
		dao.deleteMyInfo(num);
		
		return "redirect:list";
	}

검색 기능 + 출력

infoMapper.xml

if문에 안걸리면 일반 리스트 출력 / if문에 걸리면 검색효과+출력

parameterType="Map"

2개 이상의 인자값을 넘겨야 할땐 map 사용

if

form의 검색칸이 null이 아닐때만
if문에 안걸리면 일반 리스트 출력 / if문에 걸리면 검색효과+출력

${}은 컬럼을 의미
where {검색 기준이 될 필드명} like concat('%',?,'%');

		<if test="search!=null">
			<!-- 달러{}은 컬럼을 의미
				 where {검색 기준이 될 필드명} like concat('%',?,'%'); -->
			where ${title} like concat ('%',#{search},'%')
		</if>
	<!-- 검색 리스트 / 2개 이상의 인자값을 넘겨야 할땐 map 사용 -->
	<select id="selectAllOfMyInfo" resultType="indto" parameterType="Map">
		select * from myinfo
		<!-- form의 검색칸이 null이 아닐때만
			 if문에 안걸리면 일반 리스트 출력 / if문에 걸리면 검색효과+출력 -->
		<if test="search!=null">
			<!-- 달러{}은 컬럼을 의미
				 where {검색 기준이 될 필드명} like concat('%',?,'%'); -->
			where ${title} like concat ('%',#{search},'%')
		</if>
		order by num asc
	</select>

InfoInter.java

	public List<InfoDto> getAllInfoes(Map<String, String> map);

InfoDao.java

	@Override
	public List<InfoDto> getAllInfoes(Map<String, String> map) {
		// TODO Auto-generated method stub
		return session.selectList("selectAllOfMyInfo", map);
	}

InfoController.java

인자값

첫 화면에 title값이 없기때문에 400번 오류가 떠서 defaultValue로 준다

	public String list(Model model,
			//첫 화면에 title값이 없기때문에 400번 오류가 떠서 defaultValue로 준다 
			@RequestParam(defaultValue = "name") String title,
			@RequestParam(required = false) String search)
  • map
    Map을 생성해서 값을 넣어주고 dao를 list에 넣어준다
		Map<String, String> map=new HashMap<String, String>();
		map.put("search", search);
		map.put("title", title);
  • List 추가
		List<InfoDto> list=dao.getAllInfoes(map);
	
		model.addAttribute("count", count);
		model.addAttribute("list", list);

InfoController.java

	@GetMapping("/info/list")
	public String list(Model model,
			//첫 화면에 title값이 없기때문에 400번 오류가 떠서 defaultValue로 준다 
			@RequestParam(defaultValue = "name") String title,
			@RequestParam(required = false) String search)
	{
		int count=dao.getTotalCount();
		//List<InfoDto> list=dao.getAllInfoes();
		
		System.out.println(title+","+search);
		
		//Map을 생성해서 값을 넣어주고 dao를 list에 넣어준다
		Map<String, String> map=new HashMap<String, String>();
		map.put("search", search);
		map.put("title", title);
		
		List<InfoDto> list=dao.getAllInfoes(map);
	
		model.addAttribute("count", count);
		model.addAttribute("list", list);
		
		return "info/infolist";
	}

검색기능

지금상태에서는 list mapping에 추가해야해서 action이 list

select

	<div style="width: 900px; text-align: center;">
		<form action="list" class="d-inline-flex">
			<select name="title" class="form-control" style="width: 120px;">
				<!-- title의 값이 어떤 것이냐에 따라 selected -->
				<option value="name" ${title=='name'?"selected":"" }>이름</option>
				<option value="addr" ${title=='addr'?"selected":"" }>주소</option>
				<option value="driver" ${title=='driver'?"selected":"" }>운전면허</option>
			</select>
			
			<input type="text" name="search" class="form-control"
			placeholder="검색단어" style="width: 150px;" value="${search }">
			
			<button type="submit" class="btn btn-success">검색</button>
		</form>
	</div>

infolist.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>
<html>
<head>
<meta charset="UTF-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Cute+Font&family=Diphylleia&family=Dokdo&family=Nanum+Brush+Script&family=Nanum+Gothic+Coding&family=Noto+Sans+KR&display=swap" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
<title>Insert title here</title>
</head>
<body>
	<h3 class="alert alert-warning">${count }</h3>
	
	<br><br>
	<button type="button" class="btn btn-info btn-sm"
	onclick="location.href='addform'">글쓰기</button>
	
	<hr>
	<table class="table table-bordered" style="width: 900px;">
		<tr>
			<th width="60">번호</th>
			<th width="150">이름</th>
			<th width="400">주소</th>
			<th width="200">사진</th>
			<th width="160">운전면허</th>
			<th width="160">가입날짜</th>
			<th width="160">편집</th>
		</tr>
		<c:forEach var="in" items="${list }" varStatus="i">
			<tr>
				<td>${i.count }</td>
				<td>${in.name }</td>
				<td>${in.addr }</td>
				<td>
					<c:if test="${in.photo=='no' }">
						<!-- "/(루트)"바로 다음에 image가 와야하기 때문에 ../로 하나 거슬로 올라가야한다
							 mapping이 info/infolist이기 때문 -->
						<img alt="" src="../photo/no image.jpeg" width="50" height="50"
						class="img-circle">
					</c:if>
					<c:if test="${in.photo!='no' }">
						<img alt="" src="../photo/${in.photo }" width="50" height="50"
						class="img-circle">
					</c:if>
				</td>
				<td>
					${in.driver }
				</td>
				<td>
					<fmt:formatDate value="${in.gaipday }" pattern="yyyy-MM-dd"/>
				</td>
				<td>
					<button type="button" class="btn btn-outline-warning btn-sm"
					onclick="location.href='uform?num=${in.num}'">수정</button>
					<button type="button" class="btn btn-outline-danger btn-sm"
					onclick="location.href='delete?num=${in.num}'">삭제</button>
					
				</td>
			</tr>
		</c:forEach>
	</table>
	
	
	<!-- 검색기능
		 지금상태에서는 list mapping에 추가해야해서 action이 list -->
	
	<div style="width: 900px; text-align: center;">
		<form action="list" class="d-inline-flex">
			<select name="title" class="form-control" style="width: 120px;">
				<!-- title의 값이 어떤 것이냐에 따라 selected -->
				<option value="name" ${title=='name'?"selected":"" }>이름</option>
				<option value="addr" ${title=='addr'?"selected":"" }>주소</option>
				<option value="driver" ${title=='driver'?"selected":"" }>운전면허</option>
			</select>
			
			<input type="text" name="search" class="form-control"
			placeholder="검색단어" style="width: 150px;" value="${search }">
			
			<button type="submit" class="btn btn-success">검색</button>
		</form>
	</div>
	
	
</body>
</html>
profile
백엔드 개발자로서 성장해 나가는 성현이의 블로그~

0개의 댓글