1概念
2指o
if, else, elseif
switch, case, default, break
list, break
include
Import
compress
escape, noescape
assign
global
setting
macro, nested, return
t, lt, rt
3一些常用方法或注意事项
表达式{换类
数字循环
ҎQ点取整数
l变量默认?nbsp;
判断对象是不是null
常用格式化日?nbsp;
d全局׃n变量数据模型
直接调用java对象的方?nbsp;
字符串处?内置Ҏ)
在模杉K对sequences和hashes初始?nbsp;
注释标志
sequences内置Ҏ
hashes内置Ҏ
4 freemarker在web开发中注意事项
web中常用的几个对象
view中值的搜烦序
在模杉Kftl里用标{?nbsp;
如何初始化共享变?nbsp;
与webwork整合配置
5高Ҏ
自定义方?nbsp;
自定?Transforms
1概念
最常用?个概?br />
sequence 序列Q对应java里的list、数l等非键值对的集?br />
hash 键值对的集?br />
namespace 对一个ftl文g的引?利用q个名字可以讉K到该ftl文g的资?/p>
2指o
if, else, elseif
语法
<#if condition>
...
<#elseif condition2>
...
<#elseif condition3>
...
...
<#else>
...
</#if>
用例
<#if x = 1>
x is 1
</#if>
<#if x = 1>
x is 1
<#else>
x is not 1
</#if>
switch, case, default, break
语法
<#switch value>
<#case refValue1>
...
<#break>
<#case refValue2>
...
<#break>
...
<#case refValueN>
...
<#break>
<#default>
...
</#switch>
用例
字符?br />
<#switch being.size>
<#case "small">
This will be processed if it is small
<#break>
<#case "medium">
This will be processed if it is medium
<#break>
<#case "large">
This will be processed if it is large
<#break>
<#default>
This will be processed if it is neither
</#switch>
数字
<#switch x>
<#case x = 1>
1
<#case x = 2>
2
<#default>
d
</#switch>
如果x=1 输出 1 2, x=2输出 2, x=3 输出d
list, break
语法
<#list sequence as item>
...
<#if item = "spring"><#break></#if>
...
</#list>
关键?br />
item_index:是list当前值的下标
item_has_next:判断list是否q有?/p>
用例
<#assign seq = ["winter", "spring", "summer", "autumn"]>
<#list seq as x>
${x_index + 1}. ${x}<#if x_has_next>,</#if>
</#list>
输出
1. winter,
2. spring,
3. summer,
4. autumn
include
语法
<#include filename>
or
<#include filename options>
options包含两个属?br />
encoding=”GBK” ~码格式
parse=true 是否作ؓftl语法解析,默认是trueQfalse是以文本方式引?注意在ftl文g里布值都是直接赋值的如parse=true,而不是parse=”true”
用例
/common/copyright.ftl包含内容
Copyright 2001-2002 ${me}<br>
All rights reserved.
模板文g
<#assign me = "Juila Smith">
<h1>Some test</h1>
<p>Yeah.
<hr>
<#include "/common/copyright.ftl" encoding=”GBK”>
输出l果
<h1>Some test</h1>
<p>Yeah.
<hr>
Copyright 2001-2002 Juila Smith
All rights reserved.
Import
语法
<#import path as hash>
cM于java里的import,它导入文Ӟ然后可以在当前文g里用被导入文g里的宏组?/p>
用例
假设mylib.ftl里定义了宏copyright那么我们在其他模杉K面里可以q样使用
<#import "/libs/mylib.ftl" as my>
<@my.copyright date="1999-2002"/>
"my"在freemarker里被UCnamespace
compress
语法
<#compress>
...
</#compress>
用来压羃I白I间和空白的?br />
用例
<#assign x = " moo \n\n ">
(<#compress>
1 2 3 4 5
${moo}
test only
I said, test only
</#compress>)
输出
(1 2 3 4 5
moo
test only
I said, test only)
escape, noescape
语法
<#escape identifier as expression>
...
<#noescape>...</#noescape>
...
</#escape>
用例
主要使用在相似的字符串变量输出,比如某一个模块的所有字W串输出都必Lhtml安全的,q个时候就可以使用该表辑ּ
<#escape x as x?html>
First name: ${firstName}
<#noescape>Last name: ${lastName}</#noescape>
Maiden name: ${maidenName}
</#escape>
相同表达?nbsp;
First name: ${firstName?html}
Last name: ${lastName }
Maiden name: ${maidenName?html}
assign
语法
<#assign name=value>
or
<#assign name1=value1 name2=value2 ... nameN=valueN>
or
<#assign same as above... in namespacehash>
or
<#assign name>
capture this
</#assign>
or
<#assign name in namespacehash>
capture this
</#assign>
用例
生成变量,q且l变量赋?br />
lseasons赋予序列?br />
<#assign seasons = ["winter", "spring", "summer", "autumn"]>
l变量test?
<#assign test = test + 1>
lmy namespage 赋予一个变量bgColor,下面可以通过my.bgColor来访问这个变?br />
<#import "/mylib.ftl" as my>
<#assign bgColor="red" in my>
一D输出的文本作ؓ变量保存在x?br />
下面的阴影部分输出的文本被赋值给x
<#assign x>
<#list 1..3 as n>
${n} <@myMacro />
</#list>
</#assign>
Number of words: ${x?word_list?size}
${x}
<#assign x>Hello ${user}!</#assign> error
<#assign x=” Hello ${user}!”> true
同时也支持中文赋|如:
<#assign 语法>
java
</#assign>
${语法}
打印输出:
java
global
语法
<#global name=value>
or
<#global name1=value1 name2=value2 ... nameN=valueN>
or
<#global name>
capture this
</#global>
全局赋D法,利用q个语法l变量赋|那么q个变量在所有的namespace中是可见?如果q个变量被当前的assign语法覆盖 ?lt;#global x=2> <#assign x=1> 在当前页面里x=2被隐藏Q或者通过${.global.x}来访?/p>
setting
语法
<#setting name=value>
用来讄整个pȝ的一个环?br />
locale
number_format
boolean_format
date_format, time_format, datetime_format
time_zone
classic_compatible
用例
假如当前是匈牙利的设|,然后修改成美?br />
${1.2}
<#setting locale="en_US">
${1.2}
输出
1,2
1.2
因ؓ匈牙利是采用“,”作ؓ十进制的分隔W,国是用“.”
macro, nested, return
语法
<#macro name param1 param2 ... paramN>
...
<#nested loopvar1, loopvar2, ..., loopvarN>
...
<#return>
...
</#macro>
用例
<#macro test foo bar="Bar" baaz=-1>
Test text, and the params: ${foo}, ${bar}, ${baaz}
</#macro>
<@test foo="a" bar="b" baaz=5*5-2/>
<@test foo="a" bar="b"/>
<@test foo="a" baaz=5*5-2/>
<@test foo="a"/>
输出
Test text, and the params: a, b, 23
Test text, and the params: a, b, -1
Test text, and the params: a, Bar, 23
Test text, and the params: a, Bar, -1
定义循环输出的宏
<#macro list title items>
<p>${title?cap_first}:
<ul>
<#list items as x>
<li>${x?cap_first}
</#list>
</ul>
</#macro>
<@list items=["mouse", "elephant", "python"] title="Animals"/>
输出l果
<p>Animals:
<ul>
<li>Mouse
<li>Elephant
<li>Python
</ul>
包含body的宏
<#macro repeat count>
<#list 1..count as x>
<#nested x, x/2, x==count>
</#list>
</#macro>
<@repeat count=4 ; c halfc last>
${c}. ${halfc}<#if last> Last!</#if>
</@repeat>
输出
1. 0.5
2. 1
3. 1.5
4. 2 Last!
t, lt, rt
语法
<#t> L左右I白和回车换?/p>
<#lt>L左边I白和回车换?/p>
<#rt>L双I白和回车换?/p>
<#nt>取消上面的效?/p>
3一些常用方法或注意事项
表达式{换类
${expression}计算expressionq输?br />
#{ expression }数字计算#{ expression ;format}安格式输出数字format为M和m
M表示数点后最多的位数,m表示数点后最的位数?{121.2322;m2M2}输出121.23
数字循环
1..5 表示??Q原型number..number
ҎQ点取整数
${123.23?int} 输出123
l变量默认?br />
${var?default(“hello world<br>”)?html}如果var is null那么会被hello world<br>替代
判断对象是不是null
<#if mouse?exists>
Mouse found
<#else>
也可以直?{mouse?if_exists})输出布尔?br />
常用格式化日?br />
openingTime必须是Date?详细查看freemarker文档 Reference->build-in referece->build-in for date
${openingTime?date}
${openingTime?date_time}
${openingTime?time}
d全局׃n变量数据模型
在代码里的实?br />
cfg = Configuration.getDefaultConfiguration();
cfg.setSharedVariable("global", "you good");
面实现可以通过global指o,具体查看指o里的global部分
直接调用java对象的方?br />
${object.methed(args)}
字符串处?内置Ҏ)
html安全输出
“abc<table>sdfsf”?html
q回安全的html输出,替换掉html代码
xml安全输出
var?xml
substring的用?br />
<#assign user=”hello jeen”>
${user[0]}${user[4]}
${user[1..4]}
输出 :
ho
ello
cMString.split的用?
“abc;def;ghi”?split(“;”)q回sequence
字W串按空D{化成sequence,然后取sequence的长?br />
var?word_list 效果?var?split(“ ”)
var?word_list?size
取得字符串长?br /> var?length
大写输出字符
var?upper_case
写输出字符
var?lower_case
首字W大?br /> var?cap_first
首字W小?br /> var?uncap_first
L字符串前后空?
var?trim
每个单词的首字符大写
var?capitalize
cMString.indexof:
“babcdabcd”?index_of(“abc”) q回1
“babcdabcd”?index_of(“abc”,2) q回5
cMString.lastIndexOf
last_index_of和String.lastIndexOfcM,同上
下面两个可能在代码生成的时候用(在引号前?#8221;\”Q?br />
j_string: 在字W串引号前加”\”
<#assign beanName = 'The "foo" bean.'>
String BEAN_NAME = "${beanName?j_string}";
打印输出:
String BEAN_NAME = "The \"foo\" bean.";
js_string:
<#assign user = "Big Joe's \"right hand\".">
<script>
alert("Welcome ${user}!");
</script>
打印输出
alert("Welcome Big Joe\'s \"right hand\"!");
替换字符?replace
${s?replace(‘ba’, ‘XY’ )}
${s?replace(‘ba’, ‘XY’ , ‘规则参数’)}s里的所有的ba替换成xy 规则参数包含: i r m s c f 具体含义如下:
· i: 大小写不区分.
· f: 只替换第一个出现被替换字符串的字符?br />
· r: XY是正则表辑ּ
· m:
Multi-line mode for regular expressions. In multi-line mode the
expressions ^ and $ match just after or just before, respectively, a
line terminator or the end of the string. By default these expressions
only match at the beginning and the end of the entire string.
· s:
Enables dotall mode for regular expressions (same as Perl singe-line
mode). In dotall mode, the expression . matches any character,
including a line terminator. By default this expression does not match
line terminators.
· c: Permits whitespace and comments in regular expressions.
在模杉K对sequences和hashes初始?br />
sequences
1. [“you”,”me”,”he”]
2. 1..100
3. [ {“Akey”:”Avalue”},{“Akey1”:”Avalue1”},
{“Bkey”:”Bvalue”},{“Bkey1”:”Bvalue1”},
]
hashes {“you”:”a”,”me”:”b”,”he”:”c”}
注释标志
<#--
q里是注?
-->
旧版本的freemarker采用的是<#comment> 注释 </#comment>Ҏ
sequences内置Ҏ
sequence?first
q回sequence的第一个?前提条gsequence不能是null
sequence?last
q回sequence最后一个?br />
sequence?reverse
反{sequence的?br />
sequence?size
q回sequence的大?br />
sequence?sort
对sequence按里面的对象toString()的结果进行排?br />
sequence?sort_by(value)
对sequence 按里面的对象的属性valueq行排序
? sequence里面攑օ的是10 个user对象Quser对象里面包含name,age{属?br />
sequence?sort_by(name) 表示所有的user按user.nameq行排序
hashes内置Ҏ
hash?keys
q回hash里的所有keys, q回l果cdsequence
hash?values
q回hash里的所有value, q回l果cdsequence
4 freemarker在web开发中注意事项
freemarker与webwork整合
web中常用的几个对象
Freemarker的ftl文g中直接用内部对?
${Request ["a"]}
${RequestParameters["a"]}
${Session ["a"]}
${Application ["a"]}
${JspTaglibs ["a"]}
与webwork整合之后 通过配置的servlet 已经把request,session{对象置入了数据模型?br />
在view中存在下面的对象
我们可以在ftl?{req}来打印req对象
· req - the current HttpServletRequest
· res - the current HttpServletResponse
· stack - the current OgnlValueStack
· ognl - the OgnlTool instance
· webwork - an instance of FreemarkerWebWorkUtil
· action - the current WebWork action
· exception - optional the Exception instance, if the view is a JSP exception or Servlet exception view
view中值的搜烦序
${name}会以下面的序查找name?br />
· freemarker variables
· value stack
· request attributes
· session attributes
· servlet context attributes
在模杉Kftl里用标{?br />
注意Q如果标{属性值是数字Q那么必采用nubmer=123方式l属性赋?br />
JSP面
<%@page contentType="text/html;charset=ISO-8859-2" language="java"%>
<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<html>
<body>
<h1><bean:message key="welcome.title"/></h1>
<html:errors/>
<html:form action="/query">
Keyword: <html:text property="keyword"/><br>
Exclude: <html:text property="exclude"/><br>
<html:submit value="Send"/>
</html:form>
</body>
</html>
模板ftl面
<#assign html=JspTaglibs["/WEB-INF/struts-html.tld"]>
<#assign bean=JspTaglibs["/WEB-INF/struts-bean.tld"]>
<html>
<body>
<h1><@bean.message key="welcome.title"/></h1>
<@html.errors/>
<@html.form action="/query">
Keyword: <@html.text property="keyword"/><br>
Exclude: <@html.text property="exclude"/><br>
<@html.submit value="Send"/>
</@html.form>
</body>
</html>
如何初始化共享变?br />
1Q?nbsp;初始化全局׃n数据模型
freemark在web上用的时候对׃n数据的初始化支持的不?不能在配|初始化的时候实玎ͼ而必通过ftl文g来初始化全局变量。这是不能满主需求的Q我们需要在servlet init的时候留Z个接口来初始化系l的׃n数据
?
体到和webwork整合,因ؓ本nwebwork提供了整合servlet,如果要增加全局׃n变量Q可以通过修改
com.opensymphony.webwork.views.freemarker.FreemarkerServlet来实?我们可以在这?
servlet初始化的时候来初始化全局׃n变量
与webwork整合配置
配置web.xml
<servlet>
<servlet-name>freemarker</servlet-name>
<servlet-class>com.opensymphony.webwork.views.freemarker.FreemarkerServlet</servlet-class>
<init-param>
<param-name>TemplatePath</param-name>
<param-value>/</param-value>
<!—模板蝲入文件夹Q这里相对context rootQ递归获取该文件夹下的所有模?->
</init-param>
<init-param>
<param-name>NoCache</param-name> <!—是否对模板~存-->
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>ContentType</param-name>
<param-value>text/html</param-value>
</init-param>
<init-param>
<param-name>template_update_delay</param-name>
<!—模板更新时?0表示每次都更?q个适合开发时?->
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>default_encoding</param-name>
<param-value>GBK</param-value>
</init-param>
<init-param>
<param-name>number_format</param-name>
<param-value>0.##########</param-value><!—数字显C格?->
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>freemarker</servlet-name>
<url-pattern>*.ftl</url-pattern>
</servlet-mapping>
5高Ҏ
自定义方?br />
${timer("yyyy-MM-dd H:mm:ss", x)}
${timer("yyyy-MM-dd ", x)}
在模板中除了可以通过对象来调用方法外Q?{object.methed(args)}Q也可以直接调用java实现的方法,javacdd现接
口TemplateMethodModel的方法exec(List args). 下面以把毫秒的时间{换成按格式输出的旉Z?br />
public class LongToDate implements TemplateMethodModel {
public TemplateModel exec(List args) throws TemplateModelException {
SimpleDateFormat mydate = new SimpleDateFormat((String) args.get(0)));
return mydate.format(new Date(Long.parseLong((String)args.get(1)));
}
}
LongToDate对象攑օ到数据模型中
root.put("timer", new IndexOfMethod());
ftl模板里?br />
<#assign x = "123112455445">
${timer("yyyy-MM-dd H:mm:ss", x)}
${timer("yyyy-MM-dd ", x)}
输出
2001-10-12 5:21:12
2001-10-12
自定?Transforms
实现自定义的<@transform>文本或表辑ּ</@transform>的功?允许对中间的最l文本进行解析{?/p>
例子Q实?lt;@upcase>str</@upcase> str转换成STR 的功?/p>
代码如下Q?br />
import java.io.*;
import java.util.*;
import freemarker.template.TemplateTransformModel;
class UpperCaseTransform implements TemplateTransformModel {
public Writer getWriter(Writer out, Map args) {
return new UpperCaseWriter(out);
}
private class UpperCaseWriter extends Writer {
private Writer out;
UpperCaseWriter (Writer out) {
this.out = out;
}
public void write(char[] cbuf, int off, int len)
throws IOException {
out.write(new String(cbuf, off, len).toUpperCase());
}
public void flush() throws IOException {
out.flush();
}
public void close() {
}
}
}
然后此对象put到数据模型中
root.put("upcase", new UpperCaseTransform());
在view(ftl)面中可以如下方式?/p>
<@upcase>
hello world
</@upcase>
Ҏ二:通过Spring提供的工L获取ApplicationContext对象
代码Q?br />
import org.springframework.web.context.support.WebApplicationContextUtils;
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc);
ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);
ac1.getBean("beanId");
ac2.getBean("beanId");
说明Q?br />
q种方式适合于采用Spring框架的B/SpȝQ通过ServletContext对象获取ApplicationContext对象Q然后在通过它获取需要的cd例?/p>
上面两个工具方式的区别是Q前者在获取p|时抛出异常,后者返回null?/span>
其中 servletContext sc 可以具体 换成 servlet.getServletContext()或? this.getServletContext() 或?request.getSession().getServletContext(); 另外Q由于spring是注入的对象攑֜ServletContext中的Q所以可以直接在ServletContext取出 WebApplicationContext 对象Q? WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
Ҏ三:l承自抽象类ApplicationObjectSupport
说明Q抽象类ApplicationObjectSupport提供getApplicationContext()ҎQ可以方便的获取到ApplicationContext?br />
Spring初始化时Q会通过该抽象类的setApplicationContext(ApplicationContext context)ҎApplicationContext 对象注入?/p>
Ҏ四:l承自抽象类WebApplicationObjectSupport
说明Q类g面方法,调用getWebApplicationContext()获取WebApplicationContext
ibatis和Spring整合的详l例?数据库用的是mysql,开发环境是Eclipse3.2:
1.首先把用到的包导入进?此例用的是spring-framework-1.2.7,iBATIS_DBL-2.1.7.597,mysql的数
据库q接包用的是mysql-connector-java-5.0.3-bin.jar.
2.建POJOc?在此我们用的是一个Studentc?
package cn.itcast;
public class Student implements java.io.Serializable {
private Integer id;
private String firstname;
private String lastname;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
3.POJO的映文件Student.xml,在这里面只有两个功能,x据student的id索出一个Student对象,另一
个就是向数据库插入一条记?一个Student对象),注意:此应用程序中所有的配置文g(xml文g?br />
properties文g都放在configfile包下?.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "
<!--q是POJO映射文g的根元素-->
<sqlMap namespace="Student">
<!--select元素的id属性用来标识此元素,resultClass属性的值是Javacȝ全限定名Q即包括cȝ包名Q?br />
resultClass属性可以让您指定一个Javac,ҎResultSetMetaData其自动映射到JDBC的ResultSet?br />
只要是Java Bean的属性名U和ResultSet的列名匹配,属性自动赋值给列倹{?br />
parameterClass属性是参数的类?此属性的值是Javacȝ全限定名Q即包括cȝ包名Q?br />
它是可选的Q但强烈使用。它的目的是 限制输入参数的类型ؓ指定的Javac,q?br />
优化框架的性能?->
<select id="getStudentById" resultClass="cn.itcast.Student" parameterClass="int">
select id,firstname,lastname from student where id=#value#
</select>
<insert id="insertStudent" parameterClass="cn.itcast.Student">
insert into student(firstname,lastname) values(#firstname#,#lastname#)
</insert>
</sqlMap>
4.Z个SqlMap的配|文件sql-map-config.xml,sqlMap元素的resource属性告诉Springd找POJO映射文g.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN"
"
<sqlMapConfig>
<sqlMap resource="configfile/Student.xml" />
</sqlMapConfig>
5.jdbc.properties文g,存储数据库连接的driver,url,username,password{信?
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/itcast
jdbc.username=root
jdbc.password=
6.Spring配置文gapplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "
<beans>
<!--此bean告诉Springd找数据库的配|信?因ؓ有此Bean才出C面用${}标记来取变量的语?->
<bean id="propertyConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>configfile/jdbc.properties</value>
</property>
</bean>
<!--配置一个数据源,Ҏ上面propertyConfig指定的locationL数据库连接的配置信息-->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${jdbc.driver}</value>
</property>
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
<!--ҎdataSource和configLocation创徏一个SqlMapClient-->
<bean id="sqlMapClient"
class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation">
<value>configfile/sql-map-config.xml</value>
</property>
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<!--ҎsqlMapClien创徏一个SqlMapClient模版c?->
<bean id="sqlMapClientTemplate"
class="org.springframework.orm.ibatis.SqlMapClientTemplate">
<property name="sqlMapClient">
<ref bean="sqlMapClient" />
</property>
</bean>
<!--上面的模版cȝ入到我们的DAO对象?->
<bean id="studentDao" class="cn.itcast.StudentDaoSqlMap">
<property name="sqlMapClientTemplate">
<ref bean="sqlMapClientTemplate" />
</property>
</bean>
</beans>
7.StudentDaoSqlMap 是一个DAO,它负责和数据库的交互,在这里实C查询单条记录和插入单条记录的功能.
package cn.itcast;
import org.springframework.orm.ibatis.SqlMapClientTemplate;
public class StudentDaoSqlMap {
//[1]
private SqlMapClientTemplate sqlMapClientTemplate;
public SqlMapClientTemplate getSqlMapClientTemplate() {
return sqlMapClientTemplate;
}
public void setSqlMapClientTemplate(
SqlMapClientTemplate sqlMapClientTemplate) {
this.sqlMapClientTemplate = sqlMapClientTemplate;
}
//此方法的q回gStudent.xml的select元素的resultClass对应.
public Student getStudent(Integer id) {
return (Student) sqlMapClientTemplate.queryForObject("getStudentById",id);
//注意:queryForObjectҎq回一个Object,W一个参CStudent.xml的select元素
//的id属性值对?W二个参数的cd与Student.xml的select元素的parameterClass
//属性值对?
}
public Object insertStudent(Student student) {
return sqlMapClientTemplate.insert("insertStudent", student);
}
}
8.下面写一个带main函数的类来测试上面的代码.代码非常单就不再解释?
package cn.itcast;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String[] args) {
//[2]
ApplicationContext factory = new ClassPathXmlApplicationContext(
"applicationContext.xml");
StudentDaoSqlMap studentDao = (StudentDaoSqlMap) factory
.getBean("studentDao");
//插入一个student
Student student = new Student();
student.setFirstname("tian");
student.setLastname("xiangdong");
studentDao.insertStudent(student);
//查询出id?的Student对象.
//Student student = studentDao.getStudent(1);
//System.out.println(student.getId());
//System.out.println(student.getFirstname());
//System.out.println(student.getLastname());
}
}