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

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> 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 model = new LinkedHashMap();
        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" %>



${title}

没有记录

ID名字发布日期
${result.BABYWATCH_ID} ${result.BABYWATCH_NAME} ${result.BABYWATCH_PUBLISHDATE}

Portlet URLs


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


你可能感兴趣的:(Java)