使用veloctiy代替jsp

用veloctiy代替jsp作为视图展示
这里我们需要一个velocity的扩展工具包veloctiy-tools,我们可以在velocity的官方网站中得到。
在web.xml中加入相关的servlet 配置
 <servlet>
<servlet-name>velocity</servlet-name>
<servlet-class>
org.apache.velocity.tools.view.servlet.VelocityViewServlet</servlet-class>
<init-param>
<param-name>org.apache.velocity.toolbox</param-name>
<param-value>/WEB-INF/tools.xml</param-value>
</init-param>
<init-param>
<param-name>org.apache.velocity.properties</param-name>
<param-value>/WEB-INF/velocity.properties</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>velocity</servlet-name>
<url-pattern>*.vm</url-pattern>
</servlet-mapping>


tools.xml
<?xml version="1.0"?>
<!--
key表示vm引用的对象名称,该名称必须是唯一的 scope表示对象的生命周期,其可以设置的值为:request,session,application。request-path假如scope设置为request,该对象是为那一个servlet使用的,request-path的命名最后需要加上允许访问的路径,这是必须的 class表示对应的实现类
-->
<toolbox>
<data type="string">
<key>userList</key>
<value>用户列表</value>
</data>
<tool>
<key>userService</key>
<scope>request</scope>
<request-path>/user/*</request-path> <!-- /user/路径可以访问 -->
<class>demo.service.UserService</class>
</tool>
</toolbox>



package demo.model;

public class User {
private int id;
private String name;
private int age;

public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}

public int getAge() {
return age;
}

public int getId() {
return id;
}

public String getName() {
return name;
}
}

package demo.service;

import java.util.ArrayList;
import java.util.List;
import demo.model.User;

public class UserService {
static private List<User> users = new ArrayList<User>();
static {
for (int i = 0; i < 10; i++) {
users.add(new User(i, "name" + i, i + 3));
}
}

public List<User> listUsers() {
return users;
}

public User getUser(int id) {
for (User user : users) {
if (user.getId() == id)
return user;
}
return null;
}
public int parseInt(String id){
return Integer.parseInt(id);
}
}



下面看看我们的两个模板
一个是显示全部users.vm 一个是显示单个user.vm
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>$userList</title>
</head>
<body>
<table width="50%">
<tr bgcolor="#FFFFFF">
<th>姓名</th>
<th>年龄</th>
</tr>
#foreach($user in ${userService.listUsers()})
<tr bgcolor="#FFFFFF">
<td><a href="user.vm?id=${user.getId()}">${user.getName()}</a></td>
<td align="center">${user.getAge()}</td>
</tr>
#end
</table>
</body>
</html>


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>$userList</title>
</head>
<body>
#set($id = $request.getParameter("id"))
$id
<table>
<tr>
<td> 姓名</td>
<td>年龄</td>
</tr>
#set( $user=${userService.getUser($userService.parseInt($id))} )
<tr>
<td>${user.getName()}</td>
<td>${user.getAge()}</td>
<tr>
</table>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值