ModelAndView : org.springframework.web.servlet.ModelAndView 클래스는 컨트롤러의 처리 결과를 보여 줄 뷰와 뷰에 전달할 값을 저장하는 용도

  ● setViewName(String viewName)

  ● addObject(String name, Object value)

  ● addAllObjects(Map modelMap)

 

 

HelloController.java

package sp.mvc.controller;

import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

 

@Controller
public class HelloController {


 @RequestMapping("/model1.sp")
 public ModelAndView test1(){
  System.out.println("----- HelloController.test1() -----");
  
  ModelAndView modelAndView = new ModelAndView();
  modelAndView.setViewName("modelPrt");
  modelAndView.addObject("msg1", "hi~");
  modelAndView.addObject("msg2", "snoopy");

  return modelAndView;
 }
 
 @RequestMapping("/model2.sp")
 public ModelAndView test2(){
  System.out.println("----- HelloController.test2() -----");

  Map<String, String> fruitMap = new HashMap<String, String>();
  fruitMap.put("apple", "사과");
  fruitMap.put("banana", "바나나");
  
  ModelAndView modelAndView = new ModelAndView("modelPrt");
  modelAndView.addObject("msg1", "hi~~~~");
  modelAndView.addObject("fruitMap", fruitMap);
  
  return modelAndView;
 }
}

 

main_config.xml

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

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <context:annotation-config/>
 <context:component-scan base-package="sp.mvc.controller"/>
 
 <!-- ViewResolver 설정 -->
 <bean id="internalResource" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="jsp/"></property>
  <property name="suffix" value=".jsp"></property>
 </bean>


 <!-- 각종 bean 설정 -->

 
</beans>

 

modelPrt.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>출력 테스트</title>
</head>
<body>
<h2>${msg1}</h2>
<h1>${msg2}</h1>

<c:forEach var="fruit" items="${fruitMap}">
 ${fruit.key}
</c:forEach>


</body>
</html>

 

 

 

결과

 

 

 

[참고자료] Spring 3.0 프로그래밍-최범균

+ Recent posts