Velocity Learning (1)--hello world

Main content:
(1) Introduction to velocity
(2) Servlet+velocity environment construction and Demo


1 Introduction to velocity

Velocity is a Java-based template engine developed by apache . Through velocity-specific syntax VTL, it can refer to the properties of Java objects in a piece of text (template), so as to achieve the purpose of generating specific text from template + data model (Java object) . Using the template engine for web development can realize the separation of Java code from the displayed page, which is convenient for the division of labor between interface designers and Java programmers.

2 Hello World

Create a web project

pom.xml

Import the corresponding jar

<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>

DemoServlet.java

package com.wuk.velocity;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/DemoServlet")
public class DemoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request,response);
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setAttribute("text", "hello");
        request.getRequestDispatcher("/WEB-INF/hello.vm").forward(request, response);
    }

}

Configuration of web.xml

    <servlet>
    <servlet-name>velocity</servlet-name>
        <servlet-class>
            org.apache.velocity.tools.view.VelocityViewServlet
        </servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>velocity</servlet-name>
    <url-pattern>*.vm</url-pattern>
    </servlet-mapping>

Be careful to intercept all vm page requests for processing

hello.vm

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Test Velocity</title>
</head>
<body>
<p>$text</p>
</body>
</html>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325588641&siteId=291194637