spring mvc +freemarker的项目中,我们想要在html页面上利用自定义标签,来方便完成我们的一些功能,除了在页面上定义标签外,我们还可以利用程序来定义。
首先要写一个类UpperDirective.Java来实现TemplateDirectiveModel接口,
代码如下:
[java] view plain copy
public class UpperDirective implements TemplateDirectiveModel {
@Override
public void execute(Environment env, Map map, TemplateModel[] templateModels,
TemplateDirectiveBody body) throws TemplateException, IOException {
if(!map.isEmpty()){
throw new TemplateModelException("this directive doesn't allow parameters");
}
if(templateModels.length!=0){
throw new TemplateModelException("this directive doesn't allow variables");
}
if(body!=null){
body.render(new UpperCaseFilterWriter(env.getOut()));
}else{
throw new RuntimeException("missing body");
}
}
}
class UpperCaseFilterWriter extends Writer{
private final Writer out;
public UpperCaseFilterWriter(Writer out) {
this.out=out;
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
char[] transformedCbuf = new char[len];
for(int i=0;i
transformedCbuf[i]=Character.toUpperCase(cbuf[i+off]);
}
out.write(transformedCbuf);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
out.close();
}
}
然后在配置文件中进行配置:
[html] view plain copy
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
/ftl/
zh_CN
UTF-8
yyyy-MM-dd
HH:mm:ss
yyyy-MM-dd HH:mm:ss
0.################
在页面上输出的标签:hh@upper> 就能输出大写的:HH了。
http://blog.csdn.net/uk8692/article/details/38176263