欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringMVC中ModelAndView的使用

程序员文章站 2024-02-27 20:45:15
...

例子:
SpringMVC中ModelAndView的使用

MAVTest.java

package com.wyl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * ModelAndView测试,
 * 
 */
@Controller
public class MAVTest {

    public MAVTest() {
        // TODO Auto-generated constructor stub
    }

    @RequestMapping(value = "login")
    public ModelAndView login() {
        System.out.println("MAVTest.java login()....");
        ModelAndView mav = new ModelAndView();
        mav.setViewName("welcome");
        mav.addObject("msg", "hello kitty");

        // List
        List<String> list = new ArrayList<String>();
        list.add("java");
        list.add("c++");
        list.add("oracle");
        mav.addObject("bookList", list);

        // Map
        Map<String, String> map = new HashMap<String, String>();
        map.put("zhangsan", "北京");
        map.put("lisi", "上海");
        map.put("wangwu", "深圳");
        mav.addObject("map", map);

        return mav;
    }
}

welcome.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>welcome页面</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>  
   <!-- 输出普通字符 -->  
   ${msg } <br/>  
   <!-- 输出List -->  
   <p>书籍列表</p>  
   <c:forEach items="${bookList}" var="node">  
        <c:out value="${node}"></c:out>  
   </c:forEach>  
   <br/>  
   <br/>  

   <!-- 输出Map -->  
   <c:forEach items="${map}" var="node">  
        姓名:<c:out value="${node.key}"></c:out>  
        住址:<c:out value="${node.value}"></c:out>  
        <br/>  
   </c:forEach>  
</body>  
</html>

注意:c标签所依赖的jar,jstl.jar,commons-el.jar,standard.jar

项目结构:
SpringMVC中ModelAndView的使用

相关标签: spring mvc