现在的位置: 首页 > 综合 > 正文

Spring框架,如何返回数据给视图(jsp文件)

2013年12月06日 ⁄ 综合 ⁄ 共 2230字 ⁄ 字号 评论关闭

Author:kagula

Date: 2013-02-28

环境

[1]Tomcat 6.0.x

[2]Spring (portlet)2.5.6

内容概要

    以代码片段形式,举例,如何把数据返回给视图,并在视图中显示。这里记一下,免得以后我又忘记了。

第一步 准备返回给视图的数据

package com.cwebs.samples;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

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

import com.cwebs.common.CMySQL;
import com.cwebs.common.ConnectionInfo;

@Controller
@RequestMapping("VIEW")
public class QueryBySQLViewController {
	public ConnectionInfo ci = new ConnectionInfo(
			"jdbc:mysql://localhost:3366/test", "root", "root");	

    @RequestMapping
	public ModelAndView renderEditView(RenderRequest request, 
			RenderResponse response) throws Exception {
    	List<Map<String,String>> list=null;
		try {
			//step1:test open&close
			CMySQL db = new CMySQL(ci.connStr, ci.usr, ci.pwd);
			
			//step2:test query with return
			list=db.executeQuery("select * from babywatch");			
			db.testResult(list);		
			
		}catch(Exception ex)
		{
			ex.printStackTrace();			
		}
		
        final Map<String, Object> model = new LinkedHashMap<String, Object>();
        model.put("resultList", list);
        model.put("title", "测试表格");
		
		return new ModelAndView("SQLQueryResult", model);
	}
}

第二步 在视图中显示

<%@page contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<%@ include file="/WEB-INF/jsp/include.jsp" %>

<!-- View Mode -->

<h2>${title}</h2>

<c:choose>
	<c:when test="${empty resultList}">
	    <p>没有记录</p>
	</c:when>
	<c:otherwise>
	    <table>
	     <tr>
	      <th>ID</th><th>名字</th><th>发布日期</th>
	     </tr>	     
		<c:forEach var="result" items="${resultList}">
	     <tr>
	      <td>${result.BABYWATCH_ID}</td>
	      <td>${result.BABYWATCH_NAME}</td>
	      <td>${result.BABYWATCH_PUBLISHDATE}</td>
	     </tr>			
		</c:forEach>
		</table>
	</c:otherwise>
</c:choose>

<h2>Portlet URLs</h2>
<ul>
	<li><a href="<portlet:renderURL portletMode="view" />">View Mode</a>
	<li><a href="<portlet:renderURL portletMode="edit" />">Edit Mode</a>
	<li><a href="<portlet:renderURL portletMode="help" />">Help Mode</a>
	<li><a href="<portlet:renderURL windowState="normal" />">Normal State</a>
	<li><a href="<portlet:renderURL windowState="maximized" />">Maximized State</a>
	<li><a href="<portlet:renderURL windowState="minimized" />">Minimized State</a>
</ul>

上例在视图中显示了一个简单的表格。

抱歉!评论已关闭.