Solon v2.7.5

solon.view.velocity

</> markdown

1、描述

视图扩展插件,为 Solon View 提供基于 velocity 的框架适配。

2、应用示例

DemoController.java

//顺便,加个国际化在模板里的演法
@I18n
@Controller
public class DemoController{
    @Mapping("/test")
    public ModelAndView test() {
        ModelAndView model = new ModelAndView("velocity.vm");
        model.put("title", "dock");
        model.put("msg", "你好 world!");

        return model;
    }
}

resources/templates/velocity.vml

<!DOCTYPE html>
<html>
<head>
    <title>${title}</title>
</head>
<body>
velocity::${msg};i18n::${i18n.get("login.title")}
</body>
</html>

3、支持事件扩展定制示例

public class App {
    public static void main(String[] args) {
        Solon.start(App.class, args, app->{
            app.onEvent(RuntimeInstance.class, e -> {
                //可能会获取两次事件(一个是 debug 模式下才有的)
            });
        });
    }
}

4、自定义标签示例

以插件自带的权限验证标签为例:

#authPermissions("user:del")
我有user:del权限
#end

自定义标签和共享变量代码实现:

@Component("view:authPermissions")
public class AuthPermissionsTag extends Directive {
    @Override
    public String getName() {
        return AuthConstants.TAG_authPermissions;
    }

    @Override
    public int getType() {
        return BLOCK;
    }

    @Override
    public boolean render(InternalContextAdapter context, Writer writer, Node node) throws IOException, ResourceNotFoundException, ParseErrorException, MethodInvocationException {
        int attrNum = node.jjtGetNumChildren();

        if (attrNum == 0) {
            return true;
        }

        ASTBlock innerBlock = null;
        List<String> attrList = new ArrayList<>();
        for (int i = 0; i < attrNum; i++) {
            Node n1 = node.jjtGetChild(i);
            if (n1 instanceof ASTStringLiteral) {
                attrList.add((String) n1.value(context));
                continue;
            }

            if (n1 instanceof ASTBlock) {
                innerBlock = (ASTBlock) n1;
            }
        }

        if (innerBlock == null || attrList.size() == 0) {
            return true;
        }


        String nameStr = attrList.get(0);
        String logicalStr = null;
        if (attrList.size() > 1) {
            logicalStr = attrList.get(1);
        }

        if (Utils.isNotEmpty(nameStr)) {

            String[] names = nameStr.split(",");
            if (names.length > 0) {
                if (AuthUtil.verifyPermissions(names, Logical.of(logicalStr))) {
                    StringWriter content = new StringWriter();
                    innerBlock.render(context, content);
                    writer.write(content.toString());
                }
            }
        }

        return true;
    }
}

@Component("share:demo1")
public class Demo {
    public String hello(){
        return "hello";
    }
}