Spring Boot☞ 使用freemarker模板引擎渲染web视图

本文通过具体的示例代码展示了如何使用 Spring MVC 框架进行简单的 Web 开发,包括使用 Thymeleaf 和 FreeMarker 作为视图层的实现。

效果图

 

 

 

代码

package com.wls.integrateplugs.hello.controller;

/**
 * Created by wls on 2017/8/24.
 */
import java.util.Locale;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import com.sun.org.apache.regexp.internal.RE;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

@RestController
public class HelloController {

    @RequestMapping(value = "/hello",method = RequestMethod.GET)
    public String hello(Locale locale, Model model) {
        return "hello world";
    }

    @RequestMapping("/helloWorld")
    public String index() {
        return "Hello World";
    }


    /**
     * 使用@RestController时,则使用ModelAndView显示页面
     * @param map
     * @return
     */
    @ApiIgnore
    @RequestMapping(value = "/helloThymeleaf",method = RequestMethod.GET)
    public ModelAndView indexThymeleaf(ModelMap map) {
        ModelAndView mv = new ModelAndView("indexThymeleaf");
        map.addAttribute("name","王老师");
        map.addAttribute("host", "http://blog.didispace.com");
        return mv;
    }

    @RequestMapping(value = "/helloFreeMarker",method = RequestMethod.GET)
    public ModelAndView indexFreeMarker(ModelMap map) {
        ModelAndView mv = new ModelAndView("indexFreeMarker");
        map.addAttribute("name","王老师");
        map.addAttribute("host", "http://blog.didispace.com");
        return mv;
    }

    /**
     * 共享session
     * @param session
     * @return
     */
    @RequestMapping(value = "/uid",method = RequestMethod.GET)
    String uid(HttpSession session) {
        UUID uid = (UUID) session.getAttribute("uid");
        if (uid == null) {
            uid = UUID.randomUUID();
        }
        session.setAttribute("uid", uid);
        return session.getId();
    }

}

  indexFreeMarker.ftl

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
FreeMarker模板引擎
<h1>${host}</h1>
</body>
</html>

  

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

  

转载于:https://www.cnblogs.com/wlsblog/p/7487707.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值