【Velocity四】Velocity与Java互操作
Java  /  管理员 发布于 2年前   139
Velocity出现的目的用于简化基于MVC的web应用开发,用于替代JSP标签技术,那么Velocity如何访问Java代码.本篇继续以Velocity三http://bit1129.iteye.com/blog/2106142中的例子为基础,
package com.tom.servlets;public class User { private String name; private String passwd; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; }}
package com.tom.servlets;public class UserService { public User get(String userId) { User user = new User(); user.setName("tom"); user.setPasswd("tom_pwd"); return user; } public User get(Long userId) { User user = new User(); user.setName("Jack"); user.setPasswd("Jack"); return user; } public void save() {//用于测试,vm是否可以调用无参数的方法 System.out.println("save is called"); }}
package com.tom.servlets;import org.apache.velocity.Template;import org.apache.velocity.context.Context;import org.apache.velocity.tools.view.VelocityViewServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class TestVelocityViewServlet extends VelocityViewServlet { @Override protected Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) { UserService userService = new UserService(); ctx.put("userService" , userService);//把userService对象设置到Context中 return getTemplate("obj.vm"); }}
<!--obj.vm--><html> <body> <p>$userService</p> ##call userService's toString method #set($user = $userService.get(0)) ##When call the java method on its object, only string typed parameters can be accepted <p>$user.name</p> ##print #$user.name as it is, because $user can't be resolved <p>$user.getName()</p> ##Equivalent with $user.name #set($user = $userService.get("0")) <p>$user.name</p> ##print $$user.name as it is, because $user can't be resolved <p>$user.getName()</p> ##Equivalent with $user.name <p>$user.save()</p> ##$user.save can't be resolved,so vm can't resolve method that takes no parameter </body></html>
com.tom.servlets.UserService@48b4721b
$user.name
$user.getName()
tom
tom
$user.save()
1.可以通过Velocity将Java的对象注入到Context中,这样在vm中可以获得这个注入的Java对象,例子中调用了这个Java对象的toString方法
2.在vm中,仅仅能调用Java对象的带有String类型参数的方法,这是非性常巨大的局限,因为在vm中,没法像在JSP中通过<%%>创建Java对象,然后把它作为参数调用Java的方法
3.对于setter和getter,可以直接使用属性进行方法,例如$user.getName和$user.name是等价的,不管User类是否定义了name属性(比如把User类中的属性name改名为xname,getName和setName方法名不变)
4.$user.save()不能正确解析,也就是说,vm只能调用Java对象带String类型参数的方法(POJO的get方法除外)
博主 在
hyperf框架常用命令-在centos7中退出命令及在docker容器中退出命令中评论 @路过的靓仔:cdn静态资源被墙,已修复..GGGGGGGGG 在
layui框架常用输入框介绍中评论 写的很好解决问题..路过的靓仔 在
hyperf框架常用命令-在centos7中退出命令及在docker容器中退出命令中评论 剩下好多 wait 状态的..激光豆芽 在
为什么你不能安逸?国内996为什么没有国外955香?中评论 国内现在无意义的内卷太多了..激光豆芽 在
阿里云香港服务器搭建自用vpn:Shadowsocks使用流程步骤中评论 厉害了..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号