Quick Guide to Spring MVC with Velocity – 使用Velocity的Spring MVC快速指南

最后修改: 2016年 7月 28日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.绪论

Velocity is a template engine from the Apache Software Foundation that can work with normal text files, SQL, XML, Java code and many other types.

Velocity是一个来自Apache软件基金会的模板引擎,可以处理正常的文本文件、SQL、XML、Java代码和许多其他类型。

In this article we’re going to focus on utilizing Velocity with a typical Spring MVC web application.

在这篇文章中,我们将专注于在一个典型的Spring MVC网络应用中利用Velocity。

2. Maven Dependencies

2.Maven的依赖性

Let’s start by enabling the Velocity support – with the following dependencies:

让我们从启用Velocity支持开始–有以下依赖性。

<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>

The newest versions of both can be found here: velocity and velocity-tools.

两者的最新版本可以在这里找到。velocityvelocity-tools

3. Configuration

3.配置

3.1. Web Config

3.1.网络配置[/strong]

If we don’t want to use an web.xml, let’s configure our web project using Java and an initializer:

如果我们不想使用web.xml,让我们使用Java和一个初始化器来配置我们的Web项目:

public class MainWebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext sc) throws ServletException {
        AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
        root.register(WebConfig.class);

        sc.addListener(new ContextLoaderListener(root));

        ServletRegistration.Dynamic appServlet = 
          sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext()));
        appServlet.setLoadOnStartup(1);
    }
}

Alternatively, we can of course use the traditional web.xml:

另外,我们当然也可以使用传统的web.xml

<web-app ...>
    <display-name>Spring MVC Velocity</display-name>
    <servlet>
        <servlet-name>mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-servlet.xml</param-value>
     </init-param>
     <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>mvc</servlet-name>
    <url-pattern>/*</url-pattern>
    </servlet-mapping>
 
    <context-param>
        <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

Notice that we mapped our servlet on the “/*” path.

注意,我们在”/*”路径上映射了我们的Servlet。

3.2. Spring Config

3.2.Spring配置

Let’s now go over a simple Spring configuration – again, starting with Java:

现在我们来看看一个简单的Spring配置–还是从Java开始。

@Configuration
@EnableWebMvc
@ComponentScan(basePackages= {
  "com.baeldung.mvc.velocity.controller",
  "com.baeldung.mvc.velocity.service" }) 
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
          .addResourceHandler("/resources/**")
          .addResourceLocations("/resources/");
    }
 
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public ViewResolver viewResolver() {
        VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver();
        bean.setCache(true);
        bean.setPrefix("/WEB-INF/views/");
        bean.setLayoutUrl("/WEB-INF/layouts/layout.vm");
        bean.setSuffix(".vm");
        return bean;
    }
    
    @Bean
    public VelocityConfigurer velocityConfig() {
        VelocityConfigurer velocityConfigurer = new VelocityConfigurer();
        velocityConfigurer.setResourceLoaderPath("/");
        return velocityConfigurer;
    }
}

And let’s also have a quick look at the XML version of the configuration:

让我们也快速看一下XML版本的配置。

<beans ...>
    <context:component-scan base-package="com.baeldung.mvc.velocity.*" />
    <context:annotation-config /> 
    <bean id="velocityConfig" 
      class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
        <property name="resourceLoaderPath">
            <value>/</value>
        </property>
    </bean> 
    <bean id="viewResolver"
      class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
        <property name="cache" value="true" />
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="layoutUrl" value="/WEB-INF/layouts/layout.vm" />
        <property name="suffix" value=".vm" />
    </bean>
</beans>

Here we are telling Spring where to look for annotated bean definitions:

这里我们要告诉Spring在哪里寻找注解的Bean定义。

<context:component-scan base-package="com.baeldung.mvc.velocity.*" />

We are indicating we are going to use annotation-driven configuration in our project with the following line:

我们用下面一行表示我们将在我们的项目中使用注释驱动的配置。

<context:annotation-config />

By creating “velocityConfig” and “viewResolver” beans we are telling VelocityConfigurer where to look for templates, and VelocityLayoutViewResolver where to find views and layouts.

通过创建”velocityConfig“和”viewResolver“Bean,我们告诉VelocityConfigurer在哪里寻找模板,以及VelocityLayoutViewResolver在哪里寻找视图和布局。

4. Velocity Templates

4.速度模板

Finally, let’s create our templates – starting with a common header:

最后,让我们创建我们的模板–从一个普通的标题开始。

<div style="...">
    <div style="float: left">
        <h1>Our tutorials</h1>
    </div>
</div>

and footer:

和页脚。

<div style="...">
    @Copyright baeldung.com
</div>

And let’s define a common layout for our site where we are going to use above fragments with parse in the following code:

让我们为我们的网站定义一个共同的布局,我们将在下面的代码中使用上述片段与parse

<html>
    <head>
        <title>Spring & Velocity</title>  
    </head>
    <body>
        <div>
            #parse("/WEB-INF/fragments/header.vm")
        </div>  
        <div>
            <!-- View index.vm is inserted here -->
            $screen_content
        </div>  
        <div>
            #parse("/WEB-INF/fragments/footer.vm")
        </div>
    </body>
</html>

You can check that $screen_content variable has the content of the pages.

你可以检查$screen_content变量是否有页面的内容。

Finally, we’ll create a template for the main content:

最后,我们将为主要内容创建一个模板。

<h1>Index</h1>
 
<h2>Tutorials list</h2>
<table border="1">
    <tr>
        <th>Tutorial Id</th>
        <th>Tutorial Title</th>
        <th>Tutorial Description</th>
        <th>Tutorial Author</th>
    </tr>
    #foreach($tut in $tutorials)
    <tr>
        <td>$tut.tutId</td>
        <td>$tut.title</td>
        <td>$tut.description</td>
        <td>$tut.author</td>
    </tr>
    #end
</table>

5. Controller Side

5.控制器一侧

We have created a simple controller which returns a list of tutorials as content for our layout to be populated with:

我们已经创建了一个简单的控制器,它返回一个教程的列表作为内容,供我们的布局填充使用。

@Controller
@RequestMapping("/")
public class MainController {
 
    @Autowired
    private ITutorialsService tutService;

    @RequestMapping(value ="/", method = RequestMethod.GET)
    public String defaultPage() {
        return "index";
    }

    @RequestMapping(value ="/list", method = RequestMethod.GET)
    public String listTutorialsPage(Model model) { 
        List<Tutorial> list = tutService.listTutorials();
        model.addAttribute("tutorials", list);
        return "index";
    }
}

Finally, we can access this simple example locally – for example at: localhost:8080/spring-mvc-velocity/

最后,我们可以在本地访问这个简单的例子–例如在。localhost:8080/spring-mvc-velocity/a>

6. Conclusion

6.结语

In this simple tutorial, we have configured Spring MVC web application with Velocity template engine.

在这个简单的教程中,我们用Velocity模板引擎配置了Spring MVC网络应用。

The full sample code for this tutorial can be found in our GitHub repository.

本教程的完整示例代码可以在我们的GitHub 仓库中找到。