【Velocity四】Velocity与Java互操作

Velocity出现的目的用于简化基于MVC的web应用开发,用于替代JSP标签技术,那么Velocity如何访问Java代码.本篇继续以Velocity三http://bit1129.iteye.com/blog/2106142中的例子为基础,

 

   POJO

  

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

 

 

   Service

  

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");
    }
}

  

   Servlet代码

   

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");
    }
}

 

 

   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方法除外)

 

 

 

 

你可能感兴趣的:(velocity)