springmvc整合 sitemesh + freemarker+spring ioc
  auAXpmIH76WN 2023年11月02日 59 0


[color=red]使用freemarker.properties配置方式[/color]: [url]http://www.bug315.com/article/176.htm[/url]
freemarker.properties

tag_syntax=auto_detect
template_update_delay=2
default_encoding=UTF-8
output_encoding=UTF-8
locale=zh_CN
date_format=yyyy-MM-dd
time_format=HH:mm:ss
datetime_format=yyyy-MM-dd HH:mm:ss


<!-- 设置freeMarker的配置文件路径 -->
    <bean id="freemarkerConfiguration" 
        class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="location" value="classpath:freemarker.properties"/>
    </bean>

    <!-- 配置freeMarker的模板路径 -->
    <bean id="freemarkerConfig" 
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <!--property name="freemarkerSettings" ref="freemarkerConfiguration"/-->  <!-- 这里使用配置文件 -->
        <property name="templateLoaderPath">
            <value>/WEB-INF/ftl/</value>
        </property>
        <property name="freemarkerVariables">
            <map>
                <entry key="xml_escape" value-ref="fmXmlEscape" />
            </map>
        </property>
    </bean>




[b][color=red]赋值和使用方式: [/color][/b]


[color=blue]1. 使用Model model或者ModelMap map[/color]


public String list(Model model, ModelMap map) {
        Collection<Session> sessions =  sessionDAO.getActiveSessions();
        model.addAttribute("sessions", sessions);
        model.addAttribute("sesessionCount", sessions.size());

        map.put("sessions1", sessions);
        map.put("sesessionCount1", sessions.size());

        map.addAttribute("sessions2", sessions);
        map.addAttribute("sesessionCount2", sessions.size());
        return "views/online.ftl";
    }


<h1> 在线用户后台管理, 在线个数: ${sesessionCount},${sesessionCount1},${sesessionCount2},
            <#if sesessionCount = 1>
                sesessionCount is 1;
            </#if>
            <#if sesessionCount1 = 1>
                sesessionCount1 is 1;
            </#if>
            <#if sesessionCount2 = 1>
                sesessionCount2 is 1;
            </#if>
            </h1>


[color=blue]2. 使用Map<String,Object>方式[/color]


public String list(Model model, Map<String,Object> map) {
        Collection<Session> sessions =  sessionDAO.getActiveSessions();
        model.addAttribute("sessions", sessions);
        model.addAttribute("sesessionCount", sessions.size());

        map.put("sessions1", sessions);
        map.put("sesessionCount1", sessions.size());
        return "views/online.ftl";
    }


<h1> 在线用户后台管理, 在线个数: ${sesessionCount},${sesessionCount1}
            <#if sesessionCount = 1>
                sesessionCount is 1;
            </#if>
            <#if sesessionCount1 = 1>
                sesessionCount1 is 1;
            </#if>
            </h1>






spring mvc版本 4.1.5


sitemesh版本 3.0.0


freemarker-2.3.22


spring ioc 4.1.5



唯一需要更改iade地方 以前返回时不加后缀,现在返回时请加入后缀,必须你想使用jsp文件就返回 模板名称.jsp,


使用freemarker模板就返回 模板.ftl ,注意在springmvc里面2个试图解析器都不能定义后缀,否则只会调用jsp解析器


标签: Spring SiteMesh FreeMarker


代码片段(5) [全屏查看所有代码]


1. [文件] web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">

    <display-name>springmvc</display-name>
    <description>springmvc</description>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:beans.xml
        </param-value>
    </context-param>
    <!-- spring 整合索赔日内个mvc的时候是否需要写ContextLoaderListener -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--配置 HiddenHttpMethodFilter请可以把post请求转为delete请求或者post请求改成put -->
    <filter>
        <filter-name>hiddenHttpMethodfilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>hiddenHttpMethodfilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- sitemesh 配置 -->
    <filter>
        <filter-name>sitemesh</filter-name>
        <filter-class>com.sniper.springmvc.sitemesh3.MySiteMeshFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- springmvc 配置 -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!-- 加载时创建 -->
        <load-on-startup>1</load-on-startup>
    </servlet>


    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>




</web-app>


2. [文件] beans.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 如果 sprinmvc 和 spring ioc 扫描的包有重合就会把类初始化2次 context:component-scan -->
    <!-- beans可以引用springmvc的类,但是springmvc不能引用spring的类 -->
    <!-- Springmvc 的ioc容器中的bean可以引用spring 的ioc容器的bean,反之不可以 -->
    <context:component-scan base-package="com.sniper.springmvc">
        <!-- 不扫描的带有这些注解的类 -->
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
        <context:exclude-filter type="annotation"
            expression="org.springframework.web.bind.annotation.ControllerAdvice" />


    </context:component-scan>

    <!-- 配置数据源,其他框架 -->

</beans>


3. [文件] springmvc.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!--需要进行 spring整合springmvc么 还是需要加入spring的ioc容器 是否需要在web.xml中配置springioc容器的ContextLoaderListener 
        1.需要:通常情况下,类似于数据源,事务,整合其他框架都是放在spring配置文件中(而不是放在springmv里面) 2.不需要都放在springmvc的配置文件中,也可以分多个Spring 
        的配置文件然后import 节点导入其他的配置文件 实际上 -->
    <context:component-scan base-package="com.sniper.springmvc" />
    <!-- 静态文件映射 -->
    <!-- <mvc:resources location="/myfiles" mapping="myfiles"></mvc> -->
    <!-- 配置 freemarker解析器 -->
    <!-- http://www.osblog.net/wangxp/140.html -->
    <bean
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />
        <property name="suffix" value="" />
        <property name="viewNames" value="*.ftl" />
        <property name="prefix" value="" />
        <property name="cache" value="false" />
        <property name="contentType" value="text/html;charset=UTF-8" />
        <!-- <property name="exposeRequestAttributes" value="true" /> <property 
            name="exposeSessionAttributes" value="true" /> <property name="requestContextAttribute" 
            value="base" /> -->
        <property name="order" value="200" />
    </bean>

    <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"></bean>

    <bean id="freemarkerConfig"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/WEB-INF/mvc/" />
        <property name="defaultEncoding" value="UTF-8" />
        <property name="freemarkerVariables">
            <map>
                <entry key="xml_escape" value-ref="fmXmlEscape" />
            </map>
        </property>
        <property name="freemarkerSettings">
            <props>
                <prop key="tag_syntax">auto_detect</prop>
                <prop key="template_update_delay">5</prop>
                <prop key="defaultEncoding">UTF-8</prop>
                <prop key="url_escaping_charset">UTF-8</prop>
                <prop key="locale">zh_CN</prop>
                <prop key="boolean_format">true,false</prop>
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                <prop key="date_format">yyyy-MM-dd</prop>
                <prop key="time_format">HH:mm:ss</prop>
                <prop key="number_format">0.######</prop>
                <prop key="whitespace_stripping">true</prop>
                <!--空值处理<prop key="classic_compatible">true</prop> -->
                <!-- <prop key="auto_import">/ftl/tags/index.ftl as p,/ftl/spring.ftl 
                    as s</prop> -->
            </props>
        </property>

    </bean>

    <!-- 配置试图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/mvc/" />
        <!-- 下面2个都不允许设置 -->
        <!-- <property name="suffix" value="" /> -->
        <!-- <property name="order" value="0" /> -->
    </bean>

    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="cookieName" value="clientlanguage" />
        <property name="cookieMaxAge" value="-1" />
    </bean>

    <!-- id 必须是 messageSource否则出错 -->
    <!-- 使用jstl 资源国际化的设置 -->
    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="i18n" />
    </bean>

    <!--配置试图 beanNameViewResolver解析器 ,使用试图的名字来解析试图 -->
    <!-- 通过order来设置 试图解析器的优先级,只要配置都会被默认的小 -->
    <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
        <property name="order" value="100" />
    </bean>

    <!-- 配置直接转发的页面 -->
    <!-- 直接响应转发的页面不经过handler的方法 ,如果不加上下面的配置以前的 url都会失效 -->
    <mvc:view-controller path="/success" view-name="success" />

    <!-- 取消对静态资源的解释,这样可以直接访问静态资源,这里判断访问资源是否被映射过 -->
    <!-- 这样不会出现找不到匹配资源的情况 -->
    <mvc:default-servlet-handler />

    <!-- 下面是我学习是写的可以把你们没有的删除即可 -->

    <!-- 在实际开发中都通常需要配置 mvc:annotion-driven 标签 -->
    <!-- 加上这个配置就不会除了mvc之外的url都不能使用 -->
    <!-- 作用有很多会住测三个bean 支持实例对表单参数类型转换 支持很多类型注解数据类型的格式化 --><!-- -->
    <!-- <mvc:annotation-driven></mvc:annotation-driven> -->
    <!-- 下面的写法可以使用自定义转换器,自定义类型转换器和系统类型转换器一起使用 -->
    <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
    <!-- 配置 conversionService -->
    <!-- org.springframework.context.support.ConversionServiceFactoryBean -->
    <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <!-- 使用 @Component注册 用spring扫描 -->
                <ref bean="userConverter" />
            </set>
        </property>
    </bean>
    <!-- 验证 -->
    <bean id="validationFactoryBean"
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    </bean>

    <!-- 配置 SessionLocaleResolver -->
    <bean id="localResolver"
        class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
    <!-- 下面的拦截器可以指定url开始的 -->
    <!-- 配置链接修改语言环境的 拦截器 org.springframework.web.servlet.i18n.LocaleChangeInterceptor -->
    <mvc:interceptors>
        <!-- 配置自定义拦截器 -->
        <bean class="com.sniper.springmvc.interceptions.FristInterceptor"></bean>
        <!-- 链接改变语言环境的session拦截器 -->
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
        <mvc:interceptor>
            <!-- 拦截器管用的路径 -->
            <mvc:mapping path="/springmvc" />
            <!-- 那个拦截器使用此条规则 -->
            <bean class="com.sniper.springmvc.interceptions.SecondInterceptor"></bean>
            <!-- 拦截器不管用的路径 -->
            <!-- <mvc:exclude-mapping path="/abc"/> -->
        </mvc:interceptor>
    </mvc:interceptors>
    <!-- 上传文件配置 -->
    <bean
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="maxUploadSize" value="10000"></property>
    </bean>

    <!-- 配置错误处理页面 -->
    <!-- 通过 SimpleMappingExceptionResolver处理错误页面 -->

    <bean
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <!-- 更改试图中exception的名称 -->
        <!-- <property name="exceptionAttribute" value="ex"></property> <property 
            name="exceptionMappings"> <props> <prop key="java.lang.ArrayIndexOutOfRoundsException"></prop> 
            </props> </property> -->

        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.Throwable">500</prop>
            </props>
        </property>
        <property name="warnLogCategory" value="WARN"></property>
        <property name="defaultErrorView" value="500"></property>
        <property name="defaultStatusCode" value="500"></property>
        <property name="statusCodes">
            <props>
                <prop key="404">404</prop>
                <prop key="500">500</prop>
            </props>
        </property>

    </bean>



</beans>


4. [文件] MySiteMeshFilter.java


package com.sniper.springmvc.sitemesh3;

import org.sitemesh.builder.SiteMeshFilterBuilder;
import org.sitemesh.config.ConfigurableSiteMeshFilter;

public class MySiteMeshFilter extends ConfigurableSiteMeshFilter {

    @Override
    protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {

        builder.addDecoratorPath("/springmvc**", "/WEB-INF/mvc/main.jsp")
                .addExcludedPath("/springmvc/login**")
                .addExcludedPath("/springmvc/admin-print**")
                .addExcludedPath("/springmvc/file-upload**")
                .addDecoratorPath("/**", "/WEB-INF/mvc/main.jsp")
                .addExcludedPath("/myfiles/**");

    }

}


5. [文件] Index.java


package com.sniper.springmvc;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sniper.springmvc.util.SearchUtil;

@RequestMapping("/")
@Controller
public class Index {

    private final static String SUCCESS = "success";
    private final static String INDEX = "index";

    @RequestMapping("/")
    public String index(Map<String, Object> map) {
        map.put("freemarker", "freemarker");
        map.put("integers", 123456);
        return "index.jsp";
    }

    @RequestMapping("search")
    public String search(SearchUtil searchUtil, Map<String, Object> map) {
        map.put("searchUtil", searchUtil);
        System.out.println(searchUtil);
        return "search";
    }

    @RequestMapping("ftl")
    public String ftl(Map<String, Object> map) {

        // 获取模板路径跳转
        map.put("freemarker", "freemarker");
        return "ftl.ftl";
    }
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  M5nxXzKbD3Q7   2023年11月12日   24   0   0 xmlmavenjar
  ehrZuhofWJiC   2024年04月26日   39   0   0 日志Java
auAXpmIH76WN