您的位置:首页 > 编程语言 > Java开发

(三)velocity--springmvc整合velocity

2016-04-05 11:28 399 查看
还是在springmvc工程上进行整合

添加jar包
右键pom.xml,菜单maven-->Add Dependency ,可以搜索添加velocity和velocity-tools两个包,另外还需要添加spring-context-support,不然会报错

添加vm文件

在WEB-INF下新建了一个views文件夹,里面加了两个文件,一个用来做模板,一个具体页面。

layout.vm

<head>
<title>Spring MVC and Velocity</title>
</head>
<body>
<h1>Spring MVC and Velocity</h1>
$screen_content
<hr />
Copyright © 2016 lkf
</body>
</html>


hello.vm

welcome ${user}


配置

在servlet的配置文件中,加入velocity的相关配置,注意路径
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <mvc:annotation-driven />

<context:component-scan base-package="com.lucky.study"/>
<bean id="velocityConfig"
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>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="layoutUrl" value="layout.vm" />
<property name="suffix" value=".vm" />
<property name="contentType"><value>text/html;charset=UTF-8</value></property>
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>


java文件

package com.lucky.study.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MyController {

@RequestMapping(value = "/hello")
public ModelAndView hello() {
ModelAndView mv = new ModelAndView();
mv.addObject("user", "lucky");
//设置逻辑视图名,视图解析器会根据该名字解析到具体的视图页面
mv.setViewName("hello");
return mv;
}
}


运行后 访问http://localhost:8080/velocity/hello.do
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  velocity spring mvc java