Въведение в скоростта на Apache

1. Общ преглед

Velocity е базиран на Java механизъм за шаблониране.

Това е уеб рамка с отворен код, предназначена да се използва като компонент на изглед в архитектурата на MVC и предоставя алтернатива на някои съществуващи технологии като JSP.

Скоростта може да се използва за генериране на XML файлове, SQL, PostScript и повечето други текстови формати.

В тази статия ще проучим как може да се използва за създаване на динамични уеб страници.

2. Как работи скоростта

Основният клас на Velocity е VelocityEngine .

Той организира целия процес на четене, анализиране и генериране на съдържание, използвайки модел на данни и шаблон за скорост.

Просто казано, ето стъпките, които трябва да следваме за всяко типично приложение за скорост:

  • Инициализирайте двигателя за скорост
  • Прочетете шаблона
  • Поставете модела на данни в контекстния обект
  • Обединете шаблона с контекстни данни и изобразете изгледа

Нека да разгледаме един пример, като следваме тези прости стъпки:

VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.init(); Template t = velocityEngine.getTemplate("index.vm"); VelocityContext context = new VelocityContext(); context.put("name", "World"); StringWriter writer = new StringWriter(); t.merge( context, writer );

3. Зависимости на Maven

За да работим с Velocity, трябва да добавим следните зависимости към нашия проект Maven:

 org.apache.velocity velocity 1.7   org.apache.velocity velocity-tools 2.0 

Най-новата версия на двете зависимости може да бъде тук: скорост и инструменти за скорост.

4. Език на шаблона за скорост

Velocity Template Language (VTL) предоставя най-простия и изчистен начин за включване на динамичното съдържание в уеб страница чрез използване на VTL препратки.

VTL препратката в шаблона за скорост започва с $ и се използва за получаване на стойността, свързана с тази препратка. VTL предоставя също набор от директиви, които могат да се използват за манипулиране на изхода на Java кода. Тези директиви започват с #.

4.1. Препратки

Има три вида препратки в Velocity, променливи, свойства и методи:

  • променливи - дефинирани в страницата с помощта на директива #set или стойност, върната от полето на Java обекта:
    #set ($message="Hello World")
  • свойства - отнася се до полета в даден обект; те също могат да се отнасят до кариерист метод на имота:
    $customer.name
  • методи - вижте метода в Java обекта:
    $customer.getName()

Крайната стойност, получена от всяка препратка, се преобразува в низ, когато се визуализира в крайния изход.

4.2. Директиви

VTL предоставя богат набор от директиви:

  • set - може да се използва за задаване на стойността на референция; тази стойност може да бъде присвоена на променлива или препратка към свойство:
    #set ($message = "Hello World") #set ($customer.name = "Brian Mcdonald")
  • условни - директивите #if, #elseif и #else предоставят начин за генериране на съдържанието въз основа на условни проверки:
    #if($employee.designation == "Manager") 

    Manager

    #elseif($employee.designation == "Senior Developer")

    Senior Software Engineer

    #else

    Trainee

    #end
  • цикли - директивата #foreach позволява циклиране върху колекция от обекти:
    
          
      #foreach($product in $productList)
    • $product
    • #end
  • включва - #include елементът предоставя възможност за импортиране на файлове в шаблона:
    #include("one.gif","two.txt","three.html"...)
  • разбор - #parse изявление позволява дизайн на шаблони, за да импортирате друг локален файл, който съдържа VTL; След това Velocity ще анализира съдържанието и ще го направи:
    #parse (Template)
  • evaluate#evaluate directive can be used to evaluate VTL dynamically; this allows the template to evaluate a String at render time, for example to internationalise the template:
    #set($firstName = "David") #set($lastName = "Johnson") #set($dynamicsource = "$firstName$lastName") #evaluate($dynamicsource)
  • break#break directive stops any further rendering of current execution scope (i.e. #foreach, #parse)
  • stop#stop directive stops any further rendering and execution of the template.
  • velocimacros#macro directive allows the template designer to define a repeated segment of VTL:
    #macro(tablerows)  #end

    This macro now can be put in any place in the template as #tablerows():

    #macro(tablerows $color $productList) #foreach($product in $productList) $product.name #end #end

4.3. Other Features

  • math – a handful built-in mathematical functions, which can be used in templates:
    #set($percent = $number / 100) #set($remainder = $dividend % $divisor)
  • range operator – that can be used in conjunction with #set and #foreach:
    #set($array = [0..10]) #foreach($elem in $arr) $elem #end

5. Velocity Servlet

The primary job of the Velocity Engine is to generate content based on a template.

The Engine doesn't contain any web related functionalities in itself. To implement a web application, we need to use a servlet or servlet-based framework.

Velocity provides one out of the box implementation VelocityViewServlet, which is a part of the velocity-tools subproject.

To make use of the built-in functionality provided by VelocityViewServlet, we can extend our servlet from VelocityViewServlet and override the handleRequest() method:

public class ProductServlet extends VelocityViewServlet { ProductService service = new ProductService(); @Override public Template handleRequest( HttpServletRequest request, HttpServletResponse response, Context context) throws Exception { List products = service.getProducts(); context.put("products", products); return getTemplate("index.vm"); } }

6. Configuration

6.1. Web Configuration

Let's now see how to configure the VelocityViewServlet in the web.xml.

We need to specify the optional initialization parameters which include velocity.properties and toolbox.xml:

 apache-velocity //...  velocity org.apache.velocity.tools.view.VelocityViewServlet  org.apache.velocity.properties /WEB-INF/velocity.properties   //...  

We also need to specify the mapping for this servlet. All the requests for velocity templates (*.vm) need to be served by the velocity servlet:

 velocityLayout *.vm 

6.2. Resource Loader

Velocity provides flexible resource loader system. It allows one or more resource loader to be in operation at the same time:

  • FileResourceLoader
  • JarResourceLoader
  • ClassPathResourceLoader
  • URLResourceLoader
  • DataSourceResourceLoader
  • WebappResourceLoader

These resource loaders are configured in velocity.properties:

resource.loader=webapp webapp.resource.loader.class=org.apache.velocity.tools.view.WebappResourceLoader webapp.resource.loader.path = webapp.resource.loader.cache = true

7. Velocity Template

Velocity template is the place where all the view generation logic is written. These pages are written using Velocity Template Language (VTL):

 ...   ... 

$products.size() Products on Sale!

We are proud to offer these fine products at these amazing prices. ... #set( $count = 1 )

#foreach( $product in $products ) #set( $count = $count + 1 ) #end
Serial # Product Name Price
$count) $product.getName() $product.getPrice()

8. Managing the Page Layout

Velocity provides a simple layout control and customizable error screens for Velocity Tool based application.

VelocityLayoutServlet encapsulates this capability to render the specified layouts. VelocityLayoutServlet is an extension to VelocityViewServlet.

8.1. Web Configuration

Let's see how to configure the VelocityLayoutServlet. The servlet is defined for intercepting the requests for velocity template pages and the layout specific properties are defined in velocity.properties file:

 // ...  velocityLayout org.apache.velocity.tools.view.VelocityLayoutServlet  org.apache.velocity.properties /WEB-INF/velocity.properties   // ...  velocityLayout *.vm  // ... 

8.2. Layout Templates

Layout template defines the typical structure of a velocity page. By default, the VelocityLayoutServlet searches for Default.vm under the layout folder. Overriding few properties can change this location:

tools.view.servlet.layout.directory = layout/ tools.view.servlet.layout.default.template = Default.vm 

The layout file consists of header template, footer template, and a velocity variable $screen_content which renders the contents of requested velocity page:

  Velocity #parse("/fragments/header.vm") $screen_content #parse("/fragments/footer.vm") 

8.3. Layout Specification in the Requested Screen

Layout for a particular screen can be defined as a velocity variable at the beginning of a page. That is done by putting this line in the page:

#set($layout = "MyOtherLayout.vm")

8.4. Layout Specification in the Request Parameter

We can add a request parameter in the query string layout=MyOtherLayout.vm and VLS will find it and render the screen within that layout instead of searching for default layout.

8.5. Error Screens

Customized error screen can be implemented using velocity layout. VelocityLayoutServlet provides two variables $error_cause and $stack_trace to present the exception details.

Error page can be configured in velocity.properties file:

tools.view.servlet.error.template = Error.vm

9. Conclusion

В тази статия научихме как Velocity е полезен инструмент за изобразяване на динамичните уеб страници. Също така видяхме различни начини за използване на сървлети, предоставяни от скоростта.

Имаме и статия, фокусирана върху конфигурация на скоростта с Spring MVC тук в Baeldung.

Пълният код за този урок е достъпен в GitHub.