2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > springboot freemarker不渲染页面返回字符串

springboot freemarker不渲染页面返回字符串

时间:2022-11-01 13:24:46

相关推荐

springboot freemarker不渲染页面返回字符串

在集成spring boot与freemarker时,Controller不返回渲染的模板页面,而是返回模板字符串,具体如下

pom.xml

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId><version>RELEASE</version></dependency>

模板文件

模板文件位于:src\main\resources\templates\welcome.ftl

<!DOCTYPE html><html lang="en"><body>Date: ${time?date}<br>Message: ${message}</body></html>

Controller.java

```javapackage com.xleiy.blog.controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import java.util.Date;import java.util.Map;/*** @author: xlei* @Copyright (c) spring_boot_blog* @项目名称: spring_boot_blog* @类名称: WelcomeController* @创建时间: /1/3 16:33* @类描述:*/@RestControllerpublic class WelcomeController {@GetMapping("/welcome")public String welcome(Map<String, Object> model) {model.put("time", new Date());model.put("message", "张三");return "welcome";}}

运行效果

问题所在

把@RestController替换为@Controller注解

@RestController注解表示返回的内容都是HTTP Content不会被模版引擎处理的

下面是RestController的定义

package org.springframework.web.bind.annotation;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import org.springframework.stereotype.Controller;@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Controller@ResponseBodypublic @interface RestController {/*** The value may indicate a suggestion for a logical component name,* to be turned into a Spring bean in case of an autodetected component.* @return the suggested component name, if any (or empty String otherwise)* @since 4.0.1*/String value() default "";

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。