欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring mvc整合freemarker基于注解方式

程序员文章站 2024-03-04 21:10:18
基于网络改进为:最正常版本复制代码 代码如下:
基于网络改进为:最正常版本
复制代码 代码如下:

<?xml version="1.0" encoding="utf-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemalocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <!-- 针对freemarker的视图配置 -->
    <bean id="viewresolver"
        class="org.springframework.web.servlet.view.freemarker.freemarkerviewresolver">
        <property name="order" value="5" />
        <property name="suffix" value=".ftl" />
        <property name="contenttype" value="text/html;charset=utf-8" />
    </bean>

     
<bean id="freemarkerconfig"
        class="org.springframework.web.servlet.view.freemarker.freemarkerconfigurer">
        <property name="templateloaderpath" value="/web-inf/view/" />
        <property name="freemarkersettings">
            <props>
                <prop key="template_update_delay">0</prop>
                <prop key="default_encoding">utf-8</prop>
                <prop key="number_format">0.##########</prop>
                <prop key="datetime_format">yyyy-mm-dd hh:mm:ss</prop>
                <prop key="classic_compatible">true</prop>
                <prop key="template_exception_handler">ignore</prop>
            </props>
        </property>
    </bean>

controller建立
复制代码 代码如下:

import javax.servlet.http.httpservletrequest;

import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.servlet.modelandview;

@controller
public class springmvccontroller {

    @requestmapping(value="/welcome",method={requestmethod.get}) 
    public modelandview getfirstpage(httpservletrequest request) {
        //welcom就是视图的名称(welcom.ftl)
        modelandview mv = new modelandview("welcom");
        mv.addobject("name", "my first spring mvc");
        return mv;
    }
}


在url上敲http://localhost:8080/welcome就会到web-inf/view/welcom.ftl页面渲染数据
welcom.ftl页面
复制代码 代码如下:

<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>insert title here</title>
</head>
<body>
hello ${name}
</body>
</html>

页面出来的效果:
hello my first spring mvc