SpringMVC 中的视图如何使用 Velocity
介绍
在 SpringMVC 中,我们可以使用多种视图技术来渲染响应数据。其中,Velocity 是一种流行的模板引擎,它可以将模板文件和数据结合起来,生成最终的 HTML 页面。本文将介绍如何在 SpringMVC 中使用 Velocity 视图。
准备工作
在开始之前,需要进行一些准备工作:
- 添加 SpringMVC 和 Velocity 的依赖
在 pom.xml
文件中添加以下依赖:
<!-- SpringMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.8</version>
</dependency>
<!-- Velocity -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.3.0</version>
</dependency>
- 配置 SpringMVC
在 SpringMVC 的配置文件中添加以下配置:
<!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="cache" value="true"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".vm"/>
<property name="contentType" value="text/html;charset=UTF-8"/>
<property name="exposeSpringMacroHelpers" value="true"/>
<property name="exposeRequestAttributes" value="true"/>
<property name="exposeSessionAttributes" value="true"/>
<property name="toolAttributeNames" value="dateTool, numberTool"/>
<property name="order" value="1"/>
</bean>
<!-- 配置 Velocity 模板引擎 -->
<bean id="velocityConfigurer" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/views/"/>
<property name="velocityProperties">
<props>
<prop key="input.encoding">UTF-8</prop>
<prop key="output.encoding">UTF-8</prop>
<prop key="resource.loader">class</prop>
<prop key="class.resource.loader.class">org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader</prop>
</props>
</property>
</bean>
在上面的配置中,我们使用了 VelocityViewResolver
和 VelocityConfigurer
两个类来配置 Velocity 视图解析器和模板引擎。
创建 Velocity 模板文件
在 src/main/webapp/WEB-INF/views
目录下创建一个名为 hello.vm
的文件,内容如下:
<!DOCTYPE html>
<html>
<head>
<title>Hello, Velocity!</title>
</head>
<body>
<h1>Hello, ${name}!</h1>
<p>Today is ${date}.</p>
</body>
</html>
在上面的模板文件中,我们使用了 Velocity 的语法来插入变量。${name}
和 ${date}
分别表示从后端传递过来的 name
和 date
变量的值。
创建控制器
在 src/main/java
目录下创建一个名为 HelloController
的控制器,内容如下:
@Controller
public class HelloController {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public ModelAndView hello(@RequestParam("name") String name) {
ModelAndView modelAndView = new ModelAndView("hello");
modelAndView.addObject("name", name);
modelAndView.addObject("date", new Date());
return modelAndView;
}
}
在上面的控制器中,我们使用了 @Controller
和 @RequestMapping
注解来定义一个处理 HTTP GET 请求的方法。该方法接收一个名为 name
的请求参数,并将其与当前日期一起传递给 hello
视图。
运行应用程序
现在,我们可以启动应用程序并访问 http://localhost:8080/hello?name=World
,就可以看到渲染后的页面了。
总结
在本文中,我们介绍了如何在 SpringMVC 中使用 Velocity 视图。首先,我们添加了 SpringMVC 和 Velocity 的依赖,并配置了视图解析器和模板引擎。然后,我们创建了一个 Velocity 模板文件,用于渲染最终的 HTML 页面。最后,我们创建了一个控制器,将数据传递给 Velocity 模板文件,并渲染最终的页面。
使用 Velocity 视图可以使我们更容易地编写 HTML 页面,同时也可以将页面和数据分离开来,使代码更易于维护和修改。在实际开发中,我们可以根据需要选择不同的视图技术,以便更好地满足需求。