springboot整合freemarker时${xxx?html}报错
时间: 2023-12-20 08:04:41 浏览: 32
在使用Freemarker的时候,我们有时候需要对输出的HTML进行转义,以避免XSS攻击等安全问题。而在Freemarker中,可以使用`${xxx?html}`的方式进行HTML转义,但是在Spring Boot中,如果直接使用`${xxx?html}`的方式,会出现报错的情况。
要解决这个问题,可以在Spring Boot的配置文件application.properties中添加以下配置:
```
spring.freemarker.template.utility-escaping=false
```
或者在Spring Boot的配置类中添加以下配置:
```
@Configuration
public class FreemarkerConfig {
@Autowired
private freemarker.template.Configuration configuration;
@PostConstruct
public void setSharedVariable() {
configuration.setBooleanFormat("true,false");
configuration.setClassicCompatible(true);
configuration.setNumberFormat("#");
configuration.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
configuration.setDateFormat("yyyy-MM-dd");
configuration.setTimeFormat("HH:mm:ss");
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
configuration.setWhitespaceStripping(true);
configuration.setSharedVariable("html_escape", new HtmlEscape());
}
}
```
其中,HtmlEscape是一个自定义的Freemarker工具类,代码如下:
```
public class HtmlEscape implements TemplateMethodModelEx {
@Override
public Object exec(List arguments) throws TemplateModelException {
if (arguments != null && arguments.size() > 0) {
SimpleScalar simpleScalar = (SimpleScalar) arguments.get(0);
String value = simpleScalar.getAsString();
return StringEscapeUtils.escapeHtml(value);
}
return null;
}
}
```
这样配置之后,就可以在Spring Boot中正常使用`${xxx?html}`进行HTML转义了。