SPRING
2017.05.29 / 09:41

Spring MVC List Binding Çϱâ

½Å´Ïºñ
Ãßõ ¼ö 226

º¸Åë Web °³¹ß Çϸé Spring ÀÌ ÀÚ¿¬½º·´°Ô ¶°¿À¸¥´Ù. ±× ¸¸Å­ º¸ÆíÈ­ µÇ¾î ÀÖ´Ù. °³¹ß °æÇèÀÌ ÀÖ´Ù¸é @ModelAttribute ¶ó´Â ¾î³ëÅ×À̼ÇÀÌ Ä£¼÷ÇÒ °Í ÀÌ´Ù. ¾Æ·¡ ±×¸²À» º¸ÀÚ.



Spring À» »ç¿ëÇÏ¸é ´ëÇ¥ÀûÀ¸·Î ¶°¿À¸£´Â Servlet ÀÌ ÀÖ´Ù. Servlet ¸¦ Á÷Á¢ °³¹ß Çϸé HttpServletRequest.getParameter(String name) À» Á÷Á¢ »ç¿ëÇÏÁö¸¸, DispatcherServlet ´Â name °ª°ú Model Class ÀÇ field °¡ mapping µÇ¾î °ªÀ» ³Ö¾îÁØ´Ù. ±× ½ÃÁ¡Àº Controller È£Ã⠵DZâ Á÷Àü À̶ó°í º¸¸é µÈ´Ù. Âü Æí¸®ÇÑ ±â´É ÀÌ´Ù.


¿©±â¼­ Çѹø ´õ »ý°¢ Çغ¸ÀÚ. List ·Î ¹ÞÀ» ¼ö´Â ¾øÀ» ±î? ¿©·¯ ¹øÀÇ ½Ãµµ ³¡¿¡ ¹æ¹ýÀ» ã¾Ò´Ù.


@RequestMapping(value="/sample", method=RequestMethod.POST)
public ModelAndView sample(List<Sample> sampleList) throws Exception {
    try {
        ModelAndView mav = new ModelAndView();

        // Doing...

        return mav;
    } catch (Exception e) {
        throw e;
    }
}


Controller ¼Ò½º Áß ÀϺΠÀÌ´Ù. @ModelAttribute ´Â »ý·«ÀÌ °¡´É ÇÑ ¾î³ëÅ×ÀÌ¼Ç ÀÌ´Ù. ¹æ±Ý ¼³¸í Çß´ø mapping ÀÛ¾÷Àº Object ±âÁØÀ¸·Î ÀÌ·ç¾î Áø´Ù. °á±¹ À§ ¼Ò½º´Â ¹«¿ëÁö¹° ÀÌ´Ù. ´Ù¸¥ ¹æ¹ýÀ¸·Î Á¢±Ù ÇØ º¸ÀÚ.


public class Sample {

    private String sample1;
    private String sample2;
    private String sample3;
    private String files;

    private List<Sample> sampleList;

    // Doing...

}


Model Class ¿¡ List ·Î ¼±¾ð Çϸé mapping ÀÌ °¡´ÉÇÏ´Ù.


<table class="sample_table" border="0" cellspacing="0" summary="">
    <tr>
        <th scope="row">Sample 1</th>
        <td class="long">
            <input type="text" name="sampleList[index].sample1" />
        </td>
    </tr>
    <tr>
        <th scope="row">Sample 2</th>
        <td class="long">
            <input type="text" name="sampleList[index].sample2" />
        </td>
    </tr>
    <tr>
        <th scope="row">Sample 3</th>
        <td>
            <input type="text" name="sampleList[index].sample3" />
        </td>
    </tr>
    <tr>
        <th scope="row">Sample File</th>
        <td class="long">
            <input type="file" name="sampleList[index].files" />
        </td>
    </tr>
</table>


°ªÀº Àü´Þ ÇÏ´Â Html ÀÌ´Ù. name À» Áֽà ÇÏÀÚ. Model Class ¿¡¼­ ¼±¾ð Çß´ø List °ª°ú µ¿ÀÏ ÇÏ´Ù. ¹è¿­À» »ç¿ëÇϵí name °ªÀ» ÀÛ¼º ÇÑ´Ù.


@RequestMapping(value="/sample", method=RequestMethod.POST)
public ModelAndView sample(Sample sample) throws Exception {
    try {
        ModelAndView mav = new ModelAndView();

        logger.debug(sample.toString());

        // Doing...

        return mav;
    } catch (Exception e) {
        throw e;
    }
}


½ÇÁ¦ ¿äûÀ» ¹Þ¾Æ º¸ÀÚ. log À» º¸¸é °ªÀ» È®ÀÎ ÇÒ ¼ö ÀÖÀ» °Í ÀÌ°í, À̷μ­ ÈçÈ÷ °Ô½Ã±Û N°³ ¸¦ µ¿½Ã¿¡ µî·ÏÇÒ ¶§ »ç¿ëÇϸé Æí¸®ÇÏ°Ô Ã³¸®°¡ °¡´É ÇÏ´Ù.


Âü°í »çÀÌÆ®



Ãâó: http://blog.whitelife.co.kr/272 [White Life Story]