FreeMarker与Struts2结合使用

        MVC是多年以来一直较为优秀的框架。对于java来说,Mode经常是由JavaBean担当的,Controller是由Servlet担当,View是由JSP担当的。JSP确实很优秀,功能强大,甚至可以直接在里面写java代码(scriptlet),他的自定义标签功能更是强大无比。然而在JSP可以被直接访问,所以不是完全符合MVC的标准,直接写java代码导致后期维护和可扩展性大大的降低了,其实个人觉得这个完全可以从人为上去改变,大不了不在JSP中写java代码。每次都让客户端访问Servlet后再跳转到JSP,这都是完全可以由编程人员解决的事情。在JSP推出后,有两款比较出名的模板引擎可以完全代替JSP,那就是Velocity和FreeMarker。由于FreeMarker是在Velocity之后出来的所以其综合功能要比Velocity强大。这两天自己试着写了个Freemarker和Struts2结合的Demo,其中模板是随便写了个jQuery的图标工具--highcharts。

一、模板文件 highcharts1.ftl

<html>
	<head>
		<title>jqGrid&FreeMarker Test</title>
		 <script src="js/jquery-1.8.3.js" type="text/javascript"></script>  
 	     <script src="js/highcharts.js" type="text/javascript"></script> 
 	     <script type="text/javascript" >
 	     	$(function () {
    var chart;
    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                type: 'column',  //spline曲线line直线pie饼状bar横向条状scatter 散状等
                marginRight: 100,
                marginBottom: 25
            },
            title: {
                text: '2012年气温变化表',
                x: 0 //center
            },
            subtitle: {
                text: '合肥气象台提供',
                x: 0
            },
            xAxis: {
                categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                    'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
            },
            yAxis: {
                title: {
                    text: '温度 (°C)'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                formatter: function() {
                        return '<b>'+ this.series.name +'</b><br/>'+
                        this.x +': '+ this.y +'°C';
                }
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'top',
                x: 0,
                y: 0,
                borderWidth: 0
            },
            series: [{name: '马鞍山',data: [<#list mas as temp>${temp},</#list>]}, { name: '芜湖',data: [<#list wh as temp>${temp},</#list>]},{name: '合肥',data: [<#list hf as										temp>${temp},</#list>]}]    //这里是用了FreeMarker的遍历,其他地方都是highcharts的固定用法,不用管它
        });  
    });
    
});
 	     </script>
 	     <style type="text/css">
 	     	#container{
 	     		width:70%;
 	     		height 300px;
 	     	}
 	     </style>
	</head>
	
	<body>
		<div id="container"></div>
	</body>
</html>

二、模板解析java类中的方法
public void highchartsResolution(String templateFileName, String htmlName) {
		List<Integer> list = null;
		Writer out = null;
		Configuration cfg = new Configuration();
		cfg.setServletContextForTemplateLoading(
				ServletActionContext.getServletContext(), "TemplateFiles");
		cfg.setDefaultEncoding("UTF-8");
		Map root = new HashMap();
		try {
			Template template = cfg.getTemplate(templateFileName);
			String path = ServletActionContext.getServletContext().getRealPath(
					"/");
			File file = new File(path + htmlName);
			out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(file)));
			root.put("hf", tdao.getTemperatureByCity("合肥"));
			root.put("mas", tdao.getTemperatureByCity("马鞍山"));
			root.put("wh", tdao.getTemperatureByCity("芜湖"));
			template.process(root, out);

		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		} finally {
			try {
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}



三、action中的执行方法
public String execute() throws Exception {
		TemplateResolution tr = new TemplateResolution();
		tr.highchartsResolution("highcharts1.ftl","test.html");
				return Action.SUCCESS;
	}



三、struts.xml配置
<action name="test" class="com.lubby.action.ServiceAction">
			<result type="redirect">/test.html</result>
		</action>


如果有想要源码的可以给我留言哈!

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值