zoukankan      html  css  js  c++  java
  • velocity与freework生成静态页面的实例

    java代码:http://localhost:8080/ssh/login.html

    User.java
    package com.ssh.test.model;
    
    import java.io.Serializable;
    import java.util.HashSet;
    import java.util.Set;
    
    public class User implements Serializable {
        /**
         * 实体类
         */
        private static final long serialVersionUID = 1L;
        private long id;
        private String name;
        private String password;
    
        private Set<Order> orders = new HashSet<Order>();
    
        public long getId() {
            return id;
        }
    
        public void setId(long id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public Set<Order> getOrders() {
            return orders;
        }
    
        public void setOrders(Set<Order> orders) {
            this.orders = orders;
        }
        
        @Override
        public String toString(){
            return "name:"+name+" password:"+password;
        }
        
    }
    User.hbm.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
        <hibernate-mapping>
            <class name="com.ssh.test.model.User" table="tb_user" >
                <id name="id" type="java.lang.Long" column="id">
                    <generator class="assigned"></generator>
                </id>
                <property name="name" type="java.lang.String" column="name" length="20"></property>
                <property name="password" type="java.lang.String" column="password" length="20"></property>
                <set name="orders" lazy="true" inverse="true" cascade="delete">
                    <key>
                        <column name="orderid"></column>
                    </key>
                    <one-to-many class="com.ssh.test.model.Order"/>
                </set>
            </class>
        </hibernate-mapping>
    BaseDao.java
    package com.ssh.test.dao;
    
    import java.util.List;
    
    public interface BaseDao {
        public Object getModelDetail(Class cl, Long id);
        public void saveModel(Object model);
        public List search(String hql, Object paramValue);
        public List search(String hql, Object[] paramValue);
    }
    BaseDaoImpl.java
    package com.ssh.test.dao;
    
    import java.util.List;
    
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
    
    
    public class BaseDaoImpl extends HibernateDaoSupport implements BaseDao {
    
        public Object getModelDetail(Class cl, Long id) {
            // TODO Auto-generated method stub
            return super.getHibernateTemplate().get(cl, id);
        }
    
        public void saveModel(Object model) {
            // TODO Auto-generated method stub
            super.getHibernateTemplate().save(model);
        }
    
        public List search(String hql, Object paramValue) {
            // TODO Auto-generated method stub
            return super.getHibernateTemplate().find(hql,paramValue);
        }
    
        public List search(String hql, Object[] paramValue) {
            // TODO Auto-generated method stub
            return super.getHibernateTemplate().find(hql,paramValue);
        }
    
    }
    UserBean.java
    package com.ssh.test.bean;
    
    import java.util.List;
    
    import com.ssh.test.model.User;
    
    public interface UserBean {
        public User getUserDetail(User user, Long userid);
        public void saveUser(User user);
        public List search(String name);
        public List loginCheck(Object[] obj);
    }
    UserBeanImpl
    package com.ssh.test.bean;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    
    import com.ssh.test.dao.BaseDao;
    import com.ssh.test.model.User;
    
    public class UserBeanImpl implements UserBean {
        private Log log = LogFactory.getLog(UserBeanImpl.class);
        private BaseDao baseDao;
    
        public void setBaseDao(BaseDao baseDao) {
            this.baseDao = baseDao;
        }
    
        public User getUserDetail(User user, Long userid) {
            // TODO Auto-generated method stub
            return (User) baseDao.getModelDetail(user.getClass(), userid);
        }
    
        public void saveUser(User user) {
            // TODO Auto-generated method stub
            baseDao.saveModel(user);
        }
    
        public List search(String name) {
            // TODO Auto-generated method stub
            List list = new ArrayList();
            String hql = "from com.ssh.test.model.User as user where user.name = ?";
            list = baseDao.search(hql, name);
            return list;
        }
    
        public List loginCheck(Object[] obj) {
            // TODO Auto-generated method stub
            String hql = "from com.ssh.test.model.User as user where user.name = ? and user.password = ?";
            List list = baseDao.search(hql, obj);
            return list;
        }
    
    }
    UserActionForm.java
    package com.ssh.test.actionform;
    
    import org.apache.struts.action.ActionForm;
    
    
    public class UserActionForm extends ActionForm{
    
        private static final long serialVersionUID = 1L;
        
        private String id;
        private String name;
        private String password;
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
    }
    BaseDispatchAction.java
    package com.ssh.test.action;
    
    import javax.servlet.ServletContext;
    
    import org.apache.struts.action.ActionServlet;
    import org.apache.struts.actions.DispatchAction;
    import org.springframework.web.context.WebApplicationContext;
    import org.springframework.web.context.support.WebApplicationContextUtils;
    
    public class BaseDispatchAction extends DispatchAction{
        
        protected WebApplicationContext wac;
    
        @Override
        public void setServlet(ActionServlet servlet) {
            // TODO Auto-generated method stub
            super.setServlet(servlet);
            ServletContext servletContext = servlet.getServletContext();
            wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        }
    }
    LoginAction.java
    package com.ssh.test.action;
    
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    
    import com.ssh.test.actionform.UserActionForm;
    import com.ssh.test.bean.UserBean;
    import com.ssh.test.model.User;
    import com.ssh.test.staticpage.StaticPage;
    
    public class LoginAction extends BaseDispatchAction{
    
        public ActionForward login(ActionMapping mapping, ActionForm form,
                HttpServletRequest request, HttpServletResponse response)
                throws Exception {
            // TODO Auto-generated method stub
            UserActionForm sForm = (UserActionForm) form;
            System.out.println("sForm.getName():"+sForm.getName());
            Object[] obj = new Object[2];
            obj[0] = sForm.getName();
            obj[1] = sForm.getPassword();
            UserBean userBean = (UserBean) wac.getBean("userbean");
            List list = userBean.loginCheck(obj);
            if(list != null){
                User u = (User) list.get(0);
                System.out.println(u.getName());
                
                Map root = new HashMap();
                root.put("name",u.getName());
                root.put("password", u.getPassword());
                
                StaticPage staticPage = new StaticPage();
                /*
                 * 使用freework生成静态页面,且数据为:root,生成的静态页面的名为:freew
                 * */
                staticPage.staticCont(root, "freew");
                /*
                 * 使用velocity生成静态页面,且数据为:root,生成的静态页面的名为:velo
                 * */
                staticPage.staticVMCont(root,"velo");
                
                return mapping.findForward("success");
            }else{
                return mapping.findForward("fail");
            }
        }
    }
    StaticPage.java
    package com.ssh.test.staticpage;
    
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintStream;
    import java.io.PrintWriter;
    import java.io.StringWriter;
    import java.util.Map;
    import java.util.Properties;
    
    import org.apache.velocity.VelocityContext;
    import org.apache.velocity.app.Velocity;
    
    import freemarker.template.Configuration;
    import freemarker.template.Template;
    import freemarker.template.TemplateException;
    import freemarker.template.TemplateExceptionHandler;
    
    public class StaticPage {
        /**
         * 使用freework
         */
        public void staticCont(Map root, String pagename) {
            String dir = "E:\\apache-tomcat\\apache-tomcat-6.0.18\\webapps\\ssh\\ftl";
            Configuration cfg = new Configuration();
            //从什么地方加载模板文件
            try {
                cfg.setDirectoryForTemplateLoading(new File(dir));
                //忽略异常
                cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
                //定义模板
                Template template = cfg.getTemplate("login.ftl");
                /**
                 * 
                 * 定义数据
                 * Map root = new HashMap();
                 * root.put("name","admin");
                 * root.put("password","123456");
                 * 
                 * */
                //定义输出
                PrintWriter out = new PrintWriter(new BufferedWriter(
                        new FileWriter(dir + "\\" + pagename + ".html")));
                //解释模板,并输出
                template.process(root, out);
            } catch (TemplateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        /**
         * 使用velocity
         * 
         * */
        public void staticVMCont(Map root,String pagename) throws Exception {
            
            String dir = "E:/apache-tomcat/apache-tomcat-6.0.18/webapps/ssh/vm";
            Properties p = new Properties();
            p.setProperty("file.resource.loader.path", dir);
            /*
             * input.encoding = ISO-8859-1 输出模板的编码方式 (templates). 你可选择对你模板的编码方式,如UTF-8.GBK.
             * output.encoding = ISO-8859-1 VelocityServlet 对输出流(output streams)的编码方式. 
             * */
            p.setProperty(Velocity.INPUT_ENCODING, "GBK");
            p.setProperty(Velocity.OUTPUT_ENCODING, "GBK"); 
            //初始化
            Velocity.init(p);
            //选择模板
            org.apache.velocity.Template template = null;
            template = Velocity.getTemplate("login.vm");  
            //获取VelocityContext对象
            VelocityContext context = new VelocityContext(root);  
            StringWriter sw = new StringWriter();  
            //将模板与数据合并
            template.merge(context, sw );
            System.out.print(sw.toString());
            PrintStream out = new PrintStream(new FileOutputStream(dir+"\\"+pagename+".html"));
            out.println(sw.toString());
            out.flush();
            out.close();
        }
    }
    SetCharacterEncodingFilter.java
    package com.ssh.test.staticpage;
    
    import java.io.IOException;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    
    /**
     * 过滤器
     * */
    public class SetCharacterEncodingFilter implements Filter {
    
        private String encoding;
        private FilterConfig filterConfig = null;
    
        public void destroy() {
            this.encoding = null;
            this.filterConfig = null;
        }
    
        public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {
            request.setCharacterEncoding(this.encoding);
            chain.doFilter(request, response);
        }
    
        public void init(FilterConfig filterConfig) throws ServletException {
            this.encoding = filterConfig.getInitParameter("encoding");
        }
    }

    html:

    login.html
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gbk">
    <title>Insert title here</title>
    </head>
    <body>
        <form name="mainform" action="/ssh/loginAction.do?dispatch=login" method="post">
            <table width="50%">
                <tr><td width="8%">用户名:</td><td width="42%"><input name="name" type="text" value=""/></td></tr>
                <tr><td>密码:</td><td><input name="password" type="password" value=""/></td></tr>
                <tr><td><input type="submit" value="submit"/><input type="reset" value="reset"/></td></tr>
            </table>
        </form>
    </body>
    </html>
    index.jsp
    <%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>My JSP 'index.jsp' starting page</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
      </head>
      
      <body>
        <a href="/ssh/vm/velo.html">velocity</a> <br>
        <a href="/ssh/ftl/freew.html">freework</a>
      </body>
    </html>

    配置文件:

    web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
     <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/hibernate-context.xml</param-value>
        </context-param>
    
     <filter>
         <filter-name>SetCharacterEncoding</filter-name>
         <filter-class>
             com.ssh.test.staticpage.SetCharacterEncodingFilter
         </filter-class>
         <init-param>
             <param-name>encoding</param-name>
             <param-value>GBK</param-value>
         </init-param>
     </filter>
    
     <filter-mapping>
         <filter-name>SetCharacterEncoding</filter-name>
         <url-pattern>/*</url-pattern>
     </filter-mapping>
    
     <servlet>
            <servlet-name>SpringContextServlet</servlet-name>
            <servlet-class>
                org.springframework.web.context.ContextLoaderServlet
            </servlet-class>
            <load-on-startup>2</load-on-startup>
        </servlet>
     
      <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
        <init-param>
          <param-name>config</param-name>
          <param-value>/WEB-INF/struts-config.xml</param-value>
        </init-param>
        <init-param>
          <param-name>debug</param-name>
          <param-value>3</param-value>
        </init-param>
        <init-param>
          <param-name>detail</param-name>
          <param-value>3</param-value>
        </init-param>
        <load-on-startup>0</load-on-startup>
      </servlet>
      <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.do</url-pattern>
      </servlet-mapping>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>
    hibernate-context.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" 
        "http://www.springframework.org/dtd/spring-beans.dtd">
    <beans>
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >
            <property name="driverClassName">
                <value>com.mysql.jdbc.Driver</value>
            </property>
            <property name="url">
                <value>jdbc:mysql://localhost:3306/tbtest</value>
            </property>
            <property name="username">
                <value>root</value>
            </property>
            <property name="password">
                <value>root</value>
            </property>
        </bean> 
        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
            <property name="dataSource">
                <ref local="dataSource" />
            </property>
            <property name="mappingResources">
                <list>
                    <value>com/ssh/test/model/User.hbm.xml</value>
                    <value>com/ssh/test/model/Order.hbm.xml</value>
                    <value>com/ssh/test/model/Item.hbm.xml</value>
                </list>
            </property>
           <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                    <!-- prop key="hibernate.dialect"> org.hibernate.dialect.Oracle9Dialect </prop> -->
                    <prop key="hibernate.show_sql"> true </prop>
                    <!--<prop key="hibernate.hbm2ddl.auto">update</prop>-->
                    <!-- prop key="hibernate.default_schema"> xdb </prop-->
                    <!-- 主要设置hibernate 缓存和批处理的大-->
                    <prop key="hibernate.jdbc.batch_versioned_data">true</prop>
                     <!-- <prop key="hibernate.connection.provider_class">net.sf.hibernate.connection.DatasourceConnectionProvider</prop>
                     <prop key="hibernate.cache.provider_class">net.sf.hibernate.cache.EhCacheProvider</prop> -->
                    <prop key="hibernate.jdbc.fetch_size">50</prop>
                    
                    <!-- 自动增加新表,重新启动服务时执行该命令,应用时务必注释此句(本机使用) -->
                    <!--prop key="hibernate.hbm2ddl.auto">update</prop-->
                    
                    <prop key="hibernate.jdbc.batch_size">20</prop>
                </props>
            </property>
        </bean>
        <!-- 将sessionFactory注入Dao -->
        <bean id="baseDao" class="com.ssh.test.dao.BaseDaoImpl">
            <property name="sessionFactory"><ref bean="sessionFactory"/></property> 
        </bean>    
        <!-- 配置事务管理 -->
        <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory"><ref local="sessionFactory"></ref>
            </property>
        </bean>
    
        <bean id="userBeanTarget" class="com.ssh.test.bean.UserBeanImpl">
            <property name="baseDao"><ref bean="baseDao"/></property>
        </bean>
        <bean id="userbean" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
            <property name="transactionManager"><ref bean="transactionManager"></ref></property>
            <property name="target"><ref local="userBeanTarget"></ref></property>
            <property name="transactionAttributes">
                <props>
                    <prop key="*">PROPAGATION_REQUIRED</prop>
                </props>
            </property>
        </bean>
        
    </beans>
    struts-config.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
    
    <struts-config>
        <data-sources />
        <form-beans>
            <form-bean name="userActionForm" type="com.ssh.test.actionform.UserActionForm"></form-bean>
        </form-beans>
        <global-exceptions />
        <global-forwards>
            <forward name="index" path="/login.jsp"></forward>
        </global-forwards>
        <action-mappings>
            <action path="/loginAction" name="userActionForm"
                parameter="dispatch" scope="session"
                type="com.ssh.test.action.LoginAction" validate="true"
                input="/index.jsp">
                <forward name="fail" path="/login.html" redirect="false" />
                <forward name="success" path="/index.jsp"></forward>
            </action>
        </action-mappings>
        <message-resources
            parameter="com.ssh.test.struts.ApplicationResources" />
    </struts-config>

    模板:

    login.ftl
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gbk">
    <title>Insert title here</title>
    </head>
    <body>
    freework生成静态页面:
            <table width="50%">
                <tr><td width="8%">用户名:</td><td width="42%">${name}</td></tr>
                <tr><td>密码:</td><td>${password}</td></tr>
            </table>
    </body>
    </html>
    login.vm
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=gbk">
    <title>Insert title here</title>
    </head>
    <body>
    velocity生成静态页面:
            <table width="50%">
                <tr><td width="8%">用户名:</td><td width="42%">${name}</td></tr>
                <tr><td>密码:</td><td>${password}</td></tr>
            </table>
    </body>
    </html>
  • 相关阅读:
    【干货分享】C# 实体类生成工具
    ASP.NET Core部署系列二:发布到CentOS上
    ASP.NET Core部署系列一:发布到IIS上
    微信公众号开发:用户管理
    微信公众号开发:自定义菜单
    像使用SQL一样对List对象集合进行排序
    使用JRebel插件实现SpringBoot应用代码热加载
    Java Stream函数式编程图文详解(二):管道数据处理
    SpringBoot生命周期管理之停掉应用服务几种方法
    本月16日SpringBoot2.2发布,有哪些变化先知晓
  • 原文地址:https://www.cnblogs.com/sfeng1825/p/2762885.html
Copyright © 2011-2022 走看看