반응형

Spring MVC Form Handling Example


(원문 위치 : http://www.tutorialspoint.com/spring/spring_mvc_form_handling_example.htm )

이번 강좌는 Spring Web MVC framework를 사용하여 HTML 폼을 사용하는 웹기반 프로그램을 작성하는 방법을 알아본다. 

[21-1] 강좌를 참고하여 Spring MVC project를 생성한다.

src/main/java/com/tutorialspoint/hellweb 폴더에 아래 파일을 추가한다.

Student.java:

package com.tutorialspoint.HelloWebForm;


public class Student {

  private Integer age;

  private String name;

  private Integer id;


  public void setAge(Integer age) {

      this.age = age;

  }

  public Integer getAge() {

      return age;

  }


  public void setName(String name) {

      this.name = name;

  }

  public String getName() {

      return name;

  }


  public void setId(Integer id) {

      this.id = id;

  }

  public Integer getId() {

      return id;

  }

}


StudentController.java:

package com.tutorialspoint.HelloWebForm;


import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.servlet.ModelAndView;


@Controller

public class StudentController {

  @RequestMapping(value = "/student", method = RequestMethod.GET)

  public ModelAndView student() {

      return new ModelAndView("student", "command", new Student());

  }

   

  @RequestMapping(value = "/addStudent", method = RequestMethod.POST)

  public String addStudent(@ModelAttribute("SpringWeb")Student student

  ModelMap model) {

      model.addAttribute("name", student.getName());

      model.addAttribute("age", student.getAge());

      model.addAttribute("id", student.getId());

     

      return "result";

  }

}


첫번째 service method인 student(). Spring framework는 JSP file에서 <form:form> 태르르 사용하면 'command'라는 이름을 가진 객체를 원하기 때문에(expect)'command'라는 이름으로 ModelAndView객체에서 빈(blank) Student 객체를 전달하였다. 그러면 student() 함수가 추출되어질 때 student.jsp view를 반환한다.


두번째 service method인 addStudent()는 HelloWeb/addStudent URL에서 POST method에 대응하여 호출되어질 것이다. 전송되어진(Submitted) 정보를 바탕으로 model 객체가 준비될 것이다. 마지막으로 'result' view는 result.jsp rendering에서 일어날(result) service method에서 반환되어질 것이다.


web.xml : 

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">


<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>/WEB-INF/spring/root-context.xml</param-value>

</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>


<!-- Processes application requests -->

<servlet>

<servlet-name>appServlet</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>appServlet</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>

</web-app>


Servlet-context.xml : 

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/mvc"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:beans="http://www.springframework.org/schema/beans"

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd

http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->

<annotation-driven />


<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->

<resources mapping="/resources/**" location="/resources/" />


<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->

<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<beans:property name="prefix" value="/WEB-INF/views/" />

<beans:property name="suffix" value=".jsp" />

</beans:bean>

<context:component-scan base-package="com.tutorialspoint.HelloWebForm" />


</beans:beans>


student.jsp :

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>

<head>

    <title>Spring MVC Form Handling</title>

</head>

<body>


<h2>Student Information</h2>

<form:form method="POST" action="/HelloWebForm/addStudent">

   <table>

    <tr>

        <td><form:label path="name">Name</form:label></td>

        <td><form:input path="name" /></td>

    </tr>

    <tr>

        <td><form:label path="age">Age</form:label></td>

        <td><form:input path="age" /></td>

    </tr>

    <tr>

        <td><form:label path="id">id</form:label></td>

        <td><form:input path="id" /></td>

    </tr>

    <tr>

        <td colspan="2">

            <input type="submit" value="Submit"/>

        </td>

    </tr>

</table>  

</form:form>

</body>

</html>


result.jsp :

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>

<head>

    <title>Spring MVC Form Handling</title>

</head>

<body>


<h2>Submitted Student Information</h2>

   <table>

    <tr>

        <td>Name</td>

        <td>${name}</td>

    </tr>

    <tr>

        <td>Age</td>

        <td>${age}</td>

    </tr>

    <tr>

        <td>ID</td>

        <td>${id}</td>

    </tr>

</table>  

</body>

</html>


실행 결과는 아래와 같다. (원격환경이기때문에 ip를 사용했지만, local인 경우 localhost로 사용하면 된다.)


http://10.211.55.23:8080/HelloWeb <- 기본으로 생성되는 페이지



http://10.211.55.23:8080/HelloWeb/student



정보를 입력하고 'Submit'을 누른 결과는 아래와 같다.





반응형

+ Recent posts