关于三种jsp、freemarker、velocity模板语言优缺点对比及示例代码演示下载

http://www.xwood.net/_site_domain_/_root/5870/5874/t_c255568.html

前言

在java中表现层实现技术主要分为三种:jsp、freemarker、velocity,那么我们如何区分使用呢?下面让我们分析一下它们的优缺点。

一、JSP应该是模板语言中用的最多技术,其特点属性如下:

1.支持java代码直接写入,方便易学

2.支持标签(jsp tag)及自定义标签(jstl)

3.支持表达式语言(el)

4.丰富第三方jsp标签库,如(struts-tag等)

5.性能良好,jsp最终编译为class二进制文件执行

二、Velocity设计弥补jsp模板语言的缺点的,其特点属性如下:

1.不能在其中写java代码,更容易实现mvc分离

2.性能比jsp更好,不需要引入更多依赖库,解析更高效,不支持jsp标签

3.不是官方标准,用户群体和第三方标签库没jsp多

三、freemarker特点属性分析如下:

1.不能编写java代码,对于mvc分离更准确

2.性能一般

3.对jsp标签支持比较好

4.内置大量常用功能,使用方便

5.支持宏定义(类似于jsp标签)

6.使用表达式缺点:a.不是官方标准 b.用户群体和第三方标签库没jsp多

四、对于freemarker使用分析:

1.性能,velocity是最好的,其次是jsp,业务逻辑简单freemark页面是最差,复杂页面上(大量判断、日期金额格式化)页面上,要比jsp的tag和el好

2.freemark宏定义比jsp方便好用

3.其内置大量常用功能,如html过滤,日期金额格式化等,使用方便

4.也支持jsp标签

5.可以实现严格的mvc分离

五、关于如何使用freemarker和velocity,给出了具体代码示例:

1.模板主调用入口,TemplateTest.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

import java.util.ArrayList;

import java.util.Date;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

  

public class TemplateTest {

 

    @SuppressWarnings("all")

    /**  

     * @param args  

     */

    public static void main(String[] args) throws Exception {

        /* 准备数据 */

 

        Map latest = new HashMap();

        latest.put("url""products/greenmouse.html");

        latest.put("name""green mouse");

 

        Map root = new HashMap();

        root.put("user""Big Joe");

        root.put("latestProduct", latest);

        root.put("number"new Long(2222));

        root.put("date"new Date());

 

        List listTest = new ArrayList();

        listTest.add("1");

        listTest.add("2");

        root.put("list", listTest);

 

        TemplateEngine freemarkerEngine = (TemplateEngine) TemplateFactory

                .getInstance().getBean("freemarker");

        freemarkerEngine.run(root);// 使用freemarker模板技术

 

        TemplateEngine velocityEngine = (TemplateEngine) TemplateFactory

                .getInstance().getBean("velocity");

        velocityEngine.run(root);// 使用velocity模板技术

    }

 

}

2.模板引擎工厂(TemplateFactory.ava),负责调用注入各种模板语言引擎类

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

import java.util.HashMap;

import java.util.Map;

 

public class TemplateFactory {

     

    private static TemplateFactory instance;   

    private Map objectMap;   

        

    static{   

        instance = new TemplateFactory();   

    }   

        

    public TemplateFactory() {   

        super();   

        this.objectMap = new HashMap();   

        synchronized (this) {   

            objectMap.put("freemarker"new FreemarkerTemplateEngine(){   

                

            });   

                

            objectMap.put("velocity"new VelocityTemplateEngine());   

        }   

    }   

   

    public static TemplateFactory getInstance(){   

        return instance;   

    }   

        

    /**  

     * 模仿spring的工厂  

     * @param beanName  

     * @return  

     */  

    public Object getBean(String beanName){   

        return objectMap.get(beanName);   

    }   

 

  

 

}

3.模板引擎接口定义TemplateEngine.java

1

2

3

4

5

import java.util.Map;

 

public interface TemplateEngine {

    void run(Map context)throws Exception;   

}

4.模板引擎基类(AbstractTemplateEngine.java),用于实现公共方法及定义公共方法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

 import java.io.File;

import java.io.StringWriter;

import java.util.Map;

import java.util.StringTokenizer;

 

import org.apache.velocity.VelocityContext;

import org.apache.velocity.app.Velocity;

 

import freemarker.template.Configuration;

import freemarker.template.DefaultObjectWrapper;

import freemarker.template.Template;

 

  

public abstract class AbstractTemplateEngine implements TemplateEngine {

     

    private String currPath="WebRootWEB-INFclasses"+getClassPathName("");

 

    public abstract String getTemplatePath();   

     

    public abstract String getTemplate();   

        

    public abstract String getEngineType();   

        

    public void run(Map context)throws Exception{   

        if(Constants.ENGINE_TYPE_FREEMARKER.equals(getEngineType()))   

            executeFreemarker(context);   

        else  

            executeVelocity(context);   

    }   

        

    private void executeFreemarker(Map context)throws Exception{   

         System.out.println("##########freemarker111111################");

        Configuration cfg = new Configuration();   

        String path_=getTemplatePath();

        cfg.setDirectoryForTemplateLoading(   

                new File(path_));   

        cfg.setObjectWrapper(new DefaultObjectWrapper());   

        cfg.setCacheStorage(new freemarker.cache.MruCacheStorage(20250));   

        Template temp = cfg.getTemplate(getTemplate());   

//        Writer out = new OutputStreamWriter(System.out);

        StringWriter sw = new StringWriter(); 

//        Writer out = new OutputStreamWriter(new FileOutputStream(getPathString()+"reemark_test.html"));

//        temp.process(context, out);

        temp.process(context, sw);

        System.out.print(sw.toString());  

//        out.flush();   

         

         

    }   

        

    private void executeVelocity(Map root)throws Exception{   

        System.out.println("###########verlocity22222222###########");   

        Velocity.init();   

        VelocityContext context = new VelocityContext(root);  

        org.apache.velocity.Template template = null;   

//        template = Velocity.getTemplate(getTemplatePath()+""+getTemplate()); 

        template = Velocity.getTemplate("/src/"+getClassPathName("/")+"/"+getTemplate());

        StringWriter sw = new StringWriter(); 

        template.merge(context, sw );   

        System.out.print(sw.toString());   

   

    }

     

    protected  String getPathString(){

        return System.getProperty("user.dir")+this.currPath;

    }

     

    /**

     * getClassPathName("/") 输出:com/test/..

     * @param tokenizer

     * @return

     */

    public String getClassPathName(String tokenizer){

        StringTokenizer st=new StringTokenizer(this.getClass().getName(),".");

        StringBuffer sb=new StringBuffer("");

        while(st.hasMoreElements()){

            sb.append(st.nextElement()+tokenizer);

        }

        String temp_=sb.substring(0, sb.length()-1);

        temp_=temp_.substring(0,temp_.lastIndexOf(tokenizer));

        return temp_;

    }

      

 

}

5.模板引擎接口velocity及freemarker实现类(FreemarkerTemplateEngine.java、)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

import java.util.Map;

 

public class FreemarkerTemplateEngine extends AbstractTemplateEngine {

 

    private static final String DEFAULT_TEMPLATE = "FreemarkerExample.ftl";   

     

    /**  

     * 这个方法应该实现的是读取配置文件  

     */  

    public String getTemplatePath() {   

//        return this.getPathString()+""+DEFAULT_TEMPLATE;   

        return this.getPathString();

    }   

        

    public void run(Map root) throws Exception{   

        super.run(root);   

    }   

   

    public String getTemplate() {   

        // TODO Auto-generated method stub   

        return DEFAULT_TEMPLATE;   

    }   

   

    public String getEngineType() {   

        return Constants.ENGINE_TYPE_FREEMARKER;   

    }   

     

    public static void main(String[] args){

         

        System.out.println(FreemarkerTemplateEngine.class.getClassLoader().getResource("").getPath());

         

        System.out.println(FreemarkerTemplateEngine.class.getName());

         

        System.out.println(System.getProperty("user.dir")); 

         

        AbstractTemplateEngine f=new FreemarkerTemplateEngine();

         

        System.out.println(f.getPathString());

    }

 

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

 import java.util.Map;

  

public class VelocityTemplateEngine extends AbstractTemplateEngine {

 

    private static final String DEFAULT_TEMPLATE = "VelocityExample.vm";   

       

    public String getTemplatePath() {   

//        return this.getPathString()+""+DEFAULT_TEMPLATE;   

        return this.getPathString();

    }   

        

    public void run(Map map) throws Exception{   

        super.run(map);   

    }   

   

    public String getTemplate() {   

        // TODO Auto-generated method stub   

        return DEFAULT_TEMPLATE;   

    }   

   

    public String getEngineType() {   

        // TODO Auto-generated method stub   

        return Constants.ENGINE_TYPE_VELOCITY;   

    }   

 

}

6.常量公共参数定义接口(Constants.java)

1

2

3

4

5

6

7

public interface Constants {

     

    String ENGINE_TYPE_VELOCITY="VELOCITY";

     

    String ENGINE_TYPE_FREEMARKER="FREEMARKER";

 

}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值