List<T>中对比Contains, Exists, Any之间的优缺点

List<T>中,Contains, Exists, Any都可以实现判断元素是否存在。

先上结果。性能方面:Contains 优于 Exists 优于 Any

以下为测试代码

public static void Contains_Exists_Any_Test(int num)
 {
            List<int> list = new List<int>();

            int N = num;
            for (int i = 0; i < N; i++)
            {
                list.Add(i);
            }
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            Console.WriteLine(list.Contains(N));
            sw.Stop();
            Console.WriteLine("Contains:"+sw.Elapsed.ToString());

            sw.Restart();
            Console.WriteLine(list.Exists(i => i == N));
            sw.Stop();
            Console.WriteLine("Exists:"+ sw.Elapsed.ToString());

            sw.Restart();
            Console.WriteLine(list.Any(i => i == N));
            sw.Stop();
            Console.WriteLine("Any:"+ sw.Elapsed.ToString());
}

在开发过程中可以根据实际情况进行选择,当list中数据量不大时使用Exists代码更简洁易懂;数据量大时推荐使用Contains;不推荐使用Any

下面的代码对比就能看出为啥数据量不大的时候推荐Exists了。

class ITEM_GIDComparer : IEqualityComparer<T>
    {
        public bool Equals(T orl1, T orl2)
         {
             if (orl1==null)
             {
                 return orl2 == null;
             }
             return orl1.ITEM_GID == orl2.ITEM_GID;
         }

        public int GetHashCode(T orl)
         {
             if (orl == null)
                 return 0;
             return orl.ITEM_GID.GetHashCode();
         } 
    }
    orlclst.Contains(orlc, new ITEM_GIDComparer())
    //Exists一行代码就可以实现上面的功能
    orlclst.Exists(x=>x.ITEM_GID==orlc.ITEM_GID)


C#比较两个list集合,两集合同时存在或A集合存在B集合中无

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Test
{
    class Program 
    {
        static void Main(string[] args)
        {
            var student1 = new List<student>();
            student1.Add(new student() { name = "张三", subject = "英语", score = 89 });
            student1.Add(new student() { name = "李四", subject = "英语", score = 95 });
            student1.Add(new student() { name = "王五", subject = "英语", score = 69 });
            student1.Add(new student() { name = "李倩", subject = "英语", score = 99 });

            var student2 = new List<student>();
            student2.Add(new student() { name = "李四", subject = "英语", score = 95 });
            student2.Add(new student() { name = "王五", subject = "数学", score = 69 });
            student2.Add(new student() { name = "赵六", subject = "数学", score = 100 });

            //var exp1 = student1.Where(a => student2.Any(t => a.name.Contains(t.name))).ToList();  
            //使用Exists同样可以实现 字面上应该更好理解,而且效率要高些  
            var exp1 = student1.Where(a => student2.Exists(t => a.name.Contains(t.name))).ToList();
            Console.WriteLine("--查找student1和student2总同时存在的数据--");
            foreach (var item in exp1)
            {
                Console.WriteLine("{0} \t {1} \t {2}", item.name, item.subject, item.score);
            }

            //var exp2 = student1.Where(a => student2.All(t => !a.name.Contains(t.name))).ToList();    
            //使用Exists同样可以实现 字面上应该更好理解,而且效率要高些  
            var exp2 = student1.Where(a => !student2.Exists(t => a.name.Contains(t.name))).ToList();
            Console.WriteLine("--查找student1集合中存在,而student2不存在的数据--");
            foreach (var item in exp2)
            {
                Console.WriteLine("{0} \t {1} \t {2}", item.name, item.subject, item.score);
            }

            var exp3 = student2.Where(a => !student1.Exists(t => a.name.Contains(t.name))).ToList();
            Console.WriteLine("--查找student2集合中存在,而student1不存在的数据--");
            foreach (var item in exp3)
            {
                Console.WriteLine("{0} \t {1} \t {2}", item.name, item.subject, item.score);
            }
            Console.Read();   
             
        }

        public class student
        {
            /// <summary>    
            /// 姓名    
            /// </summary>    
            public string name;
            /// <summary>    
            /// 科目    
            /// </summary>    
            public string subject;
            /// <summary>    
            /// 分数    
            /// </summary>    
            public int score;
        }

    }
        
}

运行结果如图:

这里写图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Bus Hound 5.0<br><br>Copyright (C) Perisoft 2000-2003. All rights reserved worldwide.<br><br>Bus Hound is a powerful software bus analyzer for capturing I/O and protocol from devices. Features include:<br><br> Supports every version of IDE, SCSI, USB, 1394<br> Supports all devices such as hard drives, DVD, mice, scanners, web cams, and everything else<br> Supports Windows 95, 98, Me, NT 4.0, 2000, 2003, XP and XP Embedded<br> Capture megabytes of I/O limited only by available memory<br> Automatically stop the capture upon a trigger condition<br> Measure individual read, write, and isochronous device performance<br> Captures device driver packets such as IRP’s<br> Filter what type of phases are captured<br> Run on an unlimited number of machines at the same time<br> Capture any number of devices in parallel, regardless of bus type<br> Fits on a diskette for easy transportability and quick downloads<br> Drag and drop captured data to other products in html format<br> Save captured data to a text file or zip file<br> Simple device selection from a graphical tree of devices<br> Capture the system startup process<br> Arrange captured data to user preferences such as the byte width per line<br> View low level protocol including SCSI sense data and USB setup packets<br> View microsecond resolution timing of each phase<br> Watch I/O on screen in real time as it happens<br> Pure software solution--no extra hardware or system changes needed<br><br><br><br>The Capture Window<br><br>Commands sent to devices consist of one or more phases. Examples of phases are command bytes, data bytes, and status bytes. Bus hound logs each phase complete with timing information and a description of the content.<br><br>Capture columns<br><br>Below are descriptions of information in each column of the Capture Window:<br><br>Device<br><br>Device ID. Each device is assigned a number which can be matched up with devices in the Devices Window. The first detected device on the system is Device ID 0, the second is Device ID 1, and so on. This field is useful in the event multiple devices are being captured in parallel.<br><br>For USB devices, the endpoint is also displayed (eg: 4.1 = device 4, endpoint 1).<br><br>Phase<br><br>Phase type. Please refer to the table for details of each phase type.<br><br>Phase Description<br>ADDR 8 byte 1394 transfer address<br>ATI 7 byte ATA task file returned from an IDE device<br>ATO 7 byte ATA task file sent to an IDE device <br>ATP Windows ATA_PASS_THROUGH data structure<br>CDB SCSI command descriptor block<br> (Known as a packet command for ATAPI devices)<br>CTL 8 byte setup packet of a USB control transfer<br>DI Data In (Device to PC transfer)<br>DO Data Out (PC to device transfer)<br>IOR Windows VXD I/O Request data structure<br>IRB Windows 1394 I/O Request Block data structure<br>IRP Windows I/O Request Packet data structure<br>ISOC Isochronous transfer data bytes<br>LEN Data transfer length of a DI,DO, or ISOC phase in <br> decimal units. This field is off by default and can be<br> turned on from the settings Window<br>LOCK 1394 lock transaction<br>NSTS Windows 4 byte kernel mode NTSTATUS field<br>RSET Bus or device reset<br>RSTS Windows VXD IOR status<br>SNS SCSI request sense data<br>SPT Windows SCSI Pass Through data structure<br>SRB Windows SCSI Request Block (SRB) data structure<br>SSTS Windows 1 byte SCSI Request Block (SRB) status<br>STAK Windows IO_STACK_LOCATION data structure<br>URB Windows USB Request Block (URB) data structure<br>USTS Windows 4 byte USBD_STATUS code<br><br><br>Data<br><br>Data bytes associated with the phase. Examples are command bytes, data transfer bytes, and status bytes.<br><br>Description<br><br>A text description of this phase provided for your convenience.<br><br>Delta<br><br>Elapsed time from the previous phase to the current phase. The following table describes the units of the time format.<br><br>Name Units<br>us Microseconds<br>ms Milliseconds<br>sc Seconds<br>mn Minutes<br>hr Hours<br>dy Days<br><br><br>Cmd.Phase.Ofs(rep)<br><br>This unique tag identifies the exact position within the captured data. All values are in decimal.<br><br>Cmd is the command number. Commands start at 1 and increment for each new command sent to a device.<br><br>Phase is the phase number within this command. A command is usually composed of multiple phases such as data transfer and status. This value starts at 1 and increments for each new phase within the command.<br><br>Ofs is the byte offset of the data within this phase. This value starts at 0 and increments for each byte of data in the data transfer.<br><br>Rep is the number of identical commands issued back to back. The repeat count feature can be turned off by deselecting the “Merge Repeated Commands” check box in the settings Window.<br><br>Date<br><br>Date the phase occurred in year/month/day format.<br><br>Time<br><br>Time the phase occurred in hour:minute:second.millisecond format. The hour ranges from 0 to 23 (military time).<br><br><br>Capturing the system startup process<br><br>If the Bus Hound application is exited while the Run button is pressed, the device driver portion of Bus Hound continues capturing data. In the event the system is restarted, it will start capturing data early in the system startup process.<br><br>If Bus Hound is exited while stopped, no capture will occur until returning to the product and pressing Run.<br><br>Customizing the capture display<br><br>The column order can be modified by dragging the column headers to the desired position. The byte width per line can be 1, 2, 4, 8, 16, or 32 bytes and is based on the width of the window. These settings are respected for Saving and drag & drop.<br><br>Searching<br><br>Searching can be performed from the capture window in either the up or down direction by typing the search string in the lower left edit box followed by pressing the up or down arrow to search up or down respectively. If the search string is not found, the trace position is not changed. Searching is not case sensitive.<br><br>Drag and Drop<br><br>To use drag and drop, first select the desired range of lines by clicking on the starting line, then hold down shift and click the ending line. The data can now be dragged using the mouse to another product.<br><br>Pressing control-c copies the selected lines to the clipboard.<br><br>Command Overlap<br><br>Overlapped commands are identified when a command starts before previous commands to the same device have completed. It is possible for Commands to be overlapped at the I/O subsystem level (which Bus Hound displays), but not at the hardware level.<br><br>Multiple DI/DO phases<br><br>Windows 9x only: if multiple DI/DO phases are listed for the same command, it indicates the transfer was split across multiple memory address ranges<br><br>PS2 Mouse data format<br><br>Below is the format of the data returned in the data in phase for PS/2 mice. This is known as the MOUSE_INPUT_DATA structure in the Windows DDK:<br><br>Offset Length Content<br>0 2 Not used<br>2 2 Position type:<br> 0000h = relative position<br> 0001h = absolute position<br>4 2 Button flags:<br> 0001h = left button down<br> 0002h = left button up<br> 0004h = right button down<br> 0008h = right button up<br> 0010h = middle button down<br> 0020h = middle button up<br> 0040h = button 4 down<br> 0080h = button 4 up<br> 0100h = button 5 down<br> 0200h = button 5 up<br> 0400h = mouse wheel<br>6 2 Mouse wheel data<br>8 4 Not used<br>12 4 X position<br>16 4 Y position<br>20 4 Device specific information<br><br>PS2 Keyboard data format<br><br>Below is the format of the data returned in the data in phase for PS/2 keyboards. This is known as the KEYBOARD_INPUT_DATA structure in the Windows DDK:<br><br>Offset Length Content<br>0 2 Not used<br>2 2 Scan code of key<br>4 2 Flags:<br> 0000h = key pressed<br> 0001h = key released<br> 0002h = extended scan code E0<br> 0004h = extended scan code E1<br>6 2 Not used<br>8 4 Device specific information<br><br><br><br>The Save Window<br><br>The Save button saves all captured data to the specified file. The format of the file can be either a text file containing standard ASCII characters or a Zip file. The data will be saved in the same column order and byte width as seen on the screen.<br><br>A comment can be provided that will be placed into the header of the captured data. The current date and time can be included in the comment by inserting %c anywhere inside the comment. If saving to a zip file, the comment is also used for the zip file comment.<br><br><br><br>The Settings Window<br><br>This Window allows you to customize the capture process. Checkbox options in this window are applied instantly. Numeric entries are applied by pressing the apply button, switching to another window, or exiting Bus Hound.<br><br>Buffer Size<br><br>Specifies the number of kilobytes of RAM to use for capturing data. The size is limited only by system RAM. If not enough RAM is available to satisfy the requested size, the size is reduced to available RAM. If you need to get as much space as possible, besides adding more RAM to a system you can also try setting the buffer size before starting other applications. Note: allocating a very large buffer size under Windows 95/98/Me can take a minute.<br><br>Max Phase<br><br>Specifies the maximum number of bytes that will be captured on each phase. Example: if Max Phase is set to 32 bytes and a 64K read operation occurs, only the first 32 bytes of the read will be captured. This option is useful for keeping the size of the captured data to a minimum.<br><br>Stop When...<br><br>These are triggers that allow the capture to automatically stop when the specified condition is met. Any combination of triggers may be selected. When a trigger condition is met, the capture stops and the trigger text is highlighted in red.<br><br>Any Other Error stops the capture when an error occurs that does not fall into any of the other categories.<br><br>Buffer Full stops the capture when Bus Hound's buffer is full. If Buffer Full is deselected, capturing continues after the buffer is full, keeping the most recently captured data.<br><br>Bus Reset stops the capture when a bus reset occurs.<br><br>Data Overrun stops the capture when a data overrun or data underrun occurs.<br><br>Hardware Error stops the capture when a hardware error occurs.<br><br>Invalid Command stops the capture when an invalid command is issued.<br><br>Media Error stops the capture when a device reports a media error such as a bad sector.<br><br>No Media stops the capture when a device reports no media is present.<br><br>Not Ready stops the capture upon a not ready, timeout, or busy condition.<br><br>Text Pattern / Hex Pattern stops the capture when the specified data pattern is detected in the captured data. For text patterns, the match is case sensitive. The pattern is checked against the data transferred in any phase including commands, data, and status.<br><br>Vendor Error stops the capture when a vendor unique error occurs.<br><br>Windows Error stops the capture when an operating system type error occurs.<br><br>Phases to Capture<br><br>Contains a list of all the phase types Bus Hound can capture. Placing a check mark next to a phase allows it to be captured. Removing a check mark next to a phase results in the phase not being captured. This option is useful for filtering out phases that are not of interest or including special operating system phases that are off by default.<br><br>To the right of the check box, a white circle may appear. This indicates the phase has been detected and exists in the captured data. If the circle blinks bright green, it is a real time activity light indicating the phase has occurred and has been captured.<br><br>Merge Repeated Commands<br><br>When selected, if a command occurs that is identical to the previous command, the new command will not be logged separately. Instead, the repeat count of the previous command is incremented. This option is useful for compacting the captured data when a device is being continually polled with the same command.<br><br>Enable Sounds<br><br>If this option is enabled, Bus Hound will make an audible "ping" if the capture, settings, or devices window is up and a trigger condition is met. <br><br>Columns to Display<br><br>Place a checkmark in the boxes to include the desired columns in the Capture Window. The selected columns will also be included in drag & drop and save operations. See the section “The Capture Window” for more details about each column.<br><br><br><br>The Devices Window<br><br>The list of devices represents every device on the system which Bus Hound supports. The list automatically refreshes to reflect new or removed devices. To select/deselect a device to capture, click in the check box next to the device. The selection will be applied instantly.<br><br>Each device is assigned a number which is in parenthesis before the name of the device. This number is displayed in the capture window under the "Device" column. The number reflects the order in which the device was added to the system.<br><br>If a device is displayed in a light font, it indicates the device is not currently present on the system.<br><br>Capture new devices<br><br>Selecting this checkbox will automatically capture data for new devices that are detected. This feature is useful for capturing the first commands sent to hot plugged devices. <br><br>Device Properties<br><br>This window pane displays details about the device such as the performance. The performance is calculated by summing the total bytes transferred divided by the total elapsed time of the commands. The performance statistics are cleared when the run button is pressed in the Capture window.<br><br>Send Commands<br><br>You can send your own custom commands to a device using Bus Commander. To start Bus Commander, highlight a device with the mouse and click the “Send Commands” button or simply double click the device. Bus Commander is a very powerful complementary tool that lets you submit USB, 1394, ATA and SCSI commands to devices. You can also perform operations like bus resets and hardware port i/o.<br><br><br><br>Files Installed<br><br>BUSHOUND.EXE - Bus Hound application<br>BUSCMDR.EXE - Bus Commander application<br>BHUNINST.EXE - uninstaller<br>BHLOG.EXE - capture to disk tool (site license version only)<br>BHOUND3.VXD - device driver for Windows 95, 98, Me<br>BHOUND4.SYS - device driver for Windows NT 4.0<br>BHOUND5.SYS - device driver for Windows 98, Me, 2000, 2003, XP<br>HELP.RTF - product help file (this file)<br><br><br><br>Site License<br><br>The site license version of Bus Hound includes the bhlog.exe command line tool in the folder where Bus Hound is installed. bhlog spools captured data to a disk file in real time. This tool raises the maximum capture size from available RAM to available disk space. bhlog also has the ability to retain captured data in the event a system freezes or reboots by directing captured data to a file on a network drive.<br><br><br><br>FAQ<br><br>1. What type of I/O is captured?<br><br>Bus Hound takes a snap shot of packets sent across the bus. This includes commands, data, status, and timing of each command. Bus Hound does not monitor individual hardware signals.<br><br>2. Will Bus Hound change the behavior of my devices?<br><br>No. Bus Hound simply “listens” for packets. Bus Hound does not alter commands, does not send its own commands, does not replace any system drivers, and does not access the hardware. The system and devices will operate identically whether Bus Hound is installed or not.<br><br>3. Will Bus Hound degrade system performance?<br><br>Customers capturing data from extremely fast devices in parallel have been impressed by Bus Hound’s ability not to effect performance. Bus Hound is even more innocuous when in the stopped state.<br><br>4. Which devices are supported?<br><br>All IDE, SCSI, USB and 1394 devices are supported including disk drives, mice, scanners, web cams, and everything else. Devices that emulate one of these buses are also supported such as certain parallel port devices.<br><br>5. Why are there duplicate devices?<br><br>For some devices, Windows first forms high level packets that are then translated into low level packets which are in turn sent to the hardware. Bus Hound shows several devices so you can choose which level of I/O you wish to capture.<br><br>6. What does capturing I/O for a controller do?<br><br>Some controllers receive commands and some do not. You can experiment capturing data for a controller to see if the packets are of interest.<br><br>7. What if Bus Hound does not show a device?<br><br>No devices are displayed when the system is started in safe mode. This is a safety feature to keep safe mode as clean as possible.<br><br>Devices which are marked with a problem in device manager are not displayed.<br><br>SCSI adapters are not displayed under Windows 95/98/Me unless they have one or more devices attached.<br><br>8. Why are some devices grayed out?<br><br>A grayed out device indicates it is currently not attached to the system.<br><br>9. Windows 95/98/Me crashes when pressing run. What do I do?<br><br>Due to limitations in the Windows 9x architecture, if too many device drivers ask to receive notification of I/O completion, the system will crash. Microsoft device drivers and other installed software such as Bus Hound need such notifications. To resolve this, remove software likely to have additional device drivers installed for the device. For CD/DVD drives, an easy solution is to rename the legacy scsi1hlp.vxd to scsi1hlp.bak which is in the windows/system/iosubsys folder.<br><br>10. Why am I not able to capture all 1394 events?<br><br>Some 1394 devices Bus Hound displays are logical devices such as AV/VHS devices. Select devices further up the tree to capture bus activity for such devices.<br><br>While Bus Hound logs every isochronous transaction, there is no practical way for Bus Hound to see every asynchronous transaction. If you need to see more 1394 activity, note Bus Hound can capture a great deal more in operating systems prior to XP, particularly for SBP-2 devices.<br><br>11. Why am I not seeing task file (ATA) commands for IDE hard drives?<br><br>Bus Hound captures ATA commands only when an application or driver explicitly sends an ATA command (eg: SMART, IDENTIFY). For normal file system requests, Bus Hound captures SCSI CDB's instead of ATA commands due to the monolithic nature of the Windows IDE device driver. Note the CDB's captured have a one to one relationship with ATA commands and can be easily translated to their native ATA equivalent. Also note the data captured with the CDB is identical to the ATA data transfer.<br><br>12. Where can I get more detailed information on the captured data?<br><br>For your convenience, please visit www.perisoft.net/engineer for handy reference data and specifications. Also please note the following resources:<br><br>Specification Location<br>USB www.usb.org <br>SCSI www.t10.org <br>IDE, ATA, ATAPI www.t13.org <br>1394, Firewire www.1394ta.org or www.ieee.org <br>Windows DDK www.microsoft.com/ddk <br><br>14. Where do I get support?<br><br>Visit www.perisoft.net. Any questions, comments, or problem reports on the free or full version are welcome.<br><br>
Java反编译软件JAD1 ad -sjava example1.class生成example1.java文件,十分准确。 This is README file for Jad - the fast Java Decompiler. Jad home page: http://www.geocities.com/SiliconValley/Bridge/8617/jad.html Copyright 1997-99 Pavel Kouznetsov ([email protected]). 0. Please read the disclaimer on the Jad home page. 1. Installation. Unzip jad.zip file into any appropriate directory on your hard drive. This will create two files: - an executable file named 'jad.exe' (Windows 95/NT) or 'jad' (Linux) - this README file No other setup is required. 2. How to use Jad To decompile a single JAVA class file 'example1.class' type the following: jad example1.class This command will create file 'example1.jad' in the current directory. If such file already exists Jad asks if you want to overwrite it. Option -o allows overwriting without confirmations. You can omit .class extension and/or use wildcards in the names of input files. Option -s <ext> allows to change output file extension: jad -sjava example1.class This command will create file 'example1.java'. Be careful when using options -o and -sjava together, because Jad can accidentally overwrite your own source files. Jad uses JAVA class name as an output file name. For example, if class file 'example1.class' contains JAVA class 'test1' then Jad will create file 'test1.jad' rather then 'example1.jad'. If you want to specify your own output file name use output redirection: jad -p example1.class > myexm1.java Option -d allows you to specify another directory for output files, which are created, by default, in the current directory. For example: jad -o -dtest -sjava *.class (or jad -o -d test -s java *.class, which has the same effect) This command will decompile all .class files in the current directory and place all output files with extension .java into directory 'test'. If you want to decompile the whole tree of JAVA classes, then use the following command: jad -o -r -sjava -dsrc tree/**/*.class This command will decompile all .class files located in all subdirectories of 'tree' and create output files in subdirectories of 'src' according to package names of classes. For example, if file 'tree/a/b/c.class' contains class 'c' from package 'a.b' then output file will have a name 'src/a/b/c.java'. Note the use of 'two asterisks' wildcard ('**') in the previous command. It is handled by Jad rather then command shell, so on UNIX the last argument should be single-quoted: jad -o -r -sjava -dsrc 'tree/**/*.class' In case you want to check the accuracy of the decompilation or just curious, there is an option -a which tells Jad to annotate the output with JAVA Virtual Machine bytecodes. Jad supports inner and anonymous classes. When Jad expands wildcards in the input file names, it automatically skips matching inner classes. On UNIX Jad skips inner classes if there is more than one class specified in the command line. Jad looks for inner classes in the directory of their top-level container class. 3. List of the command-line options. Jad accepts the following options: -a - annotate the output with JVM bytecodes -af - same as -a, but outputs fully qualified names when annotating; -clear - clears all prefixes, including the default ones (can be abbreviated as -cl) -b - output redundant braces (e.g., if(a) { b(); }, default: no) -d <dir> - directory for output files (will be created when necessary) -dead - try to decompile dead parts of code (if any) (default: no) -disass - disassemble method bytecodes (no JAVA source generated) -f - output fully qualified names for classes/fields/methods -ff - output class fields before methods (default: after methods) -i - output default initializers for all non-final fields -l<num> - split strings into pieces of maximum <num> chars (default: no) -nl - split strings on newline character (default: no) -nodos - do not check for class files in DOS mode (default: check) -nocast - don't generate auxiliary casts -nocode - don't generate the source code for methods -noconv - don't convert Java identifiers (default: do) -noctor - suppress the empty constructors -noinner - turn off the support of inner classes (default: turn on) -nolvt - ignore Local Variable Table information -nonlb - don't output a newline before opening brace (default: do) -o - overwrite output files without confirmation (default: no) -p - send decompiled code to STDOUT (e.g., for piping) -pi<num> - pack imports into one line after <num> imports (default: 3) -pv<num> - pack fields with identical types into one line (default: no) -pa <pfx>- prefix for all packages in generated source files -pc <pfx>- prefix for classes with numerical names (default: _cls) -pf <pfx>- prefix for fields with numerical names (default: _fld) -pe <pfx>- prefix for unused exception names (default: _ex) -pl <pfx>- prefix for locals with numerical names (default: _lcl) -pm <pfx>- prefix for methods with numerical names (default: _mth) -pp <pfx>- prefix for method parms with numerical names (default: _prm) -r - restore package directory structrure -s <ext> - output file extension (by default '.jad') -stat - display the total number of processed classes/methods/fields -t - use tabs instead of spaces for indentation -t<num> - use <num> spaces for indentation (default: 4) -v - display method names being decompiled -8 - convert UNICODE strings into 8-bit strings using current ANSI code page (Win32 only) -& - redirect stderr to stdout (Win32 only) All single-word options have three formats: -o - 'reverses' value of an option -o+ - set value to 'true' or 'on' -o- - set value to 'false' or 'off'
视频人脸识别,取代jmf。。。 Introduction JavaCV uses wrappers from the JavaCPP Presets of commonly used libraries by researchers in the field of computer vision (OpenCV, FFmpeg, libdc1394, PGR FlyCapture, OpenKinect, librealsense, CL PS3 Eye Driver, videoInput, ARToolKitPlus, and flandmark), and provides utility classes to make their functionality easier to use on the Java platform, including Android. JavaCV also comes with hardware accelerated full-screen image display (CanvasFrame and GLCanvasFrame), easy-to-use methods to execute code in parallel on multiple cores (Parallel), user-friendly geometric and color calibration of cameras and projectors (GeometricCalibrator, ProCamGeometricCalibrator, ProCamColorCalibrator), detection and matching of feature points (ObjectFinder), a set of classes that implement direct image alignment of projector-camera systems (mainly GNImageAligner, ProjectiveTransformer, ProjectiveColorTransformer, ProCamTransformer, and ReflectanceInitializer), a blob analysis package (Blobs), as well as miscellaneous functionality in the JavaCV class. Some of these classes also have an OpenCL and OpenGL counterpart, their names ending with CL or starting with GL, i.e.: JavaCVCL, GLCanvasFrame, etc. To learn how to use the API, since documentation currently lacks, please refer to the Sample Usage section below as well as the sample programs, including two for Android (FacePreview.java and RecordActivity.java), also found in the samples directory. You may also find it useful to refer to the source code of ProCamCalib and ProCamTracker as well as examples ported from OpenCV2 Cookbook and the associated wiki pages. Please keep me informed of any updates or fixes you make to the code so that I may integrate them into the next release. Thank you! And feel free to ask questions on the mailing list if you encounter any problems with the software! I am sure it is far from perfect... Downloads To install manually the JAR files, obtain the following archives and follow the instructions in the Manual Installation section below. JavaCV 1.3.3 binary archive javacv-platform-1.3.3-bin.zip (212 MB) JavaCV 1.3.3 source archive javacv-platform-1.3.3-src.zip (456 KB) The binary archive contains builds for Android, Linux, Mac OS X, and Windows. The JAR files for specific child modules or platforms can also be obtained individually from the Maven Central Repository. We can also have everything downloaded and installed automatically with: Maven (inside the pom.xml file) <dependency> <groupId>org.bytedeco</groupId> <artifactId>javacv-platform</artifactId> <version>1.3.3</version> </dependency> Gradle (inside the build.gradle file) dependencies { compile group: 'org.bytedeco', name: 'javacv-platform', version: '1.3.3' } sbt (inside the build.sbt file) libraryDependencies += "org.bytedeco" % "javacv-platform" % "1.3.3" This downloads binaries for all platforms, but to get binaries for only one platform we can set the javacpp.platform system property (via the -D command line option) to something like android-arm, linux-x86_64, macosx-x86_64, windows-x86_64, etc. Please refer to the README.md file of the JavaCPP Presets for details. Another option available for Scala users is sbt-javacv. Required Software To use JavaCV, you will first need to download and install the following software: An implementation of Java SE 7 or newer: OpenJDK http://openjdk.java.net/install/ or Sun JDK http://www.oracle.com/technetwork/java/javase/downloads/ or IBM JDK http://www.ibm.com/developerworks/java/jdk/ Further, although not always required, some functionality of JavaCV also relies on: CL Eye Platform SDK (Windows only) http://codelaboratories.com/downloads/ Android SDK API 14 or newer http://developer.android.com/sdk/ JOCL and JOGL from JogAmp http://jogamp.org/ Finally, please make sure everything has the same bitness: 32-bit and 64-bit modules do not mix under any circumstances. Manual Installation Simply put all the desired JAR files (opencv*.jar, ffmpeg*.jar, etc.), in addition to javacpp.jar and javacv.jar, somewhere in your class path. Here are some more specific instructions for common cases: NetBeans (Java SE 7 or newer): In the Projects window, right-click the Libraries node of your project, and select "Add JAR/Folder...". Locate the JAR files, select them, and click OK. Eclipse (Java SE 7 or newer): Navigate to Project > Properties > Java Build Path > Libraries and click "Add External JARs...". Locate the JAR files, select them, and click OK. IntelliJ IDEA (Android 4.0 or newer): Follow the instructions on this page: http://developer.android.com/training/basics/firstapp/ Copy all the JAR files into the app/libs subdirectory. Navigate to File > Project Structure > app > Dependencies, click +, and select "2 File dependency". Select all the JAR files from the libs subdirectory. After that, the wrapper classes for OpenCV and FFmpeg, for example, can automatically access all of their C/C++ APIs: OpenCV documentation FFmpeg documentation Sample Usage The class definitions are basically ports to Java of the original header files in C/C++, and I deliberately decided to keep as much of the original syntax as possible. For example, here is a method that tries to load an image file, smooth it, and save it back to disk: import static org.bytedeco.javacpp.opencv_core.*; import static org.bytedeco.javacpp.opencv_imgproc.*; import static org.bytedeco.javacpp.opencv_imgcodecs.*; public class Smoother { public static void smooth(String filename) { IplImage image = cvLoadImage(filename); if (image != null) { cvSmooth(image, image); cvSaveImage(filename, image); cvReleaseImage(image); } } } JavaCV also comes with helper classes and methods on top of OpenCV and FFmpeg to facilitate their integration to the Java platform. Here is a small demo program demonstrating the most frequently useful parts: import java.io.File; import java.net.URL; import org.bytedeco.javacv.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.indexer.*; import static org.bytedeco.javacpp.opencv_core.*; import static org.bytedeco.javacpp.opencv_imgproc.*; import static org.bytedeco.javacpp.opencv_calib3d.*; import static org.bytedeco.javacpp.opencv_objdetect.*; public class Demo { public static void main(String[] args) throws Exception { String classifierName = null; if (args.length > 0) { classifierName = args[0]; } else { URL url = new URL("https://raw.github.com/Itseez/opencv/2.4.0/data/haarcascades/haarcascade_frontalface_alt.xml"); File file = Loader.extractResource(url, null, "classifier", ".xml"); file.deleteOnExit(); classifierName = file.getAbsolutePath(); } // Preload the opencv_objdetect module to work around a known bug. Loader.load(opencv_objdetect.class); // We can "cast" Pointer objects by instantiating a new object of the desired class. CvHaarClassifierCascade classifier = new CvHaarClassifierCascade(cvLoad(classifierName)); if (classifier.isNull()) { System.err.println("Error loading classifier file \"" + classifierName + "\"."); System.exit(1); } // The available FrameGrabber classes include OpenCVFrameGrabber (opencv_videoio), // DC1394FrameGrabber, FlyCaptureFrameGrabber, OpenKinectFrameGrabber, OpenKinect2FrameGrabber, // RealSenseFrameGrabber, PS3EyeFrameGrabber, VideoInputFrameGrabber, and FFmpegFrameGrabber. FrameGrabber grabber = FrameGrabber.createDefault(0); grabber.start(); // CanvasFrame, FrameGrabber, and FrameRecorder use Frame objects to communicate image data. // We need a FrameConverter to interface with other APIs (Android, Java 2D, or OpenCV). OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage(); // FAQ about IplImage and Mat objects from OpenCV: // - For custom raw processing of data, createBuffer() returns an NIO direct // buffer wrapped around the memory pointed by imageData, and under Android we can // also use that Buffer with Bitmap.copyPixelsFromBuffer() and copyPixelsToBuffer(). // - To get a BufferedImage from an IplImage, or vice versa, we can chain calls to // Java2DFrameConverter and OpenCVFrameConverter, one after the other. // - Java2DFrameConverter also has static copy() methods that we can use to transfer // data more directly between BufferedImage and IplImage or Mat via Frame objects. IplImage grabbedImage = converter.convert(grabber.grab()); int width = grabbedImage.width(); int height = grabbedImage.height(); IplImage grayImage = IplImage.create(width, height, IPL_DEPTH_8U, 1); IplImage rotatedImage = grabbedImage.clone(); // Objects allocated with a create*() or clone() factory method are automatically released // by the garbage collector, but may still be explicitly released by calling release(). // You shall NOT call cvReleaseImage(), cvReleaseMemStorage(), etc. on objects allocated this way. CvMemStorage storage = CvMemStorage.create(); // The OpenCVFrameRecorder class simply uses the CvVideoWriter of opencv_videoio, // but FFmpegFrameRecorder also exists as a more versatile alternative. FrameRecorder recorder = FrameRecorder.createDefault("output.avi", width, height); recorder.start(); // CanvasFrame is a JFrame containing a Canvas component, which is hardware accelerated. // It can also switch into full-screen mode when called with a screenNumber. // We should also specify the relative monitor/camera response for proper gamma correction. CanvasFrame frame = new CanvasFrame("Some Title", CanvasFrame.getDefaultGamma()/grabber.getGamma()); // Let's create some random 3D rotation... CvMat randomR = CvMat.create(3, 3), randomAxis = CvMat.create(3, 1); // We can easily and efficiently access the elements of matrices and images // through an Indexer object with the set of get() and put() methods. DoubleIndexer Ridx = randomR.createIndexer(), axisIdx = randomAxis.createIndexer(); axisIdx.put(0, (Math.random()-0.5)/4, (Math.random()-0.5)/4, (Math.random()-0.5)/4); cvRodrigues2(randomAxis, randomR, null); double f = (width + height)/2.0; Ridx.put(0, 2, Ridx.get(0, 2)*f); Ridx.put(1, 2, Ridx.get(1, 2)*f); Ridx.put(2, 0, Ridx.get(2, 0)/f); Ridx.put(2, 1, Ridx.get(2, 1)/f); System.out.println(Ridx); // We can allocate native arrays using constructors taking an integer as argument. CvPoint hatPoints = new CvPoint(3); while (frame.isVisible() && (grabbedImage = converter.convert(grabber.grab())) != null) { cvClearMemStorage(storage); // Let's try to detect some faces! but we need a grayscale image... cvCvtColor(grabbedImage, grayImage, CV_BGR2GRAY); CvSeq faces = cvHaarDetectObjects(grayImage, classifier, storage, 1.1, 3, CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_DO_ROUGH_SEARCH); int total = faces.total(); for (int i = 0; i < total; i++) { CvRect r = new CvRect(cvGetSeqElem(faces, i)); int x = r.x(), y = r.y(), w = r.width(), h = r.height(); cvRectangle(grabbedImage, cvPoint(x, y), cvPoint(x+w, y+h), CvScalar.RED, 1, CV_AA, 0); // To access or pass as argument the elements of a native array, call position() before. hatPoints.position(0).x(x-w/10) .y(y-h/10); hatPoints.position(1).x(x+w*11/10).y(y-h/10); hatPoints.position(2).x(x+w/2) .y(y-h/2); cvFillConvexPoly(grabbedImage, hatPoints.position(0), 3, CvScalar.GREEN, CV_AA, 0); } // Let's find some contours! but first some thresholding... cvThreshold(grayImage, grayImage, 64, 255, CV_THRESH_BINARY); // To check if an output argument is null we may call either isNull() or equals(null). CvSeq contour = new CvSeq(null); cvFindContours(grayImage, storage, contour, Loader.sizeof(CvContour.class), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE); while (contour != null && !contour.isNull()) { if (contour.elem_size() > 0) { CvSeq points = cvApproxPoly(contour, Loader.sizeof(CvContour.class), storage, CV_POLY_APPROX_DP, cvContourPerimeter(contour)*0.02, 0); cvDrawContours(grabbedImage, points, CvScalar.BLUE, CvScalar.BLUE, -1, 1, CV_AA); } contour = contour.h_next(); } cvWarpPerspective(grabbedImage, rotatedImage, randomR); Frame rotatedFrame = converter.convert(rotatedImage); frame.showImage(rotatedFrame); recorder.record(rotatedFrame); } frame.dispose(); recorder.stop(); grabber.stop(); } } Furthermore, after creating a pom.xml file with the following content: <project> <modelVersion>4.0.0</modelVersion> <groupId>org.bytedeco.javacv</groupId> <artifactId>demo</artifactId> <version>1.3.3</version> <dependencies> <dependency> <groupId>org.bytedeco</groupId> <artifactId>javacv-platform</artifactId> <version>1.3.3</version> </dependency> </dependencies> </project> And by placing the source code above in src/main/java/Demo.java, we can use the following command to have everything first installed automatically and then executed by Maven: $ mvn compile exec:java -Dexec.mainClass=Demo Build Instructions If the binary files available above are not enough for your needs, you might need to rebuild them from the source code. To this end, the project files were created for: Maven 3.x http://maven.apache.org/download.html JavaCPP 1.3 https://github.com/bytedeco/javacpp JavaCPP Presets 1.3 https://github.com/bytedeco/javacpp-presets Once installed, simply call the usual mvn install command for JavaCPP, its Presets, and JavaCV. By default, no other dependencies than a C++ compiler for JavaCPP are required. Please refer to the comments inside the pom.xml files for further details. Project lead: Samuel Audet [samuel.audet at gmail.com](mailto:samuel.audet at gmail.com) Developer site: https://github.com/bytedeco/javacv Discussion group: http://groups.google.com/group/javacv
JAVA模版引擎Freemarker常用标签(一) 1. if指令 这是一个典型的分支控制指令,该指令的作用完全类似于Java语言的if,if指令的语法格式如下: <#if condition>... <#elseif condition>... <#elseif condition>... <#else> ... </#if> 例子如下: <#assign age=23> <#if (age>60)>老年人 <#elseif (age>40)>年人 <#elseif (age>20)>青年人 <#else> 少年人 </#if> 输出结果是:青年人 上面的代码的逻辑表达式用括号括起来主要是因为里面有>符号,由于FreeMarker会将>符号当成标签的结束字符,可能导致程序出错,为了避免这种情况,我们应该在凡是出现这些符号的地方都使用括号. <#if animals.python.price < animals.elephant.price> Pythons are cheaper than elephants today. <#else> Pythons are not cheaper than elephants today. </#if> 2、 switch , case , default , break指令 这些指令显然是分支指令,作用类似于Java的switch语句,switch指令的语法结构如下: <#switch value> <#case refValue>...<#break> <#case refValue>...<#break> <#default>... </#switch> 3、 list, break指令 list指令是一个迭代输出指令,用于迭代输出数据模型的集合,list指令的语法格式如下: <#list sequence as item> ... </#list> 上面的语法格式,sequence就是一个集合对象,也可以是一个表达式,但该表达式将返回一个集合对象,而item是一个任意的名字,就是被迭代输出的集合元素.此外,迭代集合对象时,还包含两个特殊的循环变量: item_index:当前变量的索引值 item_has_next:是否存在下一个对象 也可以使用<#break>指令跳出迭代 例子如下: <#list ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"] as x> ${x_index + 1}.${x}<#if x_has_next>,</if> <#if x="星期四"><#break></#if> </#list> <p>We have these animals: <table border=1> <tr><th>Name<th>Price <#list animals as being> <tr><td>${being.name}<td>${being.price} Euros </#list> </table> 输出为: <p>We have these animals: <table border=1> <tr><th>Name<th>Price <tr><td>mouse<td>50 Euros <tr><td>elephant<td>5000 Euros <tr><td>python<td>4999 Euros </table> 4、include指令 include指令的作用类似于JSP的包含指令,用于包含指定页.include指令的语法格式如下: <#include filename [options]> 在上面的语法格式,两个参数的解释如下: filename:该参数指定被包含的模板文件 options:该参数可以省略,指定包含时的选项,包含encoding和parse两个选项,其encoding指定包含页面时所用的解码集,而parse指定被包含文件是否作为FTL文件来解析,如果省略了parse选项值,则该选项默认是true. <html> <head> <title>Test page</title> </head> <body> <h1>Test page</h1> <p>Blah blah... <#include "/copyright_footer.html"> </body> </html> 5、 import指令 该指令用于导入FreeMarker模板的所有变量,并将该变量放置在指定的Map对象,import指令的语法格式如下: <#import "/lib/common.ftl" as com> 上面的代码将导入/lib/common.ftl模板文件的所有变量,将这些变量放置在一个名为com的Map对象. 创建库 ? 下面是一个创建库的例子(假设保存在lib/my_test.ftl): <#macro copyright date> <p>Copyright (C) ${date} Julia Smith. All rights reserved. <br>Email: ${mail}</p> </#macro> <#assign mail = "[email protected]"> ? 使用import指令导入库到模板,Freemarker会为导入的库创建新的名字空间,并可以通过import指令指定的散列变量访问库的变量: <#import "/lib/my_test.ftl" as my> <#assign mail="[email protected]"> <@my.copyrightdate="1999-2002"/> ${my.mail} ${mail} 输出结果: <p>Copyright (C) 1999-2002 Julia Smith. All rights reserved. <br>Email: [email protected]</p> [email protected] [email protected] 可以看到例子使用的两个同名变量并没有冲突,因为它们位于不同的名字空间 l 可以使用assign指令在导入的名字空间创建或替代变量,下面是一个例子: <#import "/lib/my_test.ftl" as my> ${my.mail} <#assign mail="[email protected]" in my> ${my.mail} l 输出结果: [email protected] [email protected] l 数据模型的变量任何地方都可见,也包括不同的名字空间,下面是修改的库: <#macro copyright date> <p>Copyright (C) ${date} ${user}. All rights reserved.</p> </#macro> <#assign mail = "${user}@acme.com"> l 假设数据模型的user变量的值是Fred,则下面的代码: <#import "/lib/my_test.ftl" as my> <@my.copyright date="1999-2002"/> ${my.mail} l 输出结果: <p>Copyright (C) 1999-2002 Fred. All rights reserved.</p> 1.6 算术运算符 FreeMarker表达式完全支持算术运算,FreeMarker支持的算术运算符包括:+, - , * , / , % 看如下的代码: <#assign x=5> ${ x * x - 100 } ${ x /2 } ${ 12 } 输出结果是: -75 2.5 2 在表达式使用算术运算符时要注意以下几点: 1,运算符两边的运算数字必须是数字 2,使用+运算符时,如果一边是数字,一边是字符串,就会自动将数字转换为字符串再连接,如:${3 + "5"},结果是:35 使用内建的int函数可对数值取整,如: <#assign x=5> ${ (x/2)?int } ${ 1.1?int } ${ 1.999?int } ${ -1.1?int } ${ -1.999?int } 结果是:2 1 1 -1 -1 1.7 比较运算符 表达式支持的比较运算符有如下几个: 1. =或者==:判断两个值是否相等. 2. !=:判断两个值是否不等. 3. >或者gt:判断左边值是否大于右边值 4. >=或者gte:判断左边值是否大于等于右边值 5. <或者lt:判断左边值是否小于右边值 6. <=或者lte:判断左边值是否小于等于右边值 注意:=和!=可以用于字符串,数值和日期来比较是否相等,但=和!=两边必须是相同类型的值,否则会产生错误,而且FreeMarker是精确比 较,"x","x ","X"是不等的.其它的运行符可以作用于数字和日期,但不能作用于字符串,大部分的时候,使用gt等字母运算符代替>会有更好的效果,因为 FreeMarker会把>解释成FTL标签的结束字符,当然,也可以使用括号来避免这种情况,如:<#if (x>y)> 1.8 逻辑运算符 逻辑运算符有如下几个: 逻辑与:&& 逻辑或:|| 逻辑非:! 逻辑运算符只能作用于布尔值,否则将产生错误 1.9 内建函数 FreeMarker还提供了一些内建函数来转换输出,可以在任何变量后紧跟?,?后紧跟内建函数,就可以通过内建函数来轮换输出变量.下面是常用的内建的字符串函数: html:对字符串进行HTML编码 cap_first:使字符串第一个字母大写 lower_case:将字符串转换成小写 upper_case:将字符串转换成大写 trim:去掉字符串前后的空白字符 下面是集合的常用内建函数 size:获取序列元素的个数 下面是数字值的常用内建函数 int:取得数字的整数部分,结果带符号 例如: <#assign test="Tom & Jerry"> ${test?html} ${test?upper_case?html} 结果是:Tom & Jerry TOM & JERRY 1.10 空值处理运算符 FreeMarker对空值的处理非常严格,FreeMarker的变量必须有值,没有被赋值的变量就会抛出异常,因为FreeMarker未赋值 的变量强制出错可以杜绝很多潜在的错误,如缺失潜在的变量命名,或者其他变量错误.这里所说的空值,实际上也包括那些并不存在的变量,对于一个Java的 null值而言,我们认为这个变量是存在的,只是它的值为null,但对于FreeMarker模板而言,它无法理解null值,null值和不存在的变 量完全相同. 为了处理缺失变量,FreeMarker提供了两个运算符: !: 指定缺失变量的默认值 ??: 判断某个变量是否存在 其,!运算符的用法有如下两种: variable!或variable!defaultValue,第一种用法不给缺失的变量指定默认值,表明默认值是空字符串,长度为0的集合,或者长度为0的Map对象. 使用!指定默认值时,并不要求默认值的类型和变量类型相同.使用??运算符非常简单,它总是返回一个布尔值,用法为:variable??,如果该变量存在,返回true,否则返回false ########################### 最常用的概念 1、 scalars:存储单值 字符串:简单文本由单或双引号括起来。 数字:直接使用数值。 日期:通常从数据模型获得 布尔值:true或false,通常在<#if …>标记使用 2、 hashes:充当其它对象的容器,每个都关联一个唯一的查询名字 具有一个唯一的查询名字和他包含的每个变量相关联。 3、 sequences:充当其它对象的容器,按次序访问 使用数字和他包含的每个变量相关联。索引值从0开始。 4、 集合变量: 除了无法访问它的大小和不能使用索引来获得它的子变量:集合可以看作只能由<#list...>指令使用的受限sequences。 5、 方法:通过传递的参数进行计算,以新对象返回结果 方法变量通常是基于给出的参数计算值在数据模型定义。 6、 用户自定义FTL指令:宏和变换器 7、 节点 节点变量表示为树型结构的一个节点,通常在XML处理使用。 在模板里对sequences和hashes初始化 sequences 1. [“you”,”me”,”he”] 2. 1..100 3. [ {“Akey”:”Avalue”},{“Akey1”:”Avalue1”}, {“Bkey”:”Bvalue”},{“Bkey1”:”Bvalue1”}, ] hashes {“you”:”a”,”me”:”b”,”he”:”c”} 注释标志 <#-- 这里是注释 --> 旧版本的freemarker采用的是<#comment> 注释 </#comment>方法 sequences内置方法 sequence?first 返回sequence的第一个值;前提条件sequence不能是null sequence?last 返回sequence最后一个值 sequence?reverse 反转sequence的值 sequence?size 返回sequence的大小 sequence?sort 对sequence按里面的对象toString()的结果进行排序 sequence?sort_by(value) 对sequence 按里面的对象的属性value进行排序 如: sequence里面放入的是10 个user对象,user对象里面包含name,age等属性 sequence?sort_by(name) 表示所有的user按user.name进行排序 hashes内置方法 hash?keys 返回hash里的所有keys, 返回结果类型sequence hash?values 返回hash里的所有value, 返回结果类型sequence 模板 使用FTL(freeMarker模板语言)编写 组成部分 一、整体结构 1、注释:<#--注释内容-->,不会输出。 2、文本:直接输出。 3、interpolation:由 ${var} 或 #{var} 限定,由计算值代替输出。 4、FTL标记 二.表达式 1、直接指定值: 1-1、字符串: 由双引号或单引号括起来的字符串,其的特殊字符(如' " \等)需要转义。 1-2、raw字符串: 有一种特殊的字符串称为raw字符串,被认为是纯文本,其的\和{等不具有特殊含义,该类字符串在引号前面加r,下面是一个例子: ${r"/${data}"year""}屏幕输出结果为:/${data}"year" 转义 含义 序列 \" 双引号(u0022) \' 单引号(u0027) \\ 反斜杠(u005C) \n 换行(u000A) \r Return (u000D) \t Tab (u0009) \b Backspace (u0008) \f Form feed (u000C) \l < \g > \a & \{ { \xCode 4位16进制Unicode代码 1-3、数字:直接输入,不需要引号 1)、精度数字使用“.”分隔,不能使用分组符号 2)、目前版本不支持科学计数法,所以“1E3”是错误的 3)、不能省略小数点前面的0,所以“.5”是错误的 4)、数字8、+8、08和8.00都是相同的 1-4、布尔值:true和false,不使用引号 1-5、序列:由逗号分隔的子变量列表,由[]方括号限定。 1)、子变量列表可以是表达式 2)、可以使用数字范围定义数字序列,不需要方括号限定,例如2..5等同于[2, 3, 4, 5],但是更有效率,可以定义反递增范围如:5..2。 1-6、散列(hash) 1)、由逗号分隔的键/值列表,由{}大括号限定,键和值之间用冒号分隔,如:{"key1":valu1,"key2":"character string"....} 2)、键和值都是表达式,但是键必须是字符串。 2、获取变量: 2-1、顶层变量:${变量名} 变量名只能是字母、数字、下划线、$、#、@ 的组合,且不能以数字开头。 2-2、散列:有两种方法 1)、点语法:变量名字和顶层变量的名字受同样的限制 2)、方括号语法:变量名字无限制,可以是任意的表达式的结果 book.author.name book.author.["name"] book["author"].name book["author"]["name"] 以上是等价的。 2-3、序列:使用散列的方括号语法获取变量,方括号的表达式结果必须为数字。注意:第一个项目的索引为0。可以使用 [startindex..endindex]语法获取序列片段。 2-4、特殊变量:FreeMarker内定义变量,使用.variablename语法访问。 3、字符串操作 3-1、interpolation:使用${}或#{}在文本部分插入表达式的值,例如: ${"hello${username}!"} ${"${username}${username}${username}"} 也可以使用+来获得同样的结果: ${"hello"+username+"!"} ${username+username+username} 注意:${}只能用于文本部分而不能出现于标记内。 <#if ${user.login}>或<#if "${user.login}">都是错误的; <#if user.login>是正确的。 本例user.login的值必须是布尔类型。 3-2、子串: 举例说明:假如user的值为"Big Joe" ${user[0]}${user[4]}结果是:BJ ${user[1..4]}结果是:ig J 4、序列操作 4-1、连接操作:可以使用+来操作,例如: ["title","author"]+["month","day"] 5、散列操作 5-1、连接操作:可以使用+来操作,如果有相同的KEY,则右边的值会替代左边的值,例如: {"title":散列,"author":"emma"}+{"month":5,"day":5}+{"month":6}结果month的值就是6。 6、算术运算 6-1、操作符:+、-、*、/、% 除+号以外的其他操作符两边的数据,必须都是数字类型。 如果+号操作符一边有一个字符型数据,会自动将另一边的数据转换为字符型数据,运算结果为字符型数据。 6-2、比较操作符: 1}、= 2}、== 3}、!= 4}、< 5}、<= 6}、> 7}、>= 1-3的操作符,两边的数据类型必须相同,否则会产生错误 4-7的操作符,对于日期和数字可以使用,字符串不可以使用。 注意: 1}、FreeMarker是精确比较,所以"x" "x " "X"是不等的。 2}、因为<和>对FTL来说是开始和结束标记,所以,可以用两种方法来避免这种情况: 一种是使用括号<#if (a<b)> 另一是使用替代输出,对应如下: < lt <= lte > gt >= gte 6-3、逻辑操作符:只能用于布尔值,否则会出现错误。 &&(and)与运算 ||(or)或运算 !(not)非运算 6-4、内建函数:使用方法类似于访问散列的子变量,只是使用?代替.例如:${test?upper_case?html} 常用的内建函数列举如下: 1}、字符串使用: html:对字符串进行HTML编码 cap_first:字符串第一个字母大写 lower_first:字符串第一个字母小写 upper_case:将字符串转换成大写 trim:去掉字符前后的空白字符 2)、序列使用: size:获得序列元素的数目 3)、数字使用: int:取得数字的整数部分 7、操作符的优先顺序: 后缀:[subbarName][subStringRange].(mathodParams) 一元:+expr、-expr、! (not) 内建:? 乘法:*、/、% 加法:+、- 关系:<、<=、>、>= (lt、lte、gt、gte) 相等:=、==、!= 逻辑与:&& (and) 逻辑或:|| (or) 数字范围:.. 四、interpolation inperpolation只能用于文本,有两种类型:通用interpolation及数字interpolation 1、通用interpolation 如${expr} 1-1、插入字符串值:直接输出表达式结果。 1-2、插入数字值:根据缺省格式(由setting指令设置)将表达式结果转换成文本输出;可以使用内建函数string来格式化单个interpolation 如: <#setting number_format="currency" /> <#assign answer=42 /> ${answer} <#-- ¥42.00 --> ${answer?string} <#-- ¥42.00 --> ${answer?string.number} <#-- 42 --> ${answer?string.currency} <#-- ¥42.00 --> ${answer?string.percent} <#-- 42,00% --> 1-3、插入日期值:根据缺省格式(由setting指令设置)将表达式结果转换成文本输出;可以使用内建函数string来格式化单个interpolation 如: ${lastupdata?string("yyyy-MM-dd HH:mm:ss zzzz")} <#-- 2003-04-08 21:24:44 Pacific Daylight Time --> ${lastupdata?string("EEE,MMM d, ''yy")} <#-- tue,Apr 8, '03 --> ${lastupdata?string("EEEE,MMMM dd, yyyy,hh:mm:ss a '('zzz')'")} <#-- Tuesday,April 08, 2003, 09:24:44 PM (PDT)--> 1-4、插入布尔值:根据缺省格式(由setting指令设置)将表达式结果转换成文本输出;可以使用内建函数string来格式化单个interpolation 如: <#assign foo=ture /> ${foo?string("yes","no")} <#-- yes --> 2、数字interpolation: 有两种形式: 1)、#{expr} 2)、#{expr;format}:format可以用来格式化数字,format可以是如下: mX:小数部分最小X位 MX:小数部分最大X位 例如: <#assign x=2.582 /> <#assign y=4 /> #{x;M2} <#-- 2.58 --> #{y;M2} <#-- 4 --> #{x;m1} <#-- 2.582 --> #{y;m1} <#-- 4.0 --> #{x;m1M2} <#-- 2.58 --> #{y;m1M2} <#-- 4.0 --> 宏 宏和变换器变量是两种不同类型的用户自定义指令,他们的区别是: 宏可以在模板用macro指令来定义 变换器是在模板外由程序定义 1、宏:和某个变量关联的模板片段,以便在模板通过用户自定义指令使用该变量 1-1、基本用法: 例如: <#macro greet> <font size="+2"> Hello JOE! </#macro> 使用时: <@greet></@greet> 如果没有体内容也可以用 <@greet /> 1-2、变量: 1)、可以在宏定义之后定义参数,宏参数是局部变量,只在宏定义有效。如: <#macro greet person> <font size="+2"> Hello ${person}! </#macro> 使用时: <@greet person="emma"> and <@greet person="LEO"> 输出为: <font size="+2"> Hello emma! <font size="+2"> Hello LEO! 注意:宏的参数是FTL表达式,所以,person=emma和上面的例子具有不同的意义,这意味着将变量emma的值传给person,这个值可能是任意一种数据类型,甚至是一个复杂的表达式。 宏可以有多个参数,使用时参数的次序是无关的,但是只能使用宏定义的参数,并且对所有参数赋值。如: <#macro greet person color> <font size="+2" color="${color}"> Hello ${person}! </#macro> 使用时: <@greet color="black" person="emma" />正确 <@greet person="emma" />错误,color没有赋值,此时,如果在定义宏时为color定义缺省值<#macro greet person color="black">这样的话,这个使用方法就是正确的。 <@greet color="black" person="emma" bgcolor="yellow" />错误,宏greet定义未指定bgcolor这个参数 2、嵌套内容: 2-1、自定义指令可以有嵌套内容,使用<#nested>指令,执行自定义指令开始和结束标记之间的模板片段。例如: <#macro greet> <#nested> </#macro> <@greet>hello Emma!</@greet> 输出为 hello Emma! 2-2、<#nested>指令可以被多次调用,例如 <#macro greet> <#nested> <#nested> <#nested> <#nested> </#macro> <@greet>hello Emma!</@greet> 输出为 hello Emma! hello Emma! hello Emma! hello Emma! 2-3、嵌套的内容可以是有效的FTL,例如: <#macro welcome> <#nested> </#macro> <#macro greet person color="black"> <font size="+2" color="${color}"> Hello ${person}! </#macro> <@welcome> <@greet person="Emma" color="red" /> <@greet person="Andrew" /> <@greet person="Peter" /> </@welcome> 输出为: <font size="+2" color="red"> Hello Emma! <font size="+2" color="black"> Hello Andrew! <font size="+2" color="black"> Hello Peter! 2-4、宏定义的局部变量对嵌套内容是不可见的,例如: <#macro repeat count> <#local y="test" /> <#list 1..count as x> ${y}${count}/${x}:<#nested /> </#list> </#macro> <@repeat count=3> ${y?default("?")} ${x?default("?")} ${count?default("?")} </@repeat> 输出结果为 test 3/1:??? test 3/2:??? test 3/3:??? 2-5、在宏定义使用循环变量,通常用来重复嵌套内容,基本用法为:作为nested指令的参数,传递循环变量的实际值,而在调用自定义指令时,在标记的参数后面指定循环变量的名字。 例如: <#macro repeat count> <#list 1..count as x> <#nested x,x/2,x==count /> </#list> </#macro> <@repeat count=4;c,halfc,last> ${c}. ${halfc} <#if last> last! </#if> </@repeat> 输出结果是 1. 0.5 2. 1 3. 1.5 4. 2last! 注意:指定循环变量的数目和用户定义指令开始标记指定的不同不会有问题 调用时,少指定循环变量,多指定的值会不见 调用时,多指定循环变量,多余的循环变量不会被创建 二、在模板定义变量 1、在模板定义的变量有三种类型 1-1、plain变量:可以在模板的任何地方访问,包括使用include指令插入的模板,使用assign指令创建和替换。 1-2、局部变量:在宏定义体有效,使用local指令创建和替换。 1-3、循环变量:只能存在于指令的嵌套内容,由指令(如list)自动创建。 注意: 1)、宏的参数是局部变量,不是循环变量。 2)、局部变量隐藏同名的plain变量 3)、循环变量隐藏同名的plain变量和局部变量。 例如: <#assign x="plain"> 1. ${x} <#-- plain --> <@test /> 6. ${x} <#list ["loop"] as x> 7. ${x} <#-- loop --> <#assign x="plain2"> 8. ${x} <#-- loop --> </#list> 9. ${x} <#-- plain2 --> <#macro test> 2. ${x} <#-- plain --> <#local x="local"> 3. ${x} <#-- local --> <#list ["loop"] as x> 4. ${x} <#-- loop --> </#list> 5. ${x} <#-- local --> </#macro> 4)、内部循环变量隐藏同名的外部循环变量 <#list ["loop1"] as x> ${x} <#-- loop1 --> <#list ["loop2"] as x> ${x} <#-- loop2 --> <#list ["loop3"] as x> ${x} <#-- loop3 --> </#list> ${x} <#-- loop2 --> </#list> ${x} <#-- loop1 --> </#list> 5)、模板的变量会隐藏数据模型的同名变量,如果需访问数据模型的变量,使用特殊变量global。 例如: 假设数据模型的user值为Emma <#assign user="Man"> ${user} <#-- Man --> ${.global.user} <#-- Emma --> macro, nested, return 语法 <#macro name param1 param2 ... paramN> ... <#nested loopvar1, loopvar2, ..., loopvarN> ... <#return> ... </#macro> 用例 <#macro test foo bar="Bar"[A1] baaz=-1> Test text, and the params: ${foo}, ${bar}, ${baaz} </#macro> <@test foo="a" bar="b" baaz=5*5-2/> <@test foo="a" bar="b"/> <@test foo="a" baaz=5*5-2/> <@test foo="a"/> 输出 Test text, and the params: a, b, 23 Test text, and the params: a, b, -1 Test text, and the params: a, Bar, 23 Test text, and the params: a, Bar, -1 定义循环输出的宏 <#macro list title items> ${title?cap_first}: <ul> <#list items as x> <li>${x?cap_first} </#list> </#macro> <@list items=["mouse", "elephant", "python"] title="Animals"/> 输出结果 Animals: 包含body的宏 <#macro repeat count> <#list 1..count as x> <#nested x, x/2, x==count> </#list> </#macro> <@repeat count=4 ; c halfc last> ${c}. ${halfc} <#if last> Last!</#if> </@repeat> 输出 1. 0.5 2. 1 3. 1.5 4. 2 Last! t, lt, rt 语法 <#t> 去掉左右空白和回车换行 <#lt>去掉左边空白和回车换行 <#rt>去掉右边空白和回车换行 <#nt>取消上面的效果 B指令 freemarker指令有两种: 1、预定义指令:引用方式为<#指令名称> 2、用户定义指令:引用方式为<@指令名称>,引用用户定义指令时须将#换为@。 注意:如果使用不存在的指令,FreeMarker不会使用模板输出,而是产生一个错误消息。 freemarker指令由FTL标记来引用,FTL标记和HTML标记类似,名字前加#来加以区分。如HTML标记的形式为<h1></h1>则FTL标记的形式是<#list></#list>(此处h1标记和list指令没有任何功能上的对应关系,只是做为说明使用一下)。 有三种FTL标记: 1)、开始标记:<#指令名称> 2)、结束标记:</#指令名称> 3)、空标记:<#指令名称/> 注意: 1) FTL会忽略标记之的空格,但是,<#和指令 与 </#和指令 之间不能有空格。 2) FTL标记不能够交叉,必须合理嵌套。每个开始标记对应一个结束标记,层层嵌套。 如: <#list> <li> ${数据} <#if 变量> game over! </#if> </#list> 注意事项: 1)、FTL对大小写敏感。所以使用的标记及interpolation要注意大小写。name与NAME就是不同的对象。<#list>是正确的标记,而<#List>则不是。 2)、interpolation只能在文本部分使用,不能位于FTL标记内。如<#if ${var}>是错误的,正确的方法是:<#if var>,而且此处var必须为布尔值。 3)、FTL标记不能位于另一个FTL标记内部,注释例外。注释可以位于标记及interpolation内部。 if, else, elseif 语法 <#if condition> ... <#elseif condition2> ... <#elseif condition3> ... ... <#else> ... </#if> 用例 <#if x = 1> x is 1 </#if> <#if x = 1> x is 1 <#else> x is not 1 </#if> We have these animals: <table border=1> <tr><th>Name<th>Price <#list animals as being> <tr> <td> <#if being.size = "large"></#if></#if> ${being.name} <#if being.size = "large"> <td>${being.price} Euros </#list> </table> <#if user = "Big Joe"> It is Big Joe </#if> <#if user != "Big Joe"> It is not Big Joe </#if> switch, case, default, break 语法 <#switch value> <#case refValue1> ... <#break> <#case refValue2> ... <#break> <#case refValueN> ... <#break> <#default> ... </#switch> 用例 字符串 <#switch being.size> <#case "small"> This will be processed if it is small <#break> <#case "medium"> This will be processed if it is medium <#break> <#case "large"> This will be processed if it is large <#break> <#default> This will be processed if it is neither </#switch> 数字 <#switch x> <#case x = 1> 1 <#case x = 2> 2 <#default> d </#switch> 如果x=1 输出 1 2, x=2输出 2, x=3 输出d list, break 语法 <#list sequence as item> ... <#if item = "spring"><#break></#if> ... </#list> 关键字 item_index:是list当前值的下标 item_has_next:判断list是否还有值 用例 <#assign seq = ["winter", "spring", "summer", "autumn"]> <#list seq as x> ${x_index + 1}. ${x}<#if x_has_next>,</#if> </#list> 输出 1. winter, 2. spring, 3. summer, 4. autumn include 语法 <#include filename> or <#include filename options> options包含两个属性 encoding=”GBK” 编码格式 parse=true 是否作为ftl语法解析,默认是true,false就是以文本方式引入.注意在ftl文件里布尔值都是直接赋值的如parse=true,而不是parse=”true” 用例 /common/copyright.ftl包含内容 Copyright 2001-2002 ${me}<br> All rights reserved. 模板文件 <#assign me = "Juila Smith"> <h1>Some test</h1> Yeah. <#include "/common/copyright.ftl" encoding=”GBK”> 输出结果 <h1>Some test</h1> Yeah. <html> <head> <title>Test page</title> </head> <body> <h1>Test page</h1> Blah blah... <#include "/copyright_footer.html"> </body> </html> Import 语法 <#import path as hash> 类似于java里的import,它导入文件,然后就可以在当前文件里使用被导入文件里的宏组件 用例 假设mylib.ftl里定义了宏copyright那么我们在其他模板页面里可以这样使用 <#import "/libs/mylib.ftl" as my> <@my.copyright date="1999-2002"/> "my"在freemarker里被称作namespace compress 语法 <#compress> ... </#compress> 用来压缩空白空间和空白的行 用例 <#assign x = " moo \n\n "> (<#compress> 1 2 3 4 5 ${moo} test only I said, test only </#compress>) 输出 (1 2 3 4 5 moo test only I said, test only) escape, noescape 语法 <#escape identifier as expression> ... <#noescape>...</#noescape> ... </#escape> 用例 主要使用在相似的字符串变量输出,比如某一个模块的所有字符串输出都必须是html安全的,这个时候就可以使用该表达式 <#escape x as x?html> First name: ${firstName} <#noescape>Last name: ${lastName}</#noescape> Maiden name: ${maidenName} </#escape> 相同表达式 First name: ${firstName?html} Last name: ${lastName } Maiden name: ${maidenName?html} assign 语法 <#assign name=value> or <#assign name1=value1 name2=value2 ... nameN=valueN> or <#assign same as above... in namespacehash> or <#assign name> capture this </#assign> or <#assign name in namespacehash> capture this </#assign> 用例 生成变量,并且给变量赋值 给seasons赋予序列值 <#assign seasons = ["winter", "spring", "summer", "autumn"]> 给变量test加1 <#assign test = test + 1> 给my namespage 赋予一个变量bgColor,下面可以通过my.bgColor来访问这个变量 <#import "/mylib.ftl" as my> <#assign bgColor="red" in my> 将一段输出的文本作为变量保存在x里 下面的阴影部分输出的文本将被赋值给x <#assign x> <#list 1..3 as n> ${n} <@myMacro /> </#list> </#assign> Number of words: ${x?word_list?size} ${x} <#assign x>Hello ${user}!</#assign> error <#assign x=” Hello ${user}!”> true 同时也支持文赋值,如: <#assign 语法> java </#assign> ${语法} 打印输出: java global 语法 <#global name=value> or <#global name1=value1 name2=value2 ... nameN=valueN> or <#global name> capture this </#global> 全局赋值语法,利用这个语法给变量赋值,那么这个变量在所有的namespace是可见的,如果这个变量被当前的assign语法覆盖如<#global x=2> <#assign x=1> 在当前页面里x=2将被隐藏,或者通过${.global.x}来访问[A2] setting 语法 <#setting name=value> 用来设置整个系统的一个环境 locale number_format boolean_format date_format, time_format, datetime_format time_zone classic_compatible 用例 假如当前是匈牙利的设置,然后修改成美国 ${1.2} <#setting locale="en_US"> ${1.2} 输出 1,2 1.2 因为匈牙利是采用“,”作为十进制的分隔符,美国是用“.” C一些常用方法或注意事项 表达式转换类 ${expression}计算expression并输出 #{ expression }数字计算#{ expression ;format}安格式输出数字format为M和m M表示小数点后最多的位数,m表示小数点后最少的位数如#{121.2322;m2M2}输出121.23 数字循环 1..5 表示从1到5,原型number..number 对浮点取整数 ${123.23?int} 输出123 给变量默认值 ${var?default(“hello world<br>”)?html}如果var is null那么将会被hello world<br>替代 判断对象是不是null <#if mouse?exists> Mouse found <#else> 也可以直接${mouse?if_exists})输出布尔形 常用格式化日期 openingTime必须是Date型,详细查看freemarker文档 Reference->build-in referece->build-in for date ${openingTime?date} ${openingTime?date_time} ${openingTime?time} 添加全局共享变量数据模型 在代码里的实现 cfg = Configuration.getDefaultConfiguration(); cfg.setSharedVariable("global", "you good"); 页面实现可以通过global指令,具体查看指令里的global部分 直接调用java对象的方法 ${object.methed(args)} 字符串处理(内置方法) html安全输出 “abc<table>sdfsf”?html 返回安全的html输出,替换掉html代码 xml安全输出 var?xml substring的用法 <#assign user=”hello jeen”> ${user[0]}${user[4]} ${user[1..4]} 输出 : ho ello 类似String.split的用法 “abc;def;ghi”?split(“;”)返回sequence 将字符串按空格转化成sequence,然后取sequence的长度 var?word_list 效果同 var?split(“ ”) var?word_list?size 取得字符串长度 var?length 大写输出字符 var?upper_case 小写输出字符 var?lower_case 首字符大写 var?cap_first 首字符小写 var?uncap_first 去掉字符串前后空格 var?trim 每个单词的首字符大写 var?capitalize 类似String.indexof: “babcdabcd”?index_of(“abc”) 返回1 “babcdabcd”?index_of(“abc”,2) 返回5 类似String.lastIndexOf last_index_of和String.lastIndexOf类似,同上 下面两个可能在代码生成的时候使用(在引号前加”\”) j_string: 在字符串引号前加”\” <#assign beanName = 'The "foo" bean.'> String BEAN_NAME = "${beanName?j_string}"; 打印输出: String BEAN_NAME = "The \"foo\" bean."; js_string: <#assign user = "Big Joe's \"right hand\"."> <script> alert("Welcome ${user}!"); </script> 打印输出: alert("Welcome Big Joe\'s \"right hand\"!"); 替换字符串 replace${s?replace(‘ba’, ‘XY’ )} ${s?replace(‘ba’, ‘XY’ , ‘规则参数’)}将s里的所有的ba替换成xy 规则参数包含:i r m s c f具体含义如下: ·i: 大小写不区分. ·f: 只替换第一个出现被替换字符串的字符串 ·r: XY是正则表达式 ·m: Multi-line mode for regular expressions. In multi-line mode the expressions ^ and $ match just after or just before, respectively, a line terminator or the end of the string. By default these expressions only match at the beginning and the end of the entire string. ·s: Enables dotall mode for regular expressions (same as Perl singe-line mode). In dotall mode, the expression . matches any character, including a line terminator. By default this expression does not match line terminators. ·c: Permits whitespace and comments in regular expressions. D freemarker在web开发注意事项 freemarker与webwork整合 web常用的几个对象 Freemarker的ftl文件直接使用内部对象: ${Request ["a"]} ${RequestParameters["a"]} ${Session ["a"]} ${Application ["a"]} ${JspTaglibs ["a"]} 与webwork整合之后 通过配置的servlet 已经把request,session等对象置入了数据模型 在view存在下面的对象 我们可以在ftl${req}来打印req对象 req - the current HttpServletRequest res - the current HttpServletResponse stack - the current OgnlValueStack ognl - the OgnlTool instance webwork - an instance of FreemarkerWebWorkUtil action - the current WebWork action exception - optional the Exception instance, if the view is a JSP exception or Servlet exception view view值的搜索顺序 ${name}将会以下面的顺序查找name值 freemarker variables value stack request attributes session attributes servlet context attributes 在模板里ftl里使用标签 注意,如果标签的属性值是数字,那么必须采用nubmer=123方式给属性赋值 JSP页面 < contentType="text/html;charset=ISO-8859-2" language="java"%> < uri="/WEB-INF/struts-html.tld" prefix="html"%> < uri="/WEB-INF/struts-bean.tld" prefix="bean"%> <html> <body> <h1><bean:message key="welcome.title"/></h1> <html:errors/> <html:form action="/query"> Keyword: <html:text property="keyword"/><br> Exclude: <html:text property="exclude"/><br> <html:submit value="Send"/> </html:form> </body> </html> 模板ftl页面 <#assign html=JspTaglibs["/WEB-INF/struts-html.tld"]> <#assign bean=JspTaglibs["/WEB-INF/struts-bean.tld"]> <html> <body> <h1><@bean.message key="welcome.title"/></h1> <@html.errors/> <@html.form action="/query"> Keyword: <@html.text property="keyword"/><br> Exclude: <@html.text property="exclude"/><br> <@html.submit value="Send"/> </@html.form> </body> </html> 如何初始化共享变量 1. 初始化全局共享数据模型 freemark在web上使用的时候对共享数据的初始化支持的不够,不能在配置初始化的时候实现,而必须通过ftl文件来初始化全局变量。这是不能满主需求的,我们需要在servlet init的时候留出一个接口来初始化系统的共享数据 具体到和webwork整合,因为本身webwork提供了整合servlet,如果要增加全局共享变量,可以通过修改com.opensymphony.webwork.views.freemarker.FreemarkerServlet来实现,我们可以在这个servlet初始化的时候来初始化全局共享变量 与webwork整合配置 配置web.xml <servlet> <servlet-name>freemarker</servlet-name> <servlet-class>com.opensymphony.webwork.views.freemarker.FreemarkerServlet</servlet-class> <init-param> <param-name>TemplatePath</param-name> <param-value>/</param-value> <!—模板载入文件夹,这里相对context root,递归获取该文件夹下的所有模板--> </init-param> <init-param> <param-name>NoCache</param-name> <!—是否对模板缓存--> <param-value>true</param-value> </init-param> <init-param> <param-name>ContentType</param-name> <param-value>text/html</param-value> </init-param> <init-param> <param-name>template_update_delay</param-name> <!—模板更新时间,0表示每次都更新,这个适合开发时候--> <param-value>0</param-value> </init-param> <init-param> <param-name>default_encoding</param-name> <param-value>GBK</param-value> </init-param> <init-param> <param-name>number_format</param-name> <param-value>0.##########</param-value><!—数字显示格式--> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>freemarker</servlet-name> <url-pattern>*.ftl</url-pattern> </servlet-mapping> E高级方法 自定义方法 ${timer("yyyy-MM-dd H:mm:ss", x)} ${timer("yyyy-MM-dd ", x)} 在模板除了可以通过对象来调用方法外(${object.methed(args)})也可以直接调用java实现的方法,java类必须实现接口TemplateMethodModel的方法exec(List args). 下面以把毫秒的时间转换成按格式输出的时间为例子 public class LongToDate implements TemplateMethodModel { public TemplateModel exec(List args) throws TemplateModelException { SimpleDateFormat mydate = new SimpleDateFormat((String) args.get(0))); return mydate.format(new Date(Long.parseLong((String)args.get(1))); } } 将LongToDate对象放入到数据模型 root.put("timer", new IndexOfMethod()); ftl模板里使用 <#assign x = "123112455445"> ${timer("yyyy-MM-dd H:mm:ss", x)} ${timer("yyyy-MM-dd ", x)} 输出 2001-10-12 5:21:12 2001-10-12 自定义 Transforms 实现自定义的<@transform>文本或表达式</@transform>的功能,允许对间的最终文本进行解析转换 例子:实现<@upcase>str</@upcase> 将str转换成STR 的功能 代码如下: import java.io.*; import java.util.*; import freemarker.template.TemplateTransformModel; class UpperCaseTransform implements TemplateTransformModel { public Writer getWriter(Writer out, Map args) { return new UpperCaseWriter(out); } private class UpperCaseWriter extends Writer { private Writer out; UpperCaseWriter (Writer out) { this.out = out; } public void write(char[] cbuf, int off, int len) throws IOException { out.write(new String(cbuf, off, len).toUpperCase()); } public void flush() throws IOException { out.flush(); } public void close() { } } } 然后将此对象put到数据模型 root.put("upcase", new UpperCaseTransform()); 在view(ftl)页面可以如下方式使用 <@upcase> hello world </@upcase> 打印输出: HELLO WORLD F.Built-ins ${x?upper_case} – 小写变大写 ${test?html} - 转换为HTML编码格式 ${repeat("A", B)} – 复制B次A Example: ${test?html} ${test?upper_case?html} Assuming that test stores the string ``Tom & Jerry'', the output will be: Tom & Jerry TOM & JERRY --------- ${repeat("What", 3)} will print: :WhatWhatWhat 1. String内置的JavaScript转换: js_string 用途:用于JavaScript转义,转换',",换行等特殊字符 模板: <script> alert("${errorMessage?js_string}"); </script> 输出: <script> alert("Readonly\'s pet name is \"Cross Bone\""); </script> 2.内置的默认值处理:default 用途: 用于处理默认值 模本: User: ${userLogin.name?default("Anonymous")} <td>${(employee.department.manager.name)?default(" ")}</td> 输出: User: Anonymous <td> </td> 注,可以对整个对象树加上(),再用内置处理器这种方便的做法,偶也是最近刚学会的,以前一直用很傻的方法做..... 3. Sequence内置的计数器: xxx_index 用途:显示序号 模板: <#list employees as e> ${e_index}. ${e.name} </#list> 输出: 1. Readonly 2. Robbin 4. Sequence内置的分段器: chunk 用途:某些比较BT的排版需求 模板: <#assign seq = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']> <#list seq?chunk(4) as row> <ul> <li><#list row as cell>${cell} </#list> </#list> <#list seq?chunk(4, '-') as row> <tr> <td><#list row as cell>${cell} </#list></td> </tr> </#list> 输出: <ul> <li>a <li>b <li>c <li>d <ul> <li>e <li>f <li>g <li>h <ul> <li>i <li>j <tr> <td>a</td> <td>b</td> <td>c</td> <td>d</td> </tr> <tr> <td>e</td> <td>f</td> <td>g</td> <td>h</td> </tr> <tr> <td>i</td> <td>j</td> <td>-</td> <td>-</td> </tr> String ${"It's \"quoted\" and this is a backslash: \\"} ${'It\'s "quoted" and this is a backslash: } ${r"${foo}"} raw字符串,原封不动地现实引号的内容 ps:前一种是用双引号来引用字符串,后一种是用单引号来引用字符串。 分别需要对双引号和单引号进行转义 ${"${user}${user}${user}${user}"} ${user + user + user + user} 效果相同 ★substring ${user[0]}${user[4]} ${user[1..4]} ${user[4..]} ★number 不支持科学计数法 小数点前面的零不能省略 ★sequences <#list ["winter", "spring", "summer", "autumn"] as x> ${x} </#list> <#list 2..5 as x> ${x} </#list> <#list [2,3,4,5] as x> ${x} </#list> 数组的拼接 <#list ["Joe", "Fred"] + ["Julia", "Kate"] as user> - ${user} </#list> ★hash <#assign ages = {"Joe":23, "Fred":25} + {"Joe":30, "Julia":18}> - Joe is ${ages.Joe} - Fred is ${ages.Fred} - Julia is ${ages.Julia} 注意重复的键对应的值取最后的一个 ★运算 ${5/2?int} 显示2 cap_first : 首字母大写 capitalize: 所有单词首刺目大写 html : 转换为HTML格式 < replaced with < > replaced with > & replaced with & " replaced with " index_of : 显示元素所在的位置 "abcabc"?index_of("bc") 返回值为1(下标从0开始) Contains:判断是否存在字符 <#if "piceous"?contains("ice")>It contains "ice"</#if> 输出: It contains "ice" Replace :替换 split(“XX”):截取XX之后的字符 <#list "someMOOtestMOOtext"?split("MOO") as x> - ${x} </#list> 输出: - some - test - text starts_with :字符串由什么开始返回布尔型 trim :去掉空格 seq_index_of 数组元素的位置 <#assign colors = ["red", "green", "blue"]> ${colors?seq_index_of("blue")} 输出: 2 Default : 设置变量的默认值 Exists:放在if句 如果没有….. <#if mouse?exists> Mouse found <#else> No mouse found </#if> Creating mouse... <#assign mouse = "Jerry"> <#if mouse?exists> Mouse found <#else> No mouse found </#if> 输出 : No mouse found Creating mouse... Mouse found if_exists 放在一般语句 (${mouse?if_exists}) Creating mouse... <#assign mouse = "Jerry"> (${mouse?if_exists}) 输出: () Creating mouse... (Jerry) 删除空白行和空格 <#compress> ... </#compress> 让此标记内的代码都执行<#escape 后的?参数 <#escape> </#escape> <#escape x as x?html> From: ${mailMessage.From} Subject: ${mailMessage.Subject} <#noescape>Message: ${mailMessage.htmlFormattedBody}</#noescape> ... </#escape> 输出: From: ${mailMessage.From?html} Subject: ${mailMessage.Subject?html} Message: ${mailMessage.htmlFormattedBody} ... [A1]默认值 [A2]<#import “lib/abc.ftl” as abc>这里的abc叫做namespace chunk, is_date, last, root, j_string, contains, is_hash, long, float, ends_with, namespace, matches, time, values, seq_last_index_of, uncap_first, byte, substring, is_transform, web_safe, groups, seq_contains, is_macro, index_of, word_list, int, is_method, eval, parent, xml, number, capitalize, if_exists, rtf, node_type, double, is_directive, url, size, default, is_boolean, split, node_name, is_enumerable, seq_index_of, is_sequence, sort, is_node, sort_by, left_pad, cap_first, interpret, children, node_namespace, chop_linebreak, date, short, last_index_of, is_collection, ancestors, length, trim, datetime, is_string, reverse, c, keys, upper_case, js_string, has_content, right_pad, replace, is_hash_ex, new, is_number, is_indexable, lower_case, string, exists, html, first, starts_with ##############2222222222222222############### struts2.0 标签+ftl标签 FreeMarker文API手册(完整) http://blog.csdn.net/junjun16818/article/details/6990068 三目: ${true?string('5','7')} ${line.class.simpleName} <#if line.class.simpleName=="ViewLine">你好</#if> list里面是object数组 <#if (areaList?exists)> <#list areaList as line> <span style="background-color:#${(sc[(line_index)%6])}">${line[1]}:${line[0]}</span> </#list> </#if> 取得list的长度: <#if (pageInfo.resultList?size>0)> 截取字符串:<#if news.title?length gt 14>${news.title.substring(0,14)}...<#else>${news.title?if_exists}</#if> 拆分字符数组 <#if (lineInfo.lineDate?exists)&&(lineInfo.lineDate?length>10)> <#list lineInfo.lineDate?split(",") as d> <input type="text" name="lineInfo.lineDate" id="lineDate" value="${d}" onclick="WdatePicker({dateFmt:'yyyy-MM-dd', skin:'whyGreen'})"/> </#list> </#if> 1.注释: 包含在<#--和--> 2.注意: 由于Freemarker会将>解释成FTL标记的结束字符,所以对于>和>=可以使用括号来避免这种情况,例如 <#if (x > y)> 3.<#local y = "test"> 定义局部变量 4.<#import "/lib/my_test.ftl" as my> 导入模板文件 指定名字空间 my 5. if指令 <#if animals.python.price < animals.elephant.price> Pythons are cheaper than elephants today. <#else> Pythons are not cheaper than elephants today. </#if> 6. list指令以及列表序号 <#list animals as being> 第${being_index+1}个<#--默认是0开始--> <tr><td>${being.name}<td>${being.price} Euros </#list> <#list ["winter", "spring", "summer", "autumn"] as x> ${x} </#list> <#list ["Joe", "Fred"] + ["Julia", "Kate"] as user> - ${user} </#list> 输出结果是: - Joe - Fred - Julia - Kate include指令 <#include "/copyright_footer.html"> 7.判断是否为空 ${userInfo.userName?if_exists} <#if ((user.sex)!'')=='1'>男<#elseif ((user.sex)!'')=='2'>女</#if> <#if searchType ? exists && searchType=='on'>checked</#if> <#if time ? exists && (time!'')=='y' || (time!'')=='m' || (time!'')=='d'>统计条件<#else>保证金返款数量</#if> <#if ((time)!'')=='y'>按年统计<#elseif ((time)!'')=='m'>按月统计<#elseif ((time)!'')=='d'>按日统计<#else>默认按日统计</#if> 8.截取字符串 ${carInfo.carNum.substring(0,1)} 9.freemarker的replace功能 替换字符串 replace 线路标签:${lineInfo.lineLableDescribe?replace('#','、')} ${s?replace(‘ba’, ‘XY’ )} ${s?replace(‘ba’, ‘XY’ , ‘规则参数’)}将s里的所有的ba替换成xy 规则参数包含: i r m s c f 具体含义如下: · i: 大小写不区分. · f: 只替换第一个出现被替换字符串的字符串 · r: XY是正则表达式 · m: Multi-line mode for regular expressions. In multi-line mode the expressions ^ and $ match just after or just before, respectively, a line terminator or the end of the string. By default these expressions only match at the beginning and the end of the entire string. · s: Enables dotall mode for regular expressions (same as Perl singe-line mode). In dotall mode, the expression . matches any character, including a line terminator. By default this expression does not match line terminators. · c: Permits whitespace and comments in regular expressions. 10.三目运算 ${true?string('5','7')} 11.string格式化单个Interpolation,下面是一个例子: <#setting number_format="currency"/> <#assign answer=42/> ${answer} ${answer?string} <#-- the same as ${answer} --> ${answer?string.number} ${answer?string.currency} ${answer?string.percent} 输出结果是: $42.00 $42.00 42 $42.00 4,200% 12.插入日期值:根据缺省格式(由#setting指令设置)将表达式结果转换成文本输出;可以使用内建函数string格式化单个Interpolation,下面是一个使用格式模式的例子: ${lastUpdated?string("yyyy-MM-dd HH:mm:ss zzzz")} ${lastUpdated?string("EEE, MMM d, ''yy")} ${lastUpdated?string("EEEE, MMMM dd, yyyy, hh:mm:ss a '('zzz')'")} 输出的结果类似下面的格式: 2003-04-08 21:24:44 Pacific Daylight Time Tue, Apr 8, '03 Tuesday, April 08, 2003, 09:24:44 PM (PDT) 13.插入布尔值:根据缺省格式(由#setting指令设置)将表达式结果转换成文本输出;可以使用内建函数string格式化单个Interpolation,下面是一个例子: <#assign foo=true/> ${foo?string("yes", "no")} 输出结果是: yes <#if cList?exists> <#assign index = 1 /> <#list cList as cList> <#if index==1 || index %3==0> <div class="base_row"> </#if> <div class="fldivlr5"><font class="font_gray">车型:</font></div> <div class="fldivlr5">三厢轿车</div> <#if index %3==0 || !cList_has_next> </div> </#if> <#assign index=index+1 /> </#list> </#if> Freemarker 内置函数 数字、字符串、日期格式化 一、 Sequence的内置函数 1. sequence?first 返回sequence的第一个值。 2. sequence?last 返回sequence的最后一个值。 3. sequence?reverse 将sequence的现有顺序反转,即倒序排序 4. sequence?size 返回sequence的大小 5. sequence?sort 将sequence的对象转化为字符串后顺序排序 6. sequence?sort_by(value) 按sequence对象的属性value进行排序 二、 Hash的内置函数 1. hash?keys 返回hash里的所有key,返回结果为sequence 2. hash?values 返回hash里的所有value,返回结果为sequence 例如: <#assign user={“name”:“hailang”, “sex”:“man”}> <#assign keys=user?keys> <#list keys as key> ${key}=${user[key]} </#list> 三、 操作字符串函数 1. substring(start,end)从一个字符串截取子串 start:截取子串开始的索引,start必须大于等于0,小于等于end end: 截取子串的长度,end必须大于等于0,小于等于字符串长度,如果省略该参数,默认为字符串长度。 例子: ${‘str’?substring(0)}à结果为str ${‘str’?substring(1)}à结果为tr ${‘str’?substring(2)}à结果为r ${‘str’?substring(3)}à结果为 ${‘str’?substring(0,0)}à结果为 ${‘str’?substring(0,1)}à结果为s ${‘str’?substring(0,2)}à结果为st ${‘str’?substring(0,3)}à结果为str 2. cap_first 将字符串的第一个单词的首字母变为大写。 ${‘str’?cap_first}à结果为Str 3. uncap_first将字符串的第一个单词的首字母变为小写。 ${‘Str’?cap_first}à结果为str 4. capitalize将字符串的所有单词的首字母变为大写 ${‘str’? capitalize}à结果为STR 5. date,time,datetime将字符串转换为日期 例如: <#assign date1=”2009-10-12”?date(“yyyy-MM-dd”)> <#assign date2=”9:28:20”?time(“HH:mm:ss”)> <#assign date3=” 2009-10-12 9:28:20”?time(“HH:mm:ss”)> ${date1}à结果为2009-10-12 ${date2}à结果为9:28:20 ${date3}à结果为2009-10-12 9:28:20 注意:如果指定的字符串格式不正确将引发错误。 6. ends_with 判断某个字符串是否由某个子串结尾,返回布尔值。 ${“string”?ends_with(“ing”)?string} 返回结果为true 注意:布尔值必须转换为字符串才能输出 7. html 用于将字符串的<、>、&和“替换为对应得<>":& 8. index_of(substring,start)在字符串查找某个子串,返回找到子串的第一个字符的索引,如果没有找到子串,则返回-1。 Start参数用于指定从字符串的那个索引处开始搜索,start为数字值。 如果start大于字符串长度,则start取值等于字符串长度,如果start小于0, 则start取值为0。 ${“string”?index_of(“in”) à结果为3 ${“string”?index_of(“ab”) à结果为-1 9.length返回字符串的长度 ${“string”?length}à结果为6 10. lower_case将字符串转为小写 ${“STRING”?lower_case}à结果为string 11.upper_case将字符串转为大写 ${“string”?upper_case}à结果为STRING 12. contains 判断字符是否包含某个子串。返回布尔值 ${“string”?contains(“ing”)?string} à结果为true 注意:布尔值必须转换为字符串才能输出 13. number将字符串转换为数字 ${“111.11”?number}à结果为111.11 14.replace用于将字符串的一部分从左到右替换为另外的字符串。 ${“strabg”?replace(“ab”,”in”)} à结果为string 15.split使用指定的分隔符将一个字符串拆分为一组字符串 <#list “This|is|split”?split(“|”) as s> ${s} </#list> 结果为: This is split 16. trim 删除字符串首尾空格 ${“ String ”?trim} à结果为String 四、 操作数字 1. c 用于将数字转换为字符串 ${123?c} à结果为123 2. string用于将数字转换为字符串 Freemarker预订义了三种数字格式:number,currency(货币)和percent(百分比)其number为默认的数字格式转换 例如: <#assign tempNum=20> ${tempNum} ${tempNum?string.number}或${tempNum?string(“number”)} à结果为20 ${tempNum?string.currency}或${tempNum?string(“currency”)} à结果为¥20.00 ${tempNum?string. percent}或${tempNum?string(“percent”)} à结果为2,000% 五、 操作布尔值 string 用于将布尔值转换为字符串输出 true转为“true”,false转换为“false” foo?string(“yes”,”no”)如果布尔值是true,那么返回“yes”,否则返回no <#assign index = 1 /> <#list pageInfo.resultList as p> <tr class=<#if index%2==0>"sealistra"<#else>"sealistrb"</#if> align="center"> <td align="center">${index}</td> ${p.userName?if_exists} <td><#if ((p.roleType)!'')=='1'>司机<#elseif ((p.roleType)!'')=='2'>乘客</#if></td> <td><#if ((p.journeyType)!'')=='1'>单程<#elseif ((p.journeyType)!'')=='2'>往返</#if></td> <td>${(p.ver)!""}</td> <td> <#if ((p.statusFlag)!'')=='0'>默认 <#elseif ((p.statusFlag)!'')=='1'>匹配成功 </#if> </td> <td> <#if p.createTime?exists >${p.createTime?string("yyyy-MM-dd HH:mm:ss")}</#if> </td> </tr> <#assign index=index+1 /> </#list> if, else, elseif 语法: <#if condition> ... <#elseif condition2> ... <#elseif condition3> ... ... <#else> ... </#if> 备注:condition、condition2···必须为boolean 类型,<#elseif ··>、<#else>可有0或多个。 实例: <#if x == 1> x is 1 <#elseif x == 2> x is 2 <#elseif x == 3> x is 3 <#elseif x > 4> x is 4 <#else> x is not 1 nor 2 nor 3 nor 4 </#if> 备注:< 或 > 号 必须转义,否则出错。。转义请参考其他文档。 switch, case, default, break 语法 <#switch value> <#case refValue1> ... <#break> <#case refValue2> ... <#break> ... <#case refValueN> ... <#break> <#default> ... </#switch> 备注:该指令官方不推荐使用了,可以用if, else, elseif 指令代替。 list, break 语法 <#list sequence as item> ... </#list> 备注: sequence 为一个sequence 或者 collection 类型。item 为 循环的变量。该指令包含有两个特殊的循环变量, item_index:该值为当前循环的值。 item_has_next:该值为一个boolean类型,表明该循环是否含有下一个(是否为循环到了最后一个) 实例: <#assign seq = ["winter", "spring", "summer", "autumn"]> <#list seq as x> ${x_index + 1}. ${x}<#if x_has_next>,</#if> </#list> 输出: 1. winter, 2. spring, 3. summer, 4. autumn 实例: <#assign x=3> <#list 1..x as i> ${i} </#list> 备注:当x 为一个数值序列时,可以使用该list 列出两个数值之间的值。(适合于表格的序号填写) 实例: <#list seq as x> ${x} <#if x = "spring"><#break></#if> </#list> 备注:可以用<#if···><#break> 来终止该循环。 freemarker常见语法大全 FreeMarker的插值有如下两种类型:1,通用插值${expr};2,数字格式化插值:#{expr}或#{expr;format} ${book.name?if_exists } //用于判断如果存在,就输出这个值 ${book.name?default(‘xxx’)}//默认值xxx ${book.name!"xxx"}//默认值xxx ${book.date?string('yyyy-MM-dd')} //日期格式 ${book?string.number} 20 //三种不同的数字格式 ${book?string.currency}--<#-- $20.00 --> ${book?string.percent}—<#-- 20% --> <#assign foo=ture /> //声明变量,插入布尔值进行显示 ${foo?string("yes","no")} <#-- yes --> <等大小比较符号使用需要注意:(xml的原因),可以用于比较数字和日期 使用lt、lte、gt和gte来替代<、<=、>和>= 也可以使用括号<#if (x>y)> 内置函数: 调用区别于属性的访问,使用?代替. 常见的一些内置函数 对于字符串 html-对字符串进行HTML编码 cap_first-使字符串第一个字母大写 lower_case-将字符串转换成小写 trim-去掉字符串前后的空白字符 对于Sequences(序列) size-获得序列元素的数目 对于数字 int-取得数字的整数部分(如-1.9?int的结果是-1) 对于集合,可以使用数组的方式,使用下标索引进行访问 逻辑判断: if................ <#if condition>... <#elseif condition2>... <#elseif condition3>...... <#else>... Boolean类型的空值判断 空值判断可以写成<#if book.name?? > //注意${}为变量的渲染显示,而<>为定义等操作符的定义 switch............ <#switch value> <#case refValue1> ... <#break> <#case refValue2> ... <#break> ... <#case refValueN> ... <#break> <#default> ... </#switch> 速定义int区间的集合 <#assign l=0..100/> //注意不需要[] 3:循环读取集合: 注意/的使用 <#list student as stu> ${stu}<br/> </#list> 与jstl循环类似,也可以访问循环的状态 item_index:当前变量的索引值 item_has_next:是否存在下一个对象 其item名称为as后的变量名,如stu 集合长度判断 <#if student?size != 0></#if> 判断=的时候,注意只要一个=符号,而不是== 宏/模板 初步了解: 使用更像一个闭包closure,可以定义后,在脚本任意地方引用,并原地起作用 <#macro greet> <font size="+2">Hello Joe!</font> </#macro> 使用的方式为: <@greet></@greet> //同xml可以简写成<@greet/> 宏的参数定义,类似js,在宏名后 带参数进行传递定义 <#macro greet person color> ${person} </#macro> 调用带参数时,注意使用类似XML的属性格式进行传递,不需要关心顺序问题 <@greet person="Fred" color="black"/> 参数默认值定义,如果没有,就必须要求传递完整的参数列表 <#macro greet person color="black"> <font size="+2" color="${color}">Hello ${person}!</font> </#macro> 使用xml的嵌套内容进行传递宏调用,关键标签 <#nested> <#macro border> <table border=4 cellspacing=0 cellpadding=4><tr><td> <#nested> </tr></td></table> </#macro> 调用时: <@border>The bordered text</@border> <#nested> 标签可以在宏多次调用,也可以将多个宏组合进行嵌套 for循环的精简版: <#list 1..count as x> </#list> 宏的循环变量,配合嵌套标签进行参数传递, <#macro repeat count> <#list 1..count as x> <#nested x, x/2, x==count> //这里的三个参数,将会传递到嵌套内容 </#list> </#macro> <@repeat count=4 ; c, halfc, last> ${c}. ${halfc}<#if last> Last!</#if> //这里的内容由macro的<#nested>进行参数的传递,传递的数量任意,当注意需要宏接受这些 </@repeat> 上述还需要注意;的使用 参数的数量是可变的,并不要求全部都有,但是效果不同 在模板定义变量 在模板定义的变量有三种类型: plain变量:可以在模板的任何地方访问,包括使用include指令插入的模板,使用assign指令创建和替换。 局部变量:在宏定义体有效,使用local指令创建和替换。 循环变量:只能存在于指令的嵌套内容,由指令(如list)自动创建;宏的参数是局部变量,而不是循环变量 <#assign x = "plain"> //全局的plain变量 内部循环变量将会隐藏同名的外部循环变量 外部导入的使用,可以用于模块化,并且提供公用性 如:lib/my_lib.ftl文件 <#macro copyright date> <p>Copyright (C) ${date} Julia Smith. All rights reserved. <br>Email: ${mail}</p> </#macro> <#assign mail = "[email protected]"> lib/my_inc.ftl文件 <#import "/lib/my_test.ftl" as my> <#assign mail="[email protected]"> <@my.copyright date="1999-2002"/> ${my.mail} ${mail} 输出结果将不会出现冲突 对于库的变量修改,使用in关键字 <#assign mail="[email protected]" in my> 函数定义:区别于宏对象,带返回值 <#function name param1 param2><#return val></#function>函数,有返回参数 stringA[M .. N] 取子字符串,类似substring(stringA, M, N) <#include "/copyright_footer.html"> 导入其他页面元素 <#include filename options> options包含两个属性 encoding=”GBK” 编码格式 parse=true 是否作为ftl语法解析,默认是true,false就是以文本方式引入.注意在ftl文件里布尔值都是直接赋值的如parse=true,而不是 parse=”true” hash与list的定义 <#assign c= {"a":"orz","b":"czs"}> ${c.a} List片段可以采用: products[10..19] or products[5..] 的格式进行定义,当只局限于数字 <#assign c= [1,2,3,4,5,6,6,7]> <#list c[1..3] as v> ${v} </#list> 对变量的缺省处理 product.color!"red" 用compress directive或者transform来处理输出。 <#compress>...</#compress>:消除空白行。 <@compress single_line=true>...</@compress>将输出压缩为一行。都需要包裹所需文档 freemarker可用"["代替"<".在模板的文件开头加上[#ftl]. 数字输出的另外一种方式 #{c.a;m0} 区别于${},这个例子是用于输出数字的格式化,保留小数的位数,详细如下 数字格式化插值可采用#{expr;format}形式来格式化数字,其format可以是: mX:小数部分最小X位 MX:小数部分最大X位 在定义字符串的时候,可以使用''或者"",对特殊字符,需要使用\进行转义 如果存在大量特殊字符,可以使用${r"..."}进行过滤 ${r"${foo}"} ${r"C:\foo\bar"} Map对象的key和value都是表达式,但是key必须是字符串 可以混合使用.和[""]访问 book.author["name"] //混合使用点语法和方括号语法 为了处理缺失变量,FreeMarker提供了两个运算符: 用于防止对象不存在而导致的异常 !:指定缺失变量的默认值 ??:判断某个变量是否存在,返回boolean值 noparse指令指定FreeMarker不处理该指定里包含的内容,该指令的语法格式如下: <#noparse>...</#noparse> ${firstName?html} 使用html对字符进行格式化处理,对于<等的过滤 escape , noescape指令,对body内的内容实用统一的表达式 看如下的代码: <#escape x as x?html> First name:${firstName} Last name:${lastName} Maiden name:${maidenName} </#escape> 上面的代码等同于: First name:${firstName?html} Last name:${lastName?html} Maiden name:${maidenName?html} 定义全局变量的方式 <#assign name1=value1 name2=value2 / > // 可以同时定义多个变量,也可以使用循环来给变量赋值 <#assign x> <#list ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期天"] as n> ${n} </#list> </#assign> ${x} setting指令,用于动态设置freeMarker的运行环境: 该指令用于设置FreeMarker的运行环境,该指令的语法格式如下:<#setting name=value>,在这个格式,name的取值范围包含如下几个: locale:该选项指定该模板所用的国家/语言选项 number_format:指定格式化输出数字的格式 boolean_format:指定两个布尔值的语法格式,默认值是true,false date_format,time_format,datetime_format:指定格式化输出日期的格式 time_zone:设置格式化输出日期时
1 , TaskBar_v0.5.zip"Form_Taskbar is a control for Visual Basic which, once placed onto a form, makes the form act like the Taskbar (minus the Start Menu)." -- David Newcum2 , RemBuilderplus.zip"Rem Builder will auto load on startup to use Rem Builder; start your Visual Basic program with your project code showing, right click and you should see "Rem Builder".3 , syntax.zipThis is an excellent example of how to highlight HTML code in a rich textbox. I encourage everyone to check it out.4 , status.zipThis example demonstrates how to display text about each control the mouse is currently above.5 , dm10e.zipThis COM object allows you to send SMTP mail from many of the most used applications, including:Active Server Pages (Microsoft IIS or Chili!ASP extensions) Microsoft Visual Basic 4.x/5.x/6.x Microsoft Word, Access, Excel 95/97 (VBA) Windows Scripting Host (cscript / wscript) Perl 5.x for Win32 Inprise Delphi 4 Microsoft Visual C++ 4.x/5.x/6.x Microsoft Visual J++ 1.x/6.0 (Java) 6 , ocxex.zip"This is a quick example I made to show you how to use Events and properties in a OCX."7 , news.exeThis control aids as a complete Newsgroup control. It can post messages and recieve messages through the internet.8 , optiondemo.zipThis example demonstrates how to create realistic Option Buttons in Visual Basic.9 , mencrypt.zipThis ocx allows you to encrypt strings while utilizing a password shift method.10 , listtxt.zipThis shows how to retrieve the text from the current selection in a listbox.11 , list_index.zipThis example tells you if the inputted List Index is selected or not.12 , fade.zipThis is a bas to fade a pictuerbox. Can be used to make a progressbar13 , subcls32.zipThis demonstrates hoe to write a subclassing control. And it has many examples as to how to use the control (included.)14 , djmeter.zipThis is the source for a Progress Bar control. Also includes a helpful example.15 , progress.zipThis is an example on how to use the Progress Bar included with Microsoft's Visual Basic.16 , slider.zip"This is a sample of the Slider control that is part of the Microsoft Windows Common Controls(COMCTL32.OCX). "17 , statusbar.zip"This is a sample of the StatusBar control that is part of the Microsoft Windows Common Controls(COMCTL32.OCX). "18 , tabstrip.zip"This is a sample of the TabStrip control that is part of the Microsoft Windows Common Controls(COMCTL32.OCX). "19 , uncommondialog.zipThis is an alternative to Microsoft's (tm) Common Dialog control by Nick Mancini.20 , ucmdex.zipThis is the example to go with Uncommon Dialog OCX.21 , scroll.zipThis demonstrates how to create an auto-scrolling textbox.22 , splitter.zipThis demonstrates how to "split" controls. This is an excellent example, and I reccomend this file for everyone. 23 , mtymse.zip"This project is a fully working ActiveX control, with code, that allows you to control almost every aspect of the mouse. You can move the mouse, click the buttons and adjust the click time from your application."24 , ucmdsrc.zipThis is the source to my OCX. This demontrates how to create a basic OCX. This will aid anyone who wants to create an OCX.25 , avb-systray.zipThis is a good example to add your programs' icon to the Systray. This Zip also includes a helpful example.26 , cmdex.zipThis is an example of how to use the Common Dialog. This demonstrates most of the event procedures of the CM Dialog control.27 , campbell-reg.zipThis demonstrates how to write and retrieve information from the registry.28 , basChangeCursor.zipThis module demonstrates how to animate your cursor through Visual Basic, and Win32.29 , hdcat.zipThis will grab every file on your hard drive and add its path to a listbox.30 , vbo_bump.zipThis DLL allows programmers to easily draw 3D grippers and lines on Device Contexts (DC). 31 , vbo_user32_bas.zipThis BAS file contains many functions to ease the process of using the USER32 DLL. 32 , vbo_gdi32_bas.zipThis BAS File conatains many functions to ease the process of using the GDI32 DLL. 33 , vbo_button_bas.zipThis bas contains functions to manipulate Button class objects34 , LPT_Port.zipRead/write to LPT parallel port35 , DancingBaby.zipA Dancing Baby Screen Saver Which Dance on A Famous Song Macarena ( With Sound ) A Very Cute Screen Saver ,with source code, If you want more avi files then please mail me.36 , superwriter.zipA complete Wordprocessor, with source code. You can save, open files, print them out, copy, cut, paste, well you know the concept!37 , LogOff.zipThis conveniently placed program allows you to log off from your system tray.38 , ChPass.zipChanges NT Domain Passord. This program has two compenants... a server and a a client. The Server must run on a Domain Controller.39 , Reboot.zipThis conveniently placed program allows you to restart your computer more easily, from your system tray. 40 , analogclock.zipThis is a very good demo OCX for an analog clock. Although quite big in size, this is due to the very good background to the clock face. The analog click itself is very accurate and looks very impressive.41 , edge.zipThis program uses a few API calls/functions to set 3D, sunken and etched effects to an image inside an image control. It also has an example of how to change a label control to a 3D command button.42 , splitpanel2.zipA re-written version of the SplitPanel that David originally put onto this site about a year ago. It basically is a control that you place on a form and you can put other controls on the form and by dragging the splitpanel bar around, it does the resizing for you. 43 , avcontrol.zipThis control takes care of many audio and visual functions needed for game and graphical programmers. You can easily retrieve or change the screen resolution and color depth, play audio CDs and standard wave files 44 , fsocontrol.zipThis demonstration version of this control is a wrapper around the FileSystemObject - and makes using the FSO much easier.45 , slidingtoolbar.zipThis project shows how to implement a sliding toolbar in an application using one quick Kernel32 API function "Sleep". The application is fairly simple and easy to implement. 46 , dcsize.zipWhen this control is put onto a form, it ensures that all other controls retain the correct aspect-ratio from the design time view. Basically, it resize all controls on a form when the form resizes. This code is 100% free.47 , colorchooseocx.zipThis great OCX allows you to have a drop down list of colors to allow your user to choose from. The control itself has all the events and properties that you need.48 , xgraphmeter.zipThis is XGraphMeter, a bargraph/meter control good for displaying constantly changing values such as CPU usage or DUN throughput.49 , dynlistmnu.zipWhile trying to come up with a Dynamic menu in VB, I decided that VBs menu object was just too much of a pain to work with This project contains a form to mimic the functionality that I was looking for.. Part of my design criteria was that the menu form 50 , runtime.zipSupposedly, what this code does cannot be done... But it works. Basically, its a demonstration of how you can change control properties at run-time. If you try it in VB, you will get a runtime error, but this code shows you how to do it. Gilbert says51 , ledbulb.zipThis is a first for this author. Its an OCX which represents a characters in the form of led bulbs.52 , textapiroutines.basContained here is a small set of routines can be used with a Rich Text box (RTF) control. It can be used for other controls as well with minor modifications. You are welcome to change, use and distribute the code as you see fit.53 , xflatbutton.zipFlatButton is an owner-drawn flat button that pops up when the mouse passes over it. This version is text-only, but has flexible color support.54 , urllabel.zipWith the development of the internet and intranet applications, this control could could in more and more useful. Its a hyperlink label which will change color or underline when the mouse goes over it 55 , progbar.zipThis is a great replacement for the standard VB progress bar. Its smooth, totally free (all the source code is here), and more versitile than the one that comes with VB.56 , splitpanel.zipThis little control with full source code is remarkably compact but does a lot of fancy things. It allows you to be able to split panels and handles all the resizing behind it. We couldn't think of how to describe it properly, but 下载 it and try it57,basicreg.zipBasic Save and Retrieve Functions58,proguse.zipKeep Track of a Programs Usage59,millisec.zipCount Time in Milliseconds 60,getday.zipGet the Day of Week that a Day Falls On61,shellend.zipNotify the User when a Shelled Process Ends 62,varlist.zipGet a List of Windows Variables 63,detdisp.zipDetermine Display Colors 64,ctrlntwk.zipControl Panel - Network65,ctrluser.zipControl Panel - User Properties66,ctrltwui.zipControl Panel - TweakUI67,ctrlthm.zipControl Panel - Themes68,ctrltele.zipControl Panel - Telephony69,ctrlsys.zipControl Panel - System Properties70,ctrlscrn.zipControl Panel - Screen Savers71,ctrlreg.zipControl Panel - Regional Settings72,ctrlprnt.zipControl Panel - Printers73,ctrlpwr.zipControl Panel - Power Management74,ctrlpw.zipControl Panel - Passwords75,ctrlodbc.zipControl Panel - ODBC3276,ctrlmm.zipControl Panel - Multimedia77,ctrlmdm.zipControl Panel - Modem78,ctrlkbd.zipControl Panel - Keyboard79,ctrlmous.zipControl Panel - Mouse80,ctrlpoa.zipControl Panel - Post Office Admin81,ctrlotlk.zipControl Panel - Outlook82,ctrljoy.zipControl Panel - Joystick83,ctrlie4.zipControl Panel - Internet Explorer 84,ctrlgame.zipControl Panel - Game Controllers85,ctrlfont.zipControl Panel - Fonts86,ctrlarmp.zip Control Panel - Add/Remove Programs87,ctrlanh.zipControl Panel - Add New Hardware88,ctrlanp.zipControl Panel - Add New Printer89,ctrlaccs.zipControl Panel - Accessibility90,ctrlbrf.zipControl Panel - Create Briefcase91,ctrlcdsk.zipControl Panel - Copy Disk92,ctrlcns.zipControl Panel - Create New Shortcut93,ctrldun.zipControl Panel - Dial-Up Networking94,ctrldisp.zipControl Panel - Display Properties95,RegControl.zipFree Registry ActiveX Control. Read/Write String/Binary/DWord values, Check if key/value exists, CreateKey, Delete key/value and enumerate keys/values!96,MouseEvent.zipThis is a Mouse Event procedure that is pretty cool. It can be used for Web designing. Check it out!97,ShellTrayIcon.zipThe CShellTrayIcon class allows your VB application to set, change and delete icons in the system's tray 98,Reboot2.zipReboot remotely. I wrote this to reboot selected PC's during off hours. It is a standalone application that will display a 10 second countdown. Any open data will try to be saved prior to the shutdown process.99,S-Secure.zipThis is S-Secure.....a security program I've coded for Windows. It has 4 modules each in a separate VB project. 100,DriveSpace.zipThis Program finds and displays the Drive's Space.101,Disable_X.zipThis user control allows you to disable the windows close "X" button. Example program included.102,SetParnt.zipShows how to assign controls to different forms at run time. 103,phone.zipA Cellular Phone Application Uses MSCOMM, Modem and normal telephone lines to make calls. You can use this application to make local as well as International calls. 104,Timer01.zipSimple program demonstrating how to create a stop watch using the Timer control. 105,Bubblesort.zipA simple Bubble Sort code that shows how the program works within a VB program. 106,systray.zipJust another Systray Utility, but worse than the others !!! static, flashing and animated Tray-Icons 107,FolderFiles.zipDemonstrates usage of progress bar and list box controls. Its purpose is to get all the files from a specified folder while showing the progress completed. 108,MultipleDataSets.zipThis is a simple, (1) form VB 6.0 program which demonstrates how to plot multiple sets of data on the same graph using the MSChart Control 6.0 (OLEDB). 109,MthVwPrj.zipMonthView control. Lets users view and set date information via a calendar-like interface. 110,calculator4.zipI know this is wierd but I made a calculator control. Just add it to your control bar, double click, and you can use the calculator when your project is at run-time. Source included.111,GradientButton.zipThis button was created to be an enhanced replacement for Visual Basic's standard command button by adding 2 more Border appearance schemes, 2 more button styles, and hover effects. 112,MSChart.zipMSChart. You can view MSChart in Line graph,Pie , Area, etc.. also you can update data provided in the Grid.. Very interesting must see it... 113,printing_tut.zipI made this for a freind to help him out with some basic Printing, i got the idea from a printing tut i found on the net, so the code is not mine. 114,treeview.zipThis code can as many child nodes to a tree view control and can save the data and structure of the treeview control in a text file. Later the data and structure can be retrieved from the text file and filled in the tree view control by clicking the load button. 115,alarm_clock.zipIt simulates an alarm clock. 116,DesktopByAlexDrankus.zipThis program hides/shows desktop, hides/shows taskbar, hides it self from the ctrl+alt+delete, uses pictures to create the forms (pretty cool forms) and many other functions just place this program and all components in a sub-folder 117,Label3D.zipLabel3D lets you change the Label Face Color Shadow Color ON/OFF Shadow. 118,HotLinks.zip Custom Control which acts like a text box, except the developer can specify hot links in the control which act like web page links allowing users to click them, while allowing the developer full control over the result of the click. 119,custbutt.zipThis application shows how to create non rectangular buttons. 120,grid.zipComplete grid coded in vb. supports : locked rows/columns , fg/bg colors , text alignment , cell-edge styles , different selectionstyles . texbox/dropdown cells , cell icons and lots more... 121,analogmeter.zipCreate your own analog meters using MSPaint. These .bmp or .gif files become your meter face. Use the (analogmeter) subroutine to automatically draw the meter needle over the meter face 122,wheel.zipSpinWheel control to be used in place of either the UpDown control or the ScrollBar control.123,ArielBrowseFolder.zipA browse folder control resembling a combobox. When the dropdown button is clicked, browse through a folder treeview to select a directory. Uses the SHBrowseForFolder function, amongst other APIs. A call back procedure is implemented showing the currently selected folder in the browse for folder dialog. 124,pp_prj.zipThis program shows you how to create a sample project that adds print preview capabilities to your Visual Basic program by using a generic object and the Printer object. 125,popup.zipPopUp buttons with only 4 lines of code. 126,adbevel.zipThe bevel control in Delphi is now available in VB. 127,rainbow.zipCool! Have a ProgressBar like in InstallShield!With free selectable fore- and backcolor and the percent value displayed in the middle!Check it out.128,gb12.zipWell folks. Another version of Gold Button is here. I've added a few things. Here they are: Property descriptions, MaskColor, UseMask, Base Address in OCX, picture will now automatically align with text and when you are in desing mode and OnUp property is bsNone, a Dash-Dot-Dot box is drawn over the button, so you can see th button's area. 129,gb11.zipA new version of Gold Button is here dudes.New version has Picture Property and Skin Support. 130,BIGDOGMEDIA.zipMEDIA PLAYER THAT SUPPORTS FORMATS LIKE MP3,AVI,MPEG,WAV ECT.EXAMPLE OF USING ANIMATION WHEN PLAYER IS LAUNCHED. 131,HTML.zipAn HTML editor with complete VB source code. 132,PrintPreview1.zipPrint Setup, and Print Priview application. 133,RTFEditor.zipRTF text editor, HTML text editor, web browser, and more...Try it. Note, make sure your printer is turned on before running the application. 134,VBExplorer-II.zipVBExplorer file utility application. This application uses the Visual Basic TreeView and ListView controls to create a file management application similar to Windows Explorer.135,resizepic.zipShows how to resize a picture box control on a form at run time.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值