홈페이지 최상단 카테고리(title)에 따른 search창을 spring에서 구현
<select id="selectAllOfHoewon" resultType="hdto" parameterMap="Map"> <!-- 파라메터타입이 2개 이상이면 map을 적어준다 -->
select * from hoewon
<if test="search!=null"> <!-- mybatis는 if문 사용가능 -->
where ${title} like concat('%',#{search},'%')
</if>
order bt num asc
</select>
sql문 작성 search에 값이 있을 때 search 값과 % 를 concat으로 묶어 조회한다.
public interface HoewonDaoInter {
public List<HoewonDto> getAllDatas(Map<String, String> map);
}
파라메타가 2개이상 들어가있으므로 Map방식으로 넘긴다
@Repository
public class HoewonDao implements HoewonDaoInter {
@Autowired
private SqlSession session;
@Override
public List<HoewonDto> getAllDatas(Map<String, String> map) {
// TODO Auto-generated method stub
return session.selectList("selectAllOfHoewon",map);
}
}
매퍼에서 지정한 'selectAllOfHoewon' 값 입력
@Controller
public class HoewonController {
@Autowired
HoewonDaoInter dao;
//폼으로이동
@GetMapping("/hoewon/form")
public String form()
{
return "hoewon/addform";
}
//리스트로이동(ModelAndView)
@GetMapping("/hoewon/list")
public ModelAndView list(
//리스트 검색 //defaultValue = "name" 초기값은 이름, required = false 없어도 검색됨
@RequestParam (defaultValue = "name") String title,
@RequestParam (required = false)String search
)
{
ModelAndView model=new ModelAndView();
int totalCount=dao.getTotalCount();
System.out.println(title+","+search);
Map<String, String> map=new HashMap<String, String>();
map.put("title", title);
map.put("search", search);
List<HoewonDto> list=dao.getAllDatas(map);
//request에 저장
model.addObject("list", list);
model.addObject("totalCount", totalCount);
//포워드
model.setViewName("hoewon/list");
return model;
}
}
default값을 name으로 준다. required = false를 줌으로써 검색어가 없어도 검색 가능하도록 함.
<!-- 검색창 폼 -->
<div style="width: 700px; text-align: center;">
<form action="list">
<select name="title" class="form-inline" style="width: 120px;">
<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: 120px;"
value="${search }">
<button type="submit" class="btn btn-info">검색</button>
</form>
</div>
title 속성을 3항연산자로 넣어 검색기능 구현.