001/** 002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package io.jboot.components.cache.interceptor; 017 018import com.jfinal.core.Controller; 019import com.jfinal.kit.LogKit; 020import com.jfinal.template.Env; 021import com.jfinal.template.io.Writer; 022import com.jfinal.template.stat.Scope; 023import io.jboot.utils.StrUtil; 024import io.jboot.web.controller.JbootControllerContext; 025import io.jboot.web.directive.base.JbootDirectiveBase; 026 027import java.io.IOException; 028 029public class ParaDirective extends JbootDirectiveBase { 030 031 @Override 032 public void onRender(Env env, Scope scope, Writer writer) { 033 034 Controller controller = JbootControllerContext.get(); 035 if (controller == null) { 036 throw new IllegalStateException("#para(...) directive only use for controller." + getLocation()); 037 } 038 039 String key = getPara(0, scope); 040 String defaultValue = getPara(1, scope); 041 042 if (StrUtil.isBlank(key)) { 043 throw new IllegalArgumentException("#para(...) argument must not be empty." + getLocation()); 044 } 045 046 String value = controller.getPara(key); 047 if (StrUtil.isBlank(value)) { 048 value = StrUtil.isNotBlank(defaultValue) ? defaultValue : ""; 049 } 050 051 try { 052 writer.write(value); 053 } catch (IOException e) { 054 LogKit.error(e.toString(), e); 055 } 056 } 057 058 public static Object para(String key) { 059 return para(key, null); 060 } 061 062 public static Object para(String key, Object defaultValue) { 063 Controller controller = JbootControllerContext.get(); 064 if (controller == null) { 065 throw new IllegalStateException("para(...) method only use for controller."); 066 } 067 068 String value = controller.get(key); 069 070 if (StrUtil.isNumeric(value)) { 071 return Long.valueOf(value); 072 } 073 074 if (StrUtil.isDecimal(value)) { 075 return Double.parseDouble(value); 076 } 077 078 return StrUtil.isNotBlank(value) ? value : defaultValue; 079 } 080} 081