springboot+freemarker 增加自定义变量和自定义

时间:2022-11-02 20:20:41

这个主要是因为喜欢在spring+springmvc中用freemarker时,增加${base} ,${jsPath},${cssPath}等等全局的变量来使用,这样不用使用相对路径,或者有统一的资源服务器的时候,可以动态的改变路径。还有自己定义一些方法在freemarker模板中使用,例如${conver('userType',e.user.type)},我们可以在后端对一些参数值进行转换。

刚换成springboot没有了配置文件,又不想往里边扔xml,有些强迫症,所以搞了一下,发现在springboot里实现也很简单。

直接贴代码


这里放到Application运行类中


    /**
     * 增加自定义视图变量和方法
     *
     * @return
     */
    @Bean
    public CommandLineRunner customFreemarker(FreeMarkerViewResolver resolver) {
        return new CommandLineRunner() {
            @Override
            public void run(String... strings) throws Exception {
			    //增加视图
                resolver.setViewClass(MyFreemarkerView.class);
                //添加自定义解析器
                Map map = resolver.getAttributesMap();
                map.put("conver", new MyConver());
            }
        };
    }


package com.xyauto.qa.core.assist;

import com.xyauto.qa.cons.QcdqcdnStatic;
import com.xyauto.qa.util.RequestUtil;
import com.xyauto.qa.util.SpringIocUtil;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by shiqm on 2017-04-07.
 */
public class MyFreemarkerView extends FreeMarkerView {

    @Override
    protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception {
        String base = RequestUtil.getBasePath(request);
        model.put("base", base);
        model.put("h5Url", qcdqcdnStatic.getH5());
        super.exposeHelpers(model, request);
    }
}

h5Url那个请忽略,我配置文件里自定义的一些路径,总之这样就可以在模板中使用${h5Url}  ${base},解析的值就是你设定的值


package com.xyauto.qa.util;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by shiqm on 2017/3/14.
 */
public class RequestUtil {

    public static String getRequestIP(HttpServletRequest request) {
        String clientIp = request.getHeader("x-forwarded-for");
        if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("Proxy-Client-IP");
        }
        if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getHeader("WL-Proxy-Client-IP");
        }
        if (clientIp == null || clientIp.length() == 0 || "unknown".equalsIgnoreCase(clientIp)) {
            clientIp = request.getRemoteAddr();
        }
        return clientIp;
    }

    public static boolean isResponseBody(HttpServletRequest request) {
        if (request.getRequestURI().indexOf("ajax") > -1) {
            return true;
        }
        return false;
    }


    /**
     * 得到请求的根目录
     *
     * @param request
     * @return
     */
    public static String getBasePath(HttpServletRequest request) {
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort() + path;
        return basePath;
    }

    /**
     * 得到结构目录
     *
     * @param request
     * @return
     */
    public static String getContextPath(HttpServletRequest request) {
        String path = request.getContextPath();
        return path;
    }

}

下边是自定义方法,我这里主要是做转换器用,所以第一个参数是key,进行不同类型参数的转换器,我把代码就都扔来,自己看就行,很简单

package com.xyauto.qa.core.conver;

import com.xyauto.qa.cons.ConvertCons;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;

import java.util.List;

/**
 * Created by shiqm on 2017-05-03.
 */
public class MyConver implements TemplateMethodModelEx {
    @Override
    public Object exec(List arguments) throws TemplateModelException {
        if (null != arguments && 2 == arguments.size()) {
            String key = String.valueOf(arguments.get(0));
            try {
                switch (key) {
                    case "source":
                        return ConvertCons.ResourceCover.get(Integer.parseInt(String.valueOf(arguments.get(1))));
                    case "userType":
                        return ConvertCons.UserTypeCover.get(Integer.parseInt(String.valueOf(arguments.get(1))));
                    case "logModule":
                        return ConvertCons.LogModuleCover.get(Integer.parseInt(String.valueOf(arguments.get(1))));
                    case "logAction":
                        return ConvertCons.LogActionCover.get(Integer.parseInt(String.valueOf(arguments.get(1))));
                    default:
                        return null;
                }
            }catch (Exception e){
                return null;
            }
        } else {
            return null;
        }
    }
}


 

package com.xyauto.qa.cons;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by shiqm on 2016-04-23.
 */
public class ConvertCons {

    public static final class ResourceCover {
        public static final Map<Integer, String> map = new HashMap<Integer, String>();

        static {
            init();
        }

        public static void init() {
            map.put(1, "PC");
            map.put(2, "IOS");
            map.put(3, "Android");
            map.put(4, "M站");
            map.put(5, "H5");
            map.put(6, "H51");
            map.put(101, "慧商机");
            map.put(102, "百度");
            map.put(103, "360");
            map.put(998, "后台创建");
            map.put(999, "批量导入");
        }

        public static String get(Integer key) {
            return map.get(key);
        }

        public static Map<Integer, String> getMap() {
            return map;
        }
    }


    public static final class UserTypeCover {
        public static final Map<Integer, String> map = new HashMap<Integer, String>();

        static {
            init();
        }

        public static void init() {
            map.put(0, "普通用户");
            map.put(1, "标兵");
            map.put(2, "专家");
            map.put(3, "经纪人");
        }

        public static String get(Integer key) {
            return map.get(key);
        }

        public static Map<Integer, String> getMap() {
            return map;
        }
    }


    public static final class LogModuleCover {
        public static final Map<Integer, String> map = new HashMap<Integer, String>();

        static {
            init();
        }

        public static void init() {
            LogModule[] temps = LogModule.values();
            for (LogModule logModule : temps) {
                map.put(logModule.getValue(), logModule.getName());
            }
        }

        public static String get(Integer key) {
            return map.get(key);
        }

        public static Map<Integer, String> getMap() {
            return map;
        }
    }

    public static final class LogActionCover {
        public static final Map<Integer, String> map = new HashMap<Integer, String>();

        static {
            init();
        }

        public static void init() {
            LogAction[] temps = LogAction.values();
            for (LogAction logAction : temps) {
                map.put(logAction.getValue(), logAction.getName());
            }
        }

        public static String get(Integer key) {
            return map.get(key);
        }

        public static Map<Integer, String> getMap() {
            return map;
        }
    }

}

   之后页面里就可以这么用了 ${conver('userType',e.user.type)},按这方法,自己爱怎么搞就怎么搞吧