概述
操作环境:dubbo + zookeeper + springboot
参考文章:https://blog.csdn.net/hzau_itdog/article/details/89400804
-
引入freemarker pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
-
配置webMvc 配置静态资源路径
package com.skindow.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
* Created by Administrator on 2019/9/3.
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
/**
* Override this method to add resource handlers for serving static resources.
*
* @param registry
* @see ResourceHandlerRegistry
*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/");
registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/static/statics/");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
/**
* Override this method to configure cross origin requests processing.
*
* @param registry
* @see CorsRegistry
* @since 4.2
*/
@Override
protected void addCorsMappings(CorsRegistry registry) {
super.addCorsMappings(registry);
}
/**
* Override this method to add Spring MVC interceptors for
* pre- and post-processing of controller invocation.
*
* @param registry
* @see InterceptorRegistry
*/
@Override
protected void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
}
}
-
定义json方法
package com.skindow.util;
import com.alibaba.fastjson.JSON;
/**
* Created by Administrator on 2019/9/3.
*/
public class MyJson {
public static String toJson(Object src) {
String json = JSON.toJSONString(src);
return json;
}
}
-
配置Freemarker的配置
FreeMarker内部使用的变量的类型都实现了freemarker.template.TemplateModel接口。
我们需要把我们刚才的自定义类包装成TemplateModel的子类TemplateHashModel
package com.skindow.util;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.Configuration;
import freemarker.template.TemplateHashModel;
import freemarker.template.TemplateModelException;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Administrator on 2019/9/3.
*/
@Slf4j
public class FreemarkerStaticModels extends HashMap<String, Object> {
public FreemarkerStaticModels(Map<String, String> classMap) {
for (String key : classMap.keySet()) {
put(key, getModel(classMap.get(key)));
}
}
private TemplateHashModel getModel(String packageName) {
BeansWrapper wrapper = new BeansWrapperBuilder(Configuration.VERSION_2_3_28).build();
TemplateHashModel fileStatics=null;
try {
fileStatics = (TemplateHashModel) wrapper.getStaticModels().get(packageName);
return fileStatics;
} catch (TemplateModelException e) {
log.error(e.toString());
}
return fileStatics;
}
}
package com.skindow.config;
import com.skindow.util.FreemarkerStaticModels;
import freemarker.template.TemplateException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactory;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;
/**
* Created by Administrator on 2019/9/3.
*/
@Configuration
public class FreeMarkerConfig {
@Bean
public ViewResolver viewResolverFtl() {
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
resolver.setCache(false);
resolver.setViewClass(FreeMarkerView.class);
resolver.setRequestContextAttribute("re");
resolver.setExposeRequestAttributes(true);
resolver.setExposeSessionAttributes(true);
resolver.setSuffix(".ftl");
resolver.setContentType("text/html;charset=UTF-8");
resolver.setOrder(0);
//添加自定义解析器
resolver.setAttributesMap(new FreemarkerStaticModels(new HashMap<String, String>()
{{
put("Json", "com.skindow.util.MyJson");
}}));
return resolver;
}
@Bean
public FreeMarkerConfigurer freemarkerConfig() throws IOException, TemplateException {
FreeMarkerConfigurationFactory factory = new FreeMarkerConfigurationFactory();
factory.setTemplateLoaderPath("classpath:static/view/");
factory.setDefaultEncoding("UTF-8");
factory.setPreferFileSystemAccess(false);
FreeMarkerConfigurer result = new FreeMarkerConfigurer();
freemarker.template.Configuration configuration = factory.createConfiguration();
configuration.setClassicCompatible(true);
result.setConfiguration(configuration);
Properties settings = new Properties();
settings.put("template_update_delay", "0");
settings.put("default_encoding", "UTF-8");
settings.put("number_format", "0.######");
settings.put("classic_compatible", true);
settings.put("template_exception_handler", "ignore");
result.setFreemarkerSettings(settings);
return result;
}
}
- 控制类
package com.skindow.controller;
import com.skindow.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Created by Administrator on 2019/9/3.
*/
@Controller
@Slf4j
@RequestMapping("/welcome/demo")
@Api("skindow-test")
public class IndexController {
@Autowired
private UserService userService;
@RequestMapping("/index")
@ApiOperation(httpMethod = "GET", value = "通过ID查询用户", consumes = "application/json")
public String queryUserById(Model model, @RequestParam(value = "id") String id)
{
model.addAttribute("user",userService.getUser(id));
return "index";
}
}
- view
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>welcome to here</title>
</head>
<body>
<h1>user toJson : ${Json.toJson(user)}</h1>
</body>
</html>
目录大致这样
- 启动测试
http://localhost:8089/welcome/demo/index?id=1
结果如下
项目地址 github 对应tag freemarkerDemo
最后
以上就是成就魔镜为你收集整理的springboot整合freemarker + 自定义方法输出json格式 教程篇的全部内容,希望文章能够帮你解决springboot整合freemarker + 自定义方法输出json格式 教程篇所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复