BACK END/java spring(egov)

4. spring 검색창으로 원하는 항목 찾기

자코린이 2022. 3. 30. 18:59

전 전에 사용하던 코드를 약간 변경하는 정도로 만들었습니다.

 

SeachVO를 만듭니다. 이는 검색할 때 필요한 타입, 내용을 받아오는 항목입니다.

 

getter setter의 단축키는 alt + shift + s입니다.

package egovframework.example.sample.vo;

public class SearchVO {
	 private String searchType;
	 private String keyword;
	 public String getSearchType() {
		return searchType;
	}
	public void setSearchType(String searchType) {
		this.searchType = searchType;
	}
	public String getKeyword() {
		return keyword;
	}
	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}
}

 

Mapper.xml을 고쳐줍니다.

이는 jsp에서 타입, 내용을 받아 where조건에 넣기 위한 과정입니다.

설정파일을 건드렸으므로 clean을 해줍니다.

<?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파일로 바꾸어 줍니다.  -->
<mapper namespace="egovframework.example.sample.service.StockMapper">
  <select id="selectStock" resultType="egovframework.example.sample.vo.StockVO">
          SELECT * FROM stock
        <where>
            <if test="searchType=='code' and keyword != null and keyword !=''">
                AND code like CONCAT('%',#{keyword},'%')
            </if>
            <if test="searchType=='barcode' and keyword != null and keyword !=''">
                AND barcode like CONCAT('%',#{keyword},'%')
            </if>
            <if test="searchType=='partname' and keyword != null and keyword !=''">
                AND partname like CONCAT('%',#{keyword},'%')
            </if>
        </where>
        limit 100
        
    </select>
    
    
</mapper>

 

controller

컨트롤러에서 타입, 내용을 받아 처리하고 jsp에 데이터를 넘겨줍니다.

package egovframework.example.sample.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import egovframework.example.sample.service.StockService;
import egovframework.example.sample.vo.SearchVO;
import egovframework.example.sample.vo.StockVO;

@Controller
public class StockController {
    @Autowired
    private StockService stockService;
    
    @RequestMapping(value="/stockList.do")
    public String testListDo(Model model
    		,@RequestParam(required=false,defaultValue="testTitle")String searchType
            ,@RequestParam(required=false)String keyword
            ,@ModelAttribute("search")SearchVO searchVo)throws Exception{
      
    	
    	model.addAttribute("search", searchVo);
    	searchVo.setSearchType(searchType);
    	searchVo.setKeyword(keyword);
        
        model.addAttribute("list", stockService.selectStock(searchVo));


        
        
        return "stockList";
    }

}

 

Service

컨트롤러를 도와주는 파일들입니다.

package egovframework.example.sample.service;

import java.util.List;

import egovframework.example.sample.vo.SearchVO;
import egovframework.example.sample.vo.StockVO;

public interface StockService {
	 public List<StockVO> selectStock(SearchVO searchVo) throws Exception;
}

 

ServiceImpl

package egovframework.example.sample.service.impl;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import egovframework.example.sample.dao.StockDAO;
import egovframework.example.sample.service.StockService;
import egovframework.example.sample.vo.SearchVO;
import egovframework.example.sample.vo.StockVO;

@Service
public class StockServiceImpl implements StockService{
 
    @Autowired
    private StockDAO stockDao;
    
    @Override
    public List<StockVO> selectStock(SearchVO searchVo) throws Exception {
        return stockDao.selectStock(searchVo);
    }
 
}

 

DAO

DB에 직접 접속하여 결과를 객체배열인 List<VO> 형식으로 넘겨주고 있습니다.

package egovframework.example.sample.dao;

import java.util.List;

import egovframework.example.sample.vo.SearchVO;
import egovframework.example.sample.vo.StockVO;

public interface StockDAO {
	  public List<StockVO> selectStock(SearchVO searchVo) throws Exception;

	 
}

 

DAOImpl

package egovframework.example.sample.dao.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import egovframework.example.sample.dao.StockDAO;
import egovframework.example.sample.service.StockMapper;
import egovframework.example.sample.vo.SearchVO;
import egovframework.example.sample.vo.StockVO;

@Repository
public class StockDAOImpl implements StockDAO {
 
    @Autowired
    private SqlSession sqlSession;
    
    @Override
    public List<StockVO> selectStock(SearchVO searchVo) throws Exception {
        StockMapper mapper = sqlSession.getMapper(StockMapper.class);
        return mapper.selectStock(searchVo);
    }
 
}

 

Mapper

mapper.xml 과 연결해주는 인터페이스입니다.

package egovframework.example.sample.service;

import java.util.List;

import egovframework.example.sample.vo.SearchVO;
import egovframework.example.sample.vo.StockVO;

public interface StockMapper {
	List<StockVO> selectStock(SearchVO searchVo) throws Exception;


}

 

.jsp 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>Board List</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
    
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js" integrity="sha384-q2kxQ16AaE6UbzuKqyBE9/u/KzioAlnx2maXQHiDX9d4/zp8Ok3f+M7DPm+Ib6IU" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.min.js" integrity="sha384-pQQkAEnwaBkjpqZ8RU1fF1AKtTcHJwFl3pblpTlHXybJjHpMYo79HY3hIi4NKxyj" crossorigin="anonymous"></script>
<style type="text/css">
a{
 text-decoration: auto;
}
</style>
</head>
<body>
 <br/>
    <h1 class="text-center">Stock List</h1>
    <br/>
    <br/>
    <div class="container">
        <table class="table table-hover table-striped text-center" style="border:1px solid;">
				<colgroup>
					<col width="20" />
					<col width="10%" />
					<col width="10%" />
					<col width="20%" />
					<col width="10%" />
					<col width="10%" />
					<col width="10%" />
					<col width="10%" />
				</colgroup>
				<tbody>
				<thead>

					<tr>
						<th>분류항복</th>
						<th>코드</th>
						<th>바코드</th>
						<th>제품이름</th>
						<th>용량</th>
						<th>박스당 갯수</th>
						<th>박스 수</th>
						<th>낱개</th>
					</tr>
				</thead>

<!-- jstl 데이터베이스를 검색해 넘겨 받은 list 를 result 라는 이름으로 순차적으로 실행을 시키게 됨  java의 for문같이 순차적으로 실행시킴-->
			 
          <c:forEach items="${list }" var="result">
					<tr>
						<td><c:out value="${result.kind}" /></td>
						<td><c:out value="${result.code}" /></td>
						<td><c:out value="${result.barcode}" /></td>
						<td><c:out value="${result.partname}" /></td>
						<td><c:out value="${result.std}" /></td>
						<td><c:out value="${result.qtybox}" /></td>
						<td><c:out value="${result.box}" /></td>
						<td><c:out value="${result.stock}" /></td>
					</tr>
				</c:forEach>
	
				</tbody>
			</table>
        <hr/>
	        <div class="form-group row">
 
            <div class="w100" style="padding-right: 10px">
                <select class="form-control form-control-sm" name="searchType" id="searchType">
                    <option value="code">코드</option>
                    <option value="barcode">바코드</option>
                    <option value="partname">제품이름</option>
                </select>
            </div>
 
            <div class="w300" style="padding-right: 10px">
                <input type="text" class="form-control form-control-sm" name="keyword" id="keyword">
            </div>
 
            <div>
                <button class="btn btn-sm btn-primary" name="btnSearch" id="btnSearch">검색</button>
            </div>
 
        </div>



    </div>
    <br>

</body>
<script type="text/javascript">
        
    // 검색
    $(document).on('click', '#btnSearch', function(e){
        e.preventDefault();
        var url = "/stockList.do";
        url += "?searchType=" + $('#searchType').val();
        url += "&keyword=" + $('#keyword').val();
        location.href = url;
     
 
    });    
 
    </script>
</html>

 

여기까지가 검색입니다.

참조: https://ivory-room.tistory.com/63?category=875739 

 

전자정부프레임워크기반 게시판 만들기 (5) 페이징,검색

Pagination과 Search 클래스 추가 페이징,검색 참고 블로그 : freehoon.tistory.com/112?category=735500 Spring 블로그 만들기 - 9. 페이징(pagination) 이 포스팅의 샘플 게시판 개발 환경은 MAC OS, STS, Open..

ivory-room.tistory.com