JFinal


http://www.blogjava.net/xcp/archive/2014/09/07/417749.html

 

前面學習了一個開源框架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" ></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" ></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;     } }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM