webwork2+FreeMarker 制作数据列表显示简单实例
刚刚接触了FreeMarker觉得不错做了个小例子
首先建立个数据表里面有username,password两个字段自己随便加几条数据建立一个webwork action TestAction.java在xwork.xml里加入如下内容---------------------------------------- <action name="test" class="com.action.TestAction"> <result name="success" type="freemarker">/test.flt</result> </action> ----------------------------------------TestAction.java代码如下--------------------------------------------------package com.action;
import com.opensymphony.xwork.ActionSupport;import java.util.*;import com.ResultGather;
public class TestAction extends ActionSupport { private List lis; private ResultGather rs; public List getLis() { return this.lis; } public String execute() throws Exception { rs = new ResultGather(); lis = rs.selectRS("select * from userbasedatum");//数据结果我是用List,HashMap封装的,HashMap存的是单条记录 return SUCCESS; }}
-------------------------------------------------------------------------------------------------------------------ResultGather.java代码如下----------------------------------------------------------package com;
import conn.DBConnManager;//数据库连接池import java.sql.*;import java.util.*;
public class ResultGather { private String sql; public ResultGather() { } public ResultGather(String sqlcom) { this.sql=sqlcom; } public List selectRS(String sqlStr) { this.sql = sqlStr; return selectRS(); } public List selectRS() //数据结果在这里装入List和Map { List rsall = new ArrayList(); DBConnManager conn = null; Connection con = null; Statement stmt = null; ResultSet rs = null; Map rsTree; try{ conn = DBConnManager.getInstance(); con = conn.getConnection("mssql"); stmt = con.createStatement(); rs = stmt.executeQuery(sql); ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); while(rs.next()) { rsTree = new HashMap(numberOfColumns); for(int r=1;r<numberOfColumns+1;r++) { rsTree.put(rsmd.getColumnName(r),rs.getObject(r)); } rsall.add(rsTree); } }catch(java.lang.Exception ex){ ex.printStackTrace(); }finally{ try{ if(rs!=null) rs.close(); if(stmt!=null) stmt.close(); if(conn!=null) conn.releaseConnection("mssql",con); }catch(Exception e){ System.out.println(e); } } return rsall; } }-----------------------------------------------------------------------------------------------test.flt代码如下-----------------------------------------------------------------------------------------<#list lis as x>${x.username},${x.password}<br></#list> //freemarker用法网上有相关介绍-------------------------------------------------------------------------------------
OK 完成了 没有用到jsp<%.....%>和jsptag用这个例子做一点修改就可以具有分页用能了
补充:Jsp教程,Java技巧及代码