J2EE社区

苟有恒,何必三更起五更眠;
最无益,只怕一日曝十日寒.
posts - 241, comments - 318, trackbacks - 0, articles - 16

Jfinal实例-北京丰帆佳宇运输有限公司

Posted on 2014-09-07 20:43 xcp 阅读(7656) 评论(0)  编辑  收藏 所属分类: JAVA
前面学习了一个开源框架Jfinal,并用此框架开发了一个实例网站现进行分享.
公司名称:北京丰帆佳宇运输有限公司
公司简介:渣土消纳证办理,大型支护土方深度开挖,矿山暗挖,基坑开挖,建筑垃圾清运,渣土清运,砂石料配送,工程机械租赁业务
公司网址:www.bjffjy.com
    
1、框架Jfinal+freemarker+mysql
       
  
2、Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi
="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation
="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
>
    <!-- index config -->
    <display-name>北京丰帆佳宇运输有限公司</display-name>
    
    <!-- jfinal config -->
    <filter>
        <filter-name>jfinal</filter-name>
        <filter-class>com.jfinal.core.JFinalFilter</filter-class>
        <init-param>
            <param-name>configClass</param-name>
            <param-value>com.bjffjy.config.BjffjyConfig</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>jfinal</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- session config -->
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
    <!-- online config -->
    <listener>
        <listener-class>com.bjffjy.listener.SessionCounter</listener-class>
    </listener>
    
    <!-- log4j config -->
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <!-- <param-value>classpath:resources/log4j.properties</param-value> -->
        <!-- <param-value>/WEB-INF/log4j.properties</param-value> -->
        <param-value>classpath:log4j.properties</param-value>
    </context-param>
    
    <!-- Settings -->
    <servlet>
        <servlet-name>SettingsServlet</servlet-name>
        <servlet-class>com.bjffjy.servlet.SettingsServlet</servlet-class>
        <load-on-startup>0</load-on-startup>
    </servlet>
    
    
    <!-- ckFinder -->
    <servlet>
        <servlet-name>ConnectorServlet</servlet-name>
        <servlet-class>com.ckfinder.connector.ConnectorServlet</servlet-class>
        <init-param>
            <param-name>XMLConfig</param-name>
            <param-value>/WEB-INF/config.xml</param-value>
        </init-param>
        <init-param>
            <param-name>debug</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ConnectorServlet</servlet-name>
        <url-pattern>/resource/js/ckfinder/core/connector/java/connector.java</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ConnectorServlet</servlet-name>
        <url-pattern>/ckfinder/core/connector/java/connector.java</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>FileUploadFilter</filter-name>
        <filter-class>com.ckfinder.connector.FileUploadFilter</filter-class>
        <init-param>
            <param-name>sessionCookieName</param-name>
            <param-value>JSESSIONID</param-value>
        </init-param>
        <init-param>
            <param-name>sessionParameterName</param-name>
            <param-value>jsessionid</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>FileUploadFilter</filter-name>
        <url-pattern>/resource/js/ckfinder/core/connector/java/connector.java</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>FileUploadFilter</filter-name>
        <url-pattern>/ckfinder/core/connector/java/connector.java</url-pattern>
    </filter-mapping>

    <!-- 404,500 config -->
    <error-page>
        <error-code>404</error-code>
        <location>/error.jsp?key=404</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/error.jsp?key=500</location>
    </error-page>
</web-app>


3、核心控制类

package com.bjffjy.config;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.wall.WallFilter;
import com.bjffjy.interceptor.AuthInterceptor;
import com.bjffjy.model.Car;
import com.bjffjy.model.News;
import com.bjffjy.model.Picture;
import com.bjffjy.model.Settings;
import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.activerecord.tx.TxByActionMethods;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.druid.DruidStatViewHandler;
import com.jfinal.plugin.ehcache.EhCachePlugin;
import com.jfinal.render.ViewType;

/**   
 * @Title: BjffjyConfig.java
 * @Description: TODO(总配置器) 
 * @Author Comsys-XCP  
 * @Date 2014-7-6 下午05:22:49 
 * @Company 北京丰帆佳宇运输有限公司 
 
*/
public class BjffjyConfig extends JFinalConfig{
    @Override
    public void configConstant(Constants me) {
        me.setDevMode(true);
        loadPropertyFile("config.properties");
        me.setError404View("/error.jsp?key=400");
        me.setError500View("/error.jsp?key=500");
        me.setViewType(ViewType.JSP);
    }

    @Override
    public void configRoute(Routes me) {
        me.add(new FrontRoutes());
        me.add(new AdminRoutes());
    }

    @Override
    public void configInterceptor(Interceptors me) {
        //用户登录权限过滤
        me.add(new AuthInterceptor());
        
        //声明式事务处理
        me.add(new TxByActionMethods("save","update","delete","batch"));
    }

    @Override
    public void configPlugin(Plugins me) {
        //缓存插件
        /*String ehcacheConf = PathKit.getWebRootPath() + File.separator + "WEB-INF" + File.separator + "ehcache.xml";
        me.add(new EhCachePlugin(ehcacheConf)); 
*/
        me.add(new EhCachePlugin());
        
        
        //数据源插件
        DruidPlugin dp = new DruidPlugin(getProperty("jdbc.url"),getProperty("jdbc.username"), getProperty("jdbc.password"));
        dp.addFilter(new StatFilter());
        WallFilter wall = new WallFilter(); 
        wall.setDbType("mysql"); 
        dp.addFilter(wall); 
        me.add(dp); 
        
        //ActiveRecord插件 
        ActiveRecordPlugin arp = new ActiveRecordPlugin(dp); 
        arp.setDialect(new MysqlDialect()).setShowSql(true);
        me.add(arp);
        
        //添加映射
        arp.addMapping("s_settings", Settings.class);
        arp.addMapping("b_news", News.class);
        arp.addMapping("b_car", Car.class);
        arp.addMapping("b_picture", Picture.class);
    }
    
    @Override
    public void configHandler(Handlers me) {
        DruidStatViewHandler dvh =  new DruidStatViewHandler("/druid"); 
        me.add(dvh); 
    }
}


package com.bjffjy.config;

import com.bjffjy.core.AdminController;
import com.bjffjy.core.CarController;
import com.bjffjy.core.LoginController;
import com.bjffjy.core.NewsController;
import com.bjffjy.core.PictureController;
import com.bjffjy.core.SettingsController;
import com.bjffjy.core.TemplateController;
import com.bjffjy.core.UpdateCenterController;
import com.jfinal.config.Routes;

/**   
 * @Title: AdminRoutes.java
 * @Description: TODO(后台管理路由器) 
 * @Author Comsys-XCP  
 * @Date 2014-7-6 下午09:57:21 
 * @Company 北京丰帆佳宇公司 
 
*/
public class AdminRoutes extends Routes{

    @Override
    public void config() {
        /**系统登录*/
        add("/login",LoginController.class);
        add("/admin",AdminController.class);
        add("/admin/**,SettingsController.class);
        add("/admin/**",TemplateController.class);
        add("/admin/**",UpdateCenterController.class);
        add("/admin/**",NewsController.class);
        add("/admin/**",CarController.class);
        add("/admin/**",PictureController.class);
    }
}


package com.bjffjy.config;

import com.bjffjy.core.IndexController;
import com.jfinal.config.Routes;

/**   
 * @Title: FrontRoutes.java
 * @Description: TODO(前台管理路由器) 
 * @Author Comsys-XCP  
 * @Date 2014-7-6 下午10:01:10 
 * @Company 北京丰帆佳宇公司 
 
*/
public class FrontRoutes extends Routes{

    @Override
    public void config() {
        /**首页展示*/
        add("/", IndexController.class);
    }
}


package com.bjffjy.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.handler.Handler;

/**   
 * @Title: SessionHandler.java
 * @Description: TODO(Freemarker session) 
 * 因为 jfinal 提倡 restful 的 不建议使用 session
 * 如果要在页面获取session 需要自己设置 一个handler 将session 放入request中
 * 
http://www.oschina.net/question/582302_59626?sort=default&p=1
 * @Author Comsys-XCP  
 * @Date 2014-7-17 下午05:11:23 
 * @Company *****公司 
 
*/
public class SessionHandler extends Handler {
    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        request.setAttribute("session", request.getSession());
        nextHandler.handle(target, request, response, isHandled);        
    }

}


package com.bjffjy.core;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.bjffjy.model.News;
import com.bjffjy.util.ImageUtils;
import com.bjffjy.util.RequestUtil;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;

/**   
 * @Title: NewsController.java
 * @Description: TODO(新闻信息控制类) 
 * @Author Comsys-XCP  
 * @Date 2014-7-18 上午11:14:23 
 * @Company 北京丰帆佳宇公司 
 
*/
public class NewsController extends Controller{
    /** 
     * @Title: index 
     * @Description: TODO(列表查询) 
     
*/
    public void index(){
        Map<String, Object> queryWhere = new HashMap<String, Object>();
        //查询条件
        queryWhere.put("lx", getPara("news.lx"));
        queryWhere.put("bt", getPara("news.bt"));
        queryWhere.put("zt", getPara("news.zt"));
        //分页
        String currentPage = getPara("pageBean.currentPage");
        String pageSize = getPara("pageBean.pageSize");
        if(currentPage==null || currentPage.equals(""))currentPage = "1";
        if(pageSize==null || pageSize.equals(""))pageSize = "15";
        queryWhere.put("currentPage",Integer.parseInt(currentPage));
        queryWhere.put("pageSize",Integer.parseInt(pageSize));
        
        Page<News> newsPage = News.dao.findByPageBean(queryWhere);
        setAttr("newsPage", newsPage);
        setAttr("queryWhere", queryWhere);
        render("list.jsp");
    }
    
    /** 
     * @Title: add 
     * @Description: TODO(新增页面) 
     
*/
    public void add() {
        createToken("tokenid");
    }
    
    /** 
     * @Title: save 
     * @Description: TODO(新增保存) 
     
*/
    public void save() {
        if(!validateToken("tokenid")){
            StringBuilder sb = new StringBuilder();
            sb.append("<script type='text/javascript'>");
            sb.append("alert('禁止重复提交表单!');");
            sb.append("document.location.href='"+RequestUtil.getBasePath(getRequest())+"admin/news/add' ");
            sb.append("</script>");
            renderJavascript(sb.toString());
            return;
        }else{
            //获取数据
            News news = getModel(News.class);
            news.set("id", RequestUtil.getUUID());
            int fwrs = (int) (Math.random()*200);
            news.set("fwrs",fwrs);
            news.set("zt", 0);
            
            //图片解析
            
//生成效果图
            String imagePath = getFirstImagePath(news.get("zw")+"");
            if(imagePath!=null && !"".equals(imagePath)){
                //保存效果图
                news.set("tj",imagePath);
                
                //生成缩阅图
                String basepath = getSession().getServletContext().getRealPath("/");
                if(!basepath.endsWith("/"))basepath+="/";
                File image = new File(basepath+imagePath);
                if(image!=null){
                    int index = imagePath.lastIndexOf(".");
                    String signImagePath = imagePath.substring(0, index)+"_small_170x130"+imagePath.substring(index);
                    //System.out.println(signImagePath);
                    File signImage = new File(basepath+signImagePath);
                    if(!signImage.exists()){
                        ImageUtils.buildSmallPic(image, signImage, 170, 130, false);
                    }
                    //保存缩阅图
                    news.set("syt", signImagePath);
                }
            }
            
            //保存
            news.save();
            
            //更新缓存
            
//CacheKit.remove("commonCache", "findNewsByPageBean");
            
            
//跳转
            redirect("/admin/news");
        }
    }
    
    
    /** 
     * @Title: getFirstImagePath 
     * @Description: TODO(取得第一张图片作为效果图)
     * 
@return 
     
*/
    private String getFirstImagePath(String source){
        String imagePath = "";
        Pattern p = Pattern.compile("<img [\\s\\S]+? src=\".*/(resource/upload/news/images/[\\s\\S]+?)\"");
        Matcher m = p.matcher(source);
        if(m.find()){
            imagePath = m.group(1);
        }
        return imagePath;
    }
    
    /** 
     * @Title: edit 
     * @Description: TODO(修改页面) 
     
*/
    public void edit() {
        createToken("tokenid");
        setAttr("news",News.dao.findById(getPara("id")));
    }
    
    /** 
     * @Title: update 
     * @Description: TODO(修改保存) 
     
*/
    public void update() {
        if(!validateToken("tokenid")){
            StringBuilder sb = new StringBuilder();
            sb.append("<script type='text/javascript'>");
            sb.append("alert('禁止重复提交表单!');");
            sb.append("document.location.href='"+RequestUtil.getBasePath(getRequest())+"admin/news' ");
            sb.append("</script>");
            renderJavascript(sb.toString());
            return;
        }else{
            //修改
            News news = getModel(News.class);
            
            //图片解析
            
//生成效果图
            String imagePath = getFirstImagePath(news.get("zw")+"");
            if(imagePath!=null && !"".equals(imagePath)){
                //保存效果图
                news.set("tj",imagePath);
                
                //生成缩阅图
                String basepath = getSession().getServletContext().getRealPath("/");
                if(!basepath.endsWith("/"))basepath+="/";
                File image = new File(basepath+imagePath);
                if(image!=null){
                    int index = imagePath.lastIndexOf(".");
                    String signImagePath = imagePath.substring(0, index)+"_small_170x130"+imagePath.substring(index);
                    //System.out.println(signImagePath);
                    File signImage = new File(basepath+signImagePath);
                    if(!signImage.exists()){
                        ImageUtils.buildSmallPic(image, signImage, 170, 130, false);
                    }
                    //保存缩阅图
                    news.set("syt", signImagePath);
                }
            }
            
            //数据更新
            news.update();
            
            //更新缓存
            
//CacheKit.remove("commonCache", "findNewsByPageBean");
            
            
//跳转
            redirect("/admin/news");
        }
    }
    
    /** 
     * @Title: del 
     * @Description: TODO(删除或批量删除) 
     
*/
    public void delete(){
        //删除
        String ids = getPara("id");
        for(String id: ids.split(",")){
            News.dao.deleteById(id);
        }
        
        //更新缓存
        
//CacheKit.remove("commonCache", "findNewsByPageBean");
        
        redirect("/admin/news");
    }
    
    
    /** 
     * @Title: check 
     * @Description: TODO(审核) 
     
*/
    public void check(){
        String ids = getPara("id");
        String zt = getPara("zt");
        for(String id: ids.split(",")){
            News.dao.checkNews(id,zt);
        }
        
        //更新缓存
        
//CacheKit.remove("commonCache", "findNewsByPageBean");
        
        redirect("/admin/news");
    }

    public void addFwrs(){
        String carId = getPara("newsId");
        News.dao.addFwrs(carId);
        renderText("增加访问人数成功");
        return;
    }
}


4、freemarker

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <base href="${basePath}" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="keywords" content="${settings.gjz}" />
    <meta name="description" content="${settings.zy}" />
    <meta name="viewport" content="width=device-width" />
    <meta name="viewport" content="width=1136" />
    <title>${settings.mc} - 官方网站</title>
    <link type="text/css" href="css/index.css" rel="stylesheet" />
    <link type="text/css" href="css/sf.css" rel="stylesheet"/>
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="http://a.tbcdn.cn/s/kissy/1.3.0/kissy-min.js"></script>
    <script type="text/javascript" src="http://a.tbcdn.cn/apps/e/brix/brix-min.js" bx-config="{autoConfig:true,componentsPath:'./',importsPath:'./'}"></script>
    <script type="text/javascript" src="js/jquery.bxslider.js"></script>
    <script type="text/javascript" src="js/jcarousellite_1.0.1.js"></script>
    <script type="text/javascript" src="js/js.js"></script>
    <!--[if IE 6]>
        <script type="text/javascript" src="js/png.js"></script>
        <script type="text/javascript">
            PNG.fix('.png')
        </script>
    <![endif]-->
</head>
<body>
    <iframe src="${path}/top/" frameBorder="0" width="100%" scrolling="no" height="492" style="float:left;"></iframe>
    <div class="home_main">
        <div class="home_neir">
            <div class="zhuanye"><img src="images/xuchtitle.png" width="567" height="73"></div>
            <div class="yewuinfo" id="J_identity">
                <ul class="kwicks" id="ulkwicks7">
                    <li>
                        <div class="kwicks_inner ks-clear" id="tm_sale">
                            <a class="bigLetter index_tm" href="javascript:void(0);"></a>
                            <a class="bigLetter J_index index_tm_hover" href="javascript:void(0);"></a> 
                            <a class="smallLetters" href="javascript:void(0);">
                                <span class="ywspan hy02">消纳证办理</span>
                                <span class="ywnr">公司为客户办理“北京市建筑垃圾消纳许可证”服务</span> 
                            </a>
                           </div>
                    </li>
                    <li>
                        <div class="kwicks_inner ks-clear" id="tb_sale">
                            <a class="bigLetter index_tb" href="javascript:void(0);"></a> 
                            <a class="bigLetter J_index index_tb_hover" href="javascript:void(0);"></a> 
                            <a class="smallLetters" href="javascript:void(0);" target="_self">
                                <span class="ywspan hy01">普通货运</span>
                                <span class="ywnr">公司为客户提供优质、快速、便捷、安全的全国货运服务</span>
                            </a>
                        </div>
                    </li>
                    <li>
                        <div class="kwicks_inner ks-clear">
                            <a class="bigLetter index_etao" href="javascript:void(0);"></a>
                            <a class="bigLetter J_index index_etao_hover" href="javascript:void(0);"></a> 
                            <a class="smallLetters" href="javascript:void(0);">
                                <span class="ywspan hy03">大型机械设备租赁</span>
                                <span class="ywnr">公司为客户提供各类型铲车、挖掘机、破碎锤、渣土运输车辆租赁服务</span>
                            </a>
                        </div>
                    </li>
                    <li>
                        <div class="kwicks_inner ks-clear">
                            <a class="bigLetter index_other" href="javascript:void(0);"></a>
                            <a class="bigLetter J_index index_other_hover" href="javascript:void(0);"></a> 
                            <a class="smallLetters" href="javascript:void(0);">
                                <span class="ywspan hy04">土方、建筑、沙石清运</span>
                                <span class="ywnr">公司为客户提供土方、建筑、沙石的挖掘、装载、清运等优质服务</span>
                            </a>
                        </div>
                    </li>
                </ul>
            </div>
        </div>
    </div>
    <div class="home_about">
        <div class="hoab_main">
            <div class="about_title"><img src="images/home_about.png" width="426" height="44"></div>
            <div class="ho_team">
                <span class="hotitle"><img src="images/index_ho01.png" width="192" height="17"></span>
                <span class="teampic"><img src="images/teampic.jpg" width="320" height="99"></span>
                <span class="teamwz">      北京丰帆佳宇运输有限公司成立于2011年11月16日,注册资金300万,坐落于北京市顺义区龙湾屯镇府前街。公司主要从事普通货运、大型机械设备租赁,土方、建筑垃圾及沙石的清运工作。公司现有员工25名,运输车辆福田十轮自卸车20辆,全部符合《建筑垃圾运输车辆标识、监控和封闭技术要求》,铲车50型5辆,挖掘机300型3台。破碎锤230型1台,并且有自己的修理厂专门服务于所属车队,时刻保持车队良好的运行。</span>
            </div>
            <div class="carteam">
                <span class="hotitle car"><img src="images/index_ho02.png" width="228" height="19"></span>
                <div class="kache">
                    <ul>
                        <#if cars??>
                            <#list cars as car>
                                    <li><a href="${path}/car?carId=${car.id}#001"  target="_blank"><img <#if car.syt??>src="${path}/${car.syt}"</#if> width="200" height="132"></a></li>
                            </#list>
                        </#if>
                    </ul>
                </div>
            </div>
            <div class="fllow">
                <span class="hotitle car"><img src="images/index_ho03.png" width="125" height="17"></span>
                <div class="fllow_info">
                    <span class="weibo">ID:${settings.wb}</span>
                      <span class="weixin">ID:${settings.wx}</span>
                </div>
                  <div class="add_info">
                    地址:${settings.dz}</br>
                    电话:${settings.zj} <br>  
                    手机:${settings.sj}(李月波-总经理)<br/>    
                       13311384678(李志强-副总经理)
                </div>
            </div>
        </div>
    </div>
    <iframe src="${path}/buttom/" frameBorder="0" width="100%" scrolling="no" height="104" style="float:left;"></iframe>
</body>
<script type="text/javascript">
KISSY.use("brix/gallery/kwicks/",function(S,Kwicks){
    var kwicks1 = new Kwicks({
        container:'#J_identity',
        tmpl:'#ulkwicks7',
        max:460,
        spacing:79,
        autoplay:false,
        sticky:false
    });
});
    
$(function () {
    win_width = document.documentElement.clientWidth;
    var curimgH = Math.floor(win_width / 1573 * 352);
    jQuery('#slideshow .img').css({ height: curimgH});
    var bannersider=jQuery('#slideshow .img').bxSlider({
        auto: true,
        speed: 2000
    });
    jQuery('#slideshow').mouseenter(function(){
        jQuery(this).find(".bx-prev").stop().animate({left:"5%"},400);
        jQuery(this).find(".bx-next").stop().animate({right:"5%"},400);
        bannersider.stopAuto();
    });
    jQuery('#slideshow').mouseleave(function(){
        jQuery(this).find(".bx-prev").stop().animate({left:"-5%"},300);
        jQuery(this).find(".bx-next").stop().animate({right:"-5%"},300);
        bannersider.startAuto();
    });

    $(".main_div_div").hover(function () {
        $(this).find(".ad").stop();
        $(this).find(".ad").fadeIn(300);
    }, function () {
        $(this).find(".ad").stop();
        $(this).find(".ad").fadeOut(300);
    });
});
</script>


5、静态页面生成器

package com.bjffjy.core;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.List;

import com.bjffjy.init.BjffjyPropertyRegistry;
import com.bjffjy.model.Car;
import com.bjffjy.model.News;
import com.bjffjy.model.Picture;
import com.bjffjy.util.PageBean;
import com.bjffjy.util.ResourceManager;
import com.jfinal.core.Controller;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**   
 * @Title: UpdateCenterController.java
 * @Description: TODO(数据更新中心控制类) 
 * @Author Comsys-XCP  
 * @Date 2014-7-18 上午11:12:12 
 * @Company 北京丰帆佳宇公司 
 
*/
public class UpdateCenterController extends Controller{
    //private static Logger log = Logger.getLogger(UpdateCenterController.class);
    
//模板存放文件夹
    private String templatePath;
    //基本路径-网络
    private String basePath ;
    private String basePath2 ;
    //模板传送数据
    private HashMap<String, Object> data = null;
    
    
    public void index(){
        renderJsp("/admin/template/updateCenter.jsp");
    }
    
    public void build(){
        templatePath = getSession().getServletContext().getRealPath(BjffjyPropertyRegistry.TEMPLATE_PATH);
        //basePath = RequestUtil.getBasePath2(getRequest());
        basePath = ResourceManager.getValue("basePath");
        basePath2 = basePath + BjffjyPropertyRegistry.TEMPLATE_PATH;
        //数据设置
        data = new HashMap<String, Object>();
        data.put("path", basePath);
        data.put("basePath", basePath2);
        data.put("settings",getSession().getServletContext().getAttribute("settings"));
        
        
        String type = getPara("type")+"";
        String message = "数据更新中心成功";
        try{
            if(type.equals("1")){//刷新菜单导航
                buildTop();
            }else if(type.equals("2")){//刷新版权备案
                buildButtom();
            }else if(type.equals("3")){//刷新网站首页
                buildIndex();
            }else if(type.equals("4")){//刷新新闻列表
                buildNewsList();
            }else if(type.equals("5")){//刷新新闻内容
                buildNews();
            }else if(type.equals("6")){//刷新公司服务
                buildService();
            }else if(type.equals("7")){//刷新车队列表
                buildCarList();
            }else if(type.equals("8")){//刷新车队内容
                buildCar();
            }else if(type.equals("9")){//刷新关于我们
                buildAbout();
            }else if(type.equals("10")){//刷新全部
                buildTop();
                buildButtom();
                buildIndex();
                buildNewsList();
                buildNews();
                buildService();
                buildCarList();
                buildCar();
                buildAbout();
            }
        }catch(Exception e){
            e.printStackTrace();
            message = "数据更新中心失败";
        }
        
        renderText(message);
        return;
    }

    /** 
     * @Title: buildTop 
     * @Description: TODO(通过template/default/top.ftl模板文件生成template/default/static/top.html文件)
     
*/
    private void buildTop() throws Exception{
        //读取模板
        Template template = getTemplate(templatePath,"top.ftl");
        File top = new File(templatePath+File.separator+"static"+File.separator+"top.html");
        //获取输出流
        BufferedWriter out = getWriter(top);
        //要传送的数据
        
        
        
//生在静态页面
        template.process(data, out);
        //关闭流
        if(out!=null){
            out.flush();
            out.close();
        };
    }
    
    /** 
     * @Title: buildButtom 
     * @Description: TODO(通过template/default/buttom.ftl模板文件生成template/default/static/buttom.html文件)
     * 
@throws Exception 
     
*/
    private void buildButtom() throws Exception{
        //读取模板
        Template template = getTemplate(templatePath,"buttom.ftl");
        File top = new File(templatePath+File.separator+"static"+File.separator+"buttom.html");
        //获取输出流
        BufferedWriter out = getWriter(top);
        //要传送的数据
        
        
        
//生在静态页面
        template.process(data, out);
        //关闭流
        if(out!=null){
            out.flush();
            out.close();
        };
    }
    
    /** 
     * @Title: buildButtom 
     * @Description: TODO(通过template/default/index.ftl模板文件生成template/default/static/index.html文件)
     * 
@throws Exception 
     
*/
    private void buildIndex() throws Exception{
        //读取模板
        Template template = getTemplate(templatePath,"index.ftl");
        File top = new File(templatePath+File.separator+"static"+File.separator+"index.html");
        //获取输出流
        BufferedWriter out = getWriter(top);
        //要传送的数据
        
//查询最新发布的3个车辆信息
        List<Car> cars = Car.dao.findTop3ForIndex();
        List<Picture> pics = Picture.dao.findByCustom();
        data.put("cars", cars);
        data.put("pics", pics);
        
        
        //生在静态页面
        template.process(data, out);
        //关闭流
        if(out!=null){
            out.flush();
            out.close();
        };
    }
    
    /** 
     * @Title: buildNewsList 
     * @Description: TODO(通过template/default/newsList.ftl模板文件生成template/default/static/newslist.html文件) 
     
*/
    private void buildNewsList() throws Exception{
        //读取模板
        Template template = getTemplate(templatePath,"newsList.ftl");
        //获取输出流
        File top = null;
        BufferedWriter out =  null;
        //分页
        PageBean pagebean = new PageBean(1,15);
        
        //全部资讯
        String lx = "0";
        int allCount = News.dao.countNews(lx);
        pagebean.setAllRow(allCount);
        pagebean.countTotalPage(allCount);
        boolean hasNext = true;
        String fileName = "newslist";
        while(hasNext){
            if(pagebean.getCurrentPage()==1){
                top = new File(templatePath+File.separator+"static"+File.separator+fileName+".html");
            }else{
                top = new File(templatePath+File.separator+"static"+File.separator+fileName+pagebean.getCurrentPage()+".html");
            }
            out = getWriter(top);
            
            //要传送的数据
            List<News> newslist = News.dao.findAllNews(lx,pagebean);
            data.put("newslist",newslist);
            data.put("pagebean",pagebean);
            data.put("lx",lx);
            
            //生在静态页面
            template.process(data, out);
            //关闭流
            if(out!=null){
                out.flush();
                out.close();
            };
            
            //查询第二页
            if(pagebean.getCurrentPage()<pagebean.getTotalPage()){
                pagebean.setCurrentPage(pagebean.getCurrentPage()+1);
            }else{
                hasNext = false;
            }
        }
        
        
        //公司动态
        lx = "1";
        int companyCount = News.dao.countNews(lx);
        pagebean = new PageBean(1,15);
        pagebean.setAllRow(companyCount);
        pagebean.countTotalPage(companyCount);
        hasNext = true;
        fileName = "companylist";
        while(hasNext){
            if(pagebean.getCurrentPage()==1){
                top = new File(templatePath+File.separator+"static"+File.separator+fileName+".html");
            }else{
                top = new File(templatePath+File.separator+"static"+File.separator+fileName+pagebean.getCurrentPage()+".html");
            }
            out = getWriter(top);
            
            //要传送的数据
            List<News> newslist = News.dao.findAllNews(lx,pagebean);
            data.put("newslist",newslist);
            data.put("pagebean",pagebean);
            data.put("lx",lx);
            
            //生在静态页面
            template.process(data, out);
            //关闭流
            if(out!=null){
                out.flush();
                out.close();
            };
            
            //查询第二页
            if(pagebean.getCurrentPage()<pagebean.getTotalPage()){
                pagebean.setCurrentPage(pagebean.getCurrentPage()+1);
            }else{
                hasNext = false;
            }
        }
        
        
        //行业信息
        lx = "2";
        int tradeCount = News.dao.countNews(lx);
        pagebean = new PageBean(1,15);
        pagebean.setAllRow(tradeCount);
        pagebean.countTotalPage(tradeCount);
        hasNext = true;
        fileName = "tradelist";
        while(hasNext){
            if(pagebean.getCurrentPage()==1){
                top = new File(templatePath+File.separator+"static"+File.separator+fileName+".html");
            }else{
                top = new File(templatePath+File.separator+"static"+File.separator+fileName+pagebean.getCurrentPage()+".html");
            }
            out = getWriter(top);
            
            //要传送的数据
            List<News> newslist = News.dao.findAllNews(lx,pagebean);
            data.put("newslist",newslist);
            data.put("pagebean",pagebean);
            data.put("lx",lx);
            
            //生在静态页面
            template.process(data, out);
            //关闭流
            if(out!=null){
                out.flush();
                out.close();
            };
            
            //查询第二页
            if(pagebean.getCurrentPage()<pagebean.getTotalPage()){
                pagebean.setCurrentPage(pagebean.getCurrentPage()+1);
            }else{
                hasNext = false;
            }
        }
    }
    
    /** 
     * @Title: buildNews 
     * @Description: TODO(通过template/default/news.ftl模板文件生成template/default/static/news.html文件)
     * 
@throws Exception 
     
*/
    private void buildNews() throws Exception{
        //读取模板
        Template template = getTemplate(templatePath,"news.ftl");
        //获取输出流
        File top = null;
        BufferedWriter out =  null;
        //全部资讯
        String lx = "0";
        //分页
        PageBean pagebean = new PageBean(1,15);
        int allCount = News.dao.countNews(lx);
        pagebean.setAllRow(allCount);
        pagebean.countTotalPage(allCount);
        boolean hasNext = true;
        while(hasNext){
            List<News> newslist = News.dao.findAllNews2(lx,pagebean);
            for(News news: newslist){
                //要传送的数据
                top = new File(templatePath+File.separator+"static"+File.separator+"news"+File.separator+news.getStr("id")+".html");
                out = getWriter(top);
                data.put("news",news);
                
                //生在静态页面
                template.process(data, out);
                //关闭流
                if(out!=null){
                    out.flush();
                    out.close();
                };
            }
            
            //查询第二页
            if(pagebean.getCurrentPage()<pagebean.getTotalPage()){
                pagebean.setCurrentPage(pagebean.getCurrentPage()+1);
            }else{
                hasNext = false;
            }
        }
    }
    
    /** 
     * @Title: buildService 
     * @Description: TODO(通过template/default/service.ftl模板文件生成template/default/static/service.html文件)
     * 
@throws Exception 
     
*/
    private void buildService() throws Exception{
        //读取模板
        Template template = getTemplate(templatePath,"service.ftl");
        File top = new File(templatePath+File.separator+"static"+File.separator+"service.html");
        //获取输出流
        BufferedWriter out = getWriter(top);
        //要传送的数据
        List<Picture> pics = Picture.dao.findByPatner();
        data.put("pics", pics);
        
        //生在静态页面
        template.process(data, out);
        //关闭流
        if(out!=null){
            out.flush();
            out.close();
        };
    }
    
    /** 
     * @Title: buildCarList 
     * @Description: TODO(通过template/default/carList.ftl模板文件生成template/default/static/carlist.html文件)
     * 
@throws Exception 
     
*/
    private void buildCarList() throws Exception{
        //读取模板
        Template template = getTemplate(templatePath,"carList.ftl");
        File top = new File(templatePath+File.separator+"static"+File.separator+"carlist.html");
        //获取输出流
        BufferedWriter out = getWriter(top);
        //要传送的数据
        List<Car> cars = Car.dao.findAllForIndex();
        data.put("cars", cars);
        
        //生在静态页面
        template.process(data, out);
        //关闭流
        if(out!=null){
            out.flush();
            out.close();
        };
    }
    
    /** 
     * @Title: buildCar 
     * @Description: TODO(通过template/default/car.ftl模板文件生成template/default/static/car.html文件)
     * 
@throws Exception 
     
*/
    private void buildCar() throws Exception{
        //读取模板
        Template template = getTemplate(templatePath,"car.ftl");
        
        //读取所有车辆
        List<Car> cars = Car.dao.findAllForIndex();
        File top = null;
        BufferedWriter out =  null;
        String carId = "";
        if(cars!=null){
            data.remove("car");
            data.remove("pics");
            for(Car car : cars){
                carId = car.getStr("id");
                top = new File(templatePath+File.separator+"static"+File.separator+"car"+File.separator+carId+".html");
                //获取输出流
                out = getWriter(top);
                //要传送的数据
                List<Picture> pics = Picture.dao.findByYwid("1",carId);
                if(car.get("bz")==null)car.set("bz", "");
                data.put("car", car);
                data.put("pics", pics);
                
                //生在静态页面
                template.process(data, out);
                //关闭流
                if(out!=null){
                    out.flush();
                    out.close();
                };
            }
        }
    }
    
    /** 
     * @Title: buildAbout 
     * @Description: TODO(通过template/default/about.ftl模板文件生成template/default/static/about.html文件)
     * 
@throws Exception 
     
*/
    private void buildAbout() throws Exception{
        //读取模板
        Template template = getTemplate(templatePath,"about.ftl");
        File top = new File(templatePath+File.separator+"static"+File.separator+"about.html");
        //获取输出流
        BufferedWriter out = getWriter(top);
        //要传送的数据
        List<Picture> pics = Picture.dao.findByZzry();
        data.put("pics", pics);
        
        
        //生在静态页面
        template.process(data, out);
        //关闭流
        if(out!=null){
            out.flush();
            out.close();
        };
    }

    /** 
     * @Title: getConfiguration 
     * @Description: TODO(获取模板文件夹)
     * 
@throws IOException 
     
*/
    private Configuration getConfiguration(String templatePath) throws IOException{
        Configuration cfg = new Configuration();
        cfg.setDefaultEncoding("UTF-8");
        cfg.setDirectoryForTemplateLoading(new File(templatePath));
        return cfg;
    }
    /** 
     * @Title: getTemplate 
     * @Description: TODO(获取模板文件)
     * 
@param templatePath 模板文件夹路径
     * 
@param templateName 模板文件名称
     * 
@throws IOException 
     
*/
    private Template getTemplate(String templatePath,String templateName)throws IOException{
        Configuration cfg = getConfiguration(templatePath);
        Template template = cfg.getTemplate(templateName);
        template.setEncoding("UTF-8");
        return template;
    }
    
    /** 
     * @Title: getWriter 
     * @Description: TODO(获取缓冲输出流)
     * 
@param file 输出文件
     
*/
    private  BufferedWriter getWriter(File file) throws Exception{
        if(file!=null && file.exists()) file.delete();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));
        return bw;
    }
}






名称: ♪4C.ESL | .↗Evon
口号: 遇到新问题♪先要寻找一个方案乄而不是创造一个方案こ
mail: 联系我



只有注册用户登录后才能发表评论。


网站导航: