怎么让内向的人变外向:使用FreeMaker示例二(代替struts标签的使用方法)

来源:百度文库 编辑:中财网 时间:2024/04/29 11:04:56
开发工具:myeclipse 6.5 

该实例我参考了Freemarker官方网址:http://freemarker.sourceforge.net/index.html

总体目录结构如下:


1.新建项目FreemakerS ,将freemaker.jar 拷入lib下

2.项目中加入struts1.2的属性包

3.在新建com.shiryu.strutsexample.model包里新建Guestbook,java:

package com.shiryu.strutsexample.model;

public class Guestbook {
    private String name;
    private String email;
    private String message;
    
    public Guestbook() {        
    }

    public Guestbook(String name, String email, String message) {        
        this.name = name;
        this.email = email;
        this.message = message;
    }

    public String getName() {
        return name;
    }
    public String getEmail() {
        return email;
    }
    public String getMessage() {
        return message;
    }    
}

4.通过struts-config.xml 文件编辑器,加入一个GuestbookAction和GuestbookForm
在com.shiryu.strutsexample.form 包下GuestbookForm.java的内容如下:

package com.shiryu.strutsexample.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

public class GuestbookForm extends ActionForm {
    private static final long serialVersionUID = -975484770386532562L;
    private String message;
    private String email;
    private String name;

    @SuppressWarnings({ "deprecation", "deprecation" })

    //validate方法用来存放错误信息,不过该方法已经不推荐使用了
    public ActionErrors validate(ActionMapping mapping,
            HttpServletRequest request) {
        ActionErrors errs = new ActionErrors();
        if (name.length() == 0) {
            errs.add("name", new ActionError("errors.required", "name"));
        }
        if (message.length() == 0) {
            errs.add("message", new ActionError("errors.required", "message"));
        }
        return errs.size() == 0 ? null : errs;
    }    
    @SuppressWarnings("unused")
    private static String normalizeString(String s){
        if(s==null) return "";
        return s.trim();
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

5.com.shiryu.strutsexample包下的ApplicationResourses,xml文件的内容:
ApplicationResourses,xml
errors.header=

Please correct the following problems:


    errors.prefix=

  • errors.suffix=

    errors.footer=

errors.required={0} is required.

6.在com.shiryu.strutsexample.action包下的各个action:

GuestbookAction.java 
package com.shiryu.strutsexample.action;

import java.util.*;

import org.apache.struts.action.*; 

public class GuestbookAction extends Action { 
    @SuppressWarnings("unchecked")
    //该action通过servlet获得上下文,返回一组数据
    ArrayList getGuestbook(){
        return (ArrayList)servlet.getServletContext().getAttribute(GuestbookActionServlet.GUESTBOOK_KEY);
    }
}

GuestbookActionServlet .java
package com.shiryu.strutsexample.action;

import java.util.ArrayList;

import javax.servlet.*;
import org.apache.struts.action.ActionServlet;

public class GuestbookActionServlet extends ActionServlet {
    private static final long serialVersionUID = 1086968061394593748L;
    static final String GUESTBOOK_KEY = "guestbook";

    @SuppressWarnings("unchecked")
    //初始化就通过scfg获得guestbook的数据,并将其作为GUESTBOOK_KEY存放
    public void init(ServletConfig scfg) throws ServletException {
        super.init(scfg);
        ServletContext sctx = scfg.getServletContext();
        sctx.setAttribute(GUESTBOOK_KEY, new ArrayList());
    }
}

IndexAction.java
package com.shiryu.strutsexample.action;

import java.util.List;

import javax.servlet.http.*;
import org.apache.struts.action.*;

public class IndexAction extends GuestbookAction {
    @SuppressWarnings("unchecked")
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest req, HttpServletResponse resp) throws Exception {
        List snapShot;
        //通过克隆getGuestbook()得到已有的一组guestbook,并将同步,限制访问
        synchronized (getGuestbook()) {
            snapShot = (List) getGuestbook().clone();
        }
        req.setAttribute("guestbook", snapShot);
        return mapping.findForward("success");
    }
}

FormAction.java
package com.shiryu.strutsexample.action;

import javax.servlet.http.*;
import org.apache.struts.action.*;

public class FormAction extends GuestbookAction {
    public ActionForward execute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest req,
            HttpServletResponse resp) throws Exception {
        //这里没有进行操作直接进入form.ftl
        return mapping.findForward("success");
    }
}

AddAction.java
package com.shiryu.strutsexample.action;

import java.util.List;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import com.shiryu.strutsexample.form.GuestbookForm;
import com.shiryu.strutsexample.model.Guestbook;

public class AddAction extends GuestbookAction {
    @SuppressWarnings("unchecked")
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest req, HttpServletResponse resp) throws Exception {
        
        GuestbookForm f = (GuestbookForm) form;
        //声明一个list通过form f 将值传入,使用同步
        List guestbooks = getGuestbook();
        synchronized (guestbooks) {
            guestbooks.add(0, new Guestbook(f.getName(), f.getEmail(), f.getMessage()));
        }
        //成功后跳入add.ftl
        return mapping.findForward("success");
    }
}

7.通过配置struts-config.xml将action进行配置:

struts-config.xml


"http://struts.apache.org/dtds/struts-config_1_2.dtd">


   
   
       
   


   
   
   
        
                    type="com.shiryu.strutsexample.action.IndexAction">
           
       


        .ftl的action - ->
                    type="com.shiryu.strutsexample.action.FormAction" 
            name="guestbook"
            scope="request"
validate="false">
           
       


        .ftl的action 它的来源是form.do - ->
                    type="com.shiryu.strutsexample.action.AddAction" 
            name="guestbook"
            validate="true" 
            scope="request" 
            input="/form.do">
           
       

   


   


web.xml的内容如下:



PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">


    FreeMarker Struts Example

   
   
        action
       
            com.shiryu.strutsexample.action.GuestbookActionServlet
       

       
            config
            /WEB-INF/struts-config.xml
       

       
            debug
            2
       

       
            detail
            2
       

        2
   


   
   
        freemarker
       
            freemarker.ext.servlet.FreemarkerServlet
       


       
       
            TemplatePath
            /
       

       
            NoCache
            true
       

       
            ContentType
            text/html
       


       
       
            template_update_delay
            0
       

       
            default_encoding
            UTF-8
       


       
            number_format
            0.##########
       


        1
   


   
        action
        *.do
   


   
        freemarker
        *.ftl
   


   
        help.html
   




以上都是后台的部署,下面是前台页面的部署这也是freemaker的真正体现

8.在WEB-INF/lib下新建common.ftl:

common.ftl
Macro(宏)和transform(传递器),Macro是在模板中使用macro指令定义。
这里的common.ftl就是模板 - ->


<#macro page title>


FreeMaker Struts Example ${title?html}



${title?html}




指令 
也就是说这里将展示你的内容 - ->

<#nested>


   
     
       
     
   

          FreeMarker Struts Example
       

         
       





主页index.ftl的内容:

index.ftl

<#import "/WEB-INF/lib/common.ftl" as com>

escape指令body区的ftl的interpolations都会被自动加上escape表达式。而且也只会影响到body内出现的interpolations,比如不会影响到include的ftl的interpolations。 - ->
<#escape x as x?html>


<@com.page title ="IndexPage">
   form.do
">Add new message | Help
   
   <#if guestbook?size = 0>
    

No messages.


   <#else>
    

The message are:


     
      
       
       
      

      
      <#list guestbook as e>
       
         
         
       
     
   
NameMessage

            
            ${e.name} <#if e.email?length != 0> (${e.email})
         
${e.message}

   



运行效果如下:

点击Add new message 进入form.do,其对应的是form.ftl;

form.ftl

<#import "/WEB-INF/lib/common.ftl" as com>
 - ->
<#global html=JspTaglibs["/WEB-INF/struts-html.tld"]>

<#escape x as x?html>
<@com.page title="Add Message">

<@html.errors/>


<@html.form action="/add">
    Your name is :
<@html.text property="name" size="25"/>

    Your email is :
<@html.text property="email" size="25"/>

    Message:
<@html.textarea property="message" rows="3"/>

    <@html.submit value="Submit"/> 
 
Back to the index page



其页面效果(没有数据提交显示了错误信息)如下:

接下来是add.ftl 文件,它是我们添加成功后要进行显示的页面:

add.ftl

<#import "/WEB-INF/lib/common.ftl" as com>
<#escape x as x?html>

<@com.page title="Entry added">

You have added the following entry to the guestbook:

Name: ${guestbook.name}
<#if guestbook.email?length != 0>
   

Email: ${guestbook.email}

Message: ${guestbook.message}

Back to the index page...




效果如下:

点击Back to the index page... 可以看到已经添加数据后的效果;