首页 > 代码库 > SpringMVC+Freemarker环境搭建

SpringMVC+Freemarker环境搭建



一:web.xml文件配置

<servlet>
   <servlet-name>springmvc</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-mvn.xml</param-value>
   </init-param>
   <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>/</url-pattern>

</servlet-mapping>

添加编码过滤器

<filter>
        <filter-name>encoding</filter-name>
        <filter-class>
            org.springframework.web.filter.CharacterEncodingFilter
        </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
</filter>
<filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

logback集成到SpringMVC项目中

<context-param> 
        <param-name>logbackConfigLocation</param-name> 
        <param-value>classpath:logback.xml</param-value> 
</context-param> 
<listener> 
        <listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class> 
</listener>


二:spring-mvc.xml文件配置

<context:component-scan base-package="com.ultrapower.bjd.web">

</context:component-scan>

<mvc:default-servlet-handler />

配置freeMarker的模板配置信息

<bean id="freemarkerConfig"
  class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
  <property name="templateLoaderPaths">
       <array>
          <value>/WEB-INF/freemarker/</value>
          <value>/WEB-INF/freemarker/mgr/</value>
          <value>/WEB-INF/freemarker/anls/</value>
       </array>
  </property>
  <property name="freemarkerSettings">
     <props>
        <prop key="incompatible_improvements">2.3.22</prop>
        <prop key="template_exception_handler">rethrow</prop>
        <prop key="default_encoding">UTF-8</prop>
        <prop key="locale">zh_CN</prop>
        <prop key="date_format">yyyy-MM-dd</prop>
        <prop key="time_format">HH:mm:ss</prop>
        <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
        <prop key="number_format">0.################</prop>
     </props>
  </property>
</bean>

配置Freemarker视图解析器

<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
    <property name="prefix" value="" />
    <property name="suffix" value="http://www.mamicode.com/.html" />
    <property name="contentType" value="http://www.mamicode.com/text/html;charset=UTF-8" />
    <property name="order" value="http://www.mamicode.com/0"></property>
    <property name="viewClass"
              value="http://www.mamicode.com/org.springframework.web.servlet.view.freemarker.FreeMarkerView" />
</bean>

配置其他视图解析器(处理JSP类型的试图解析器 处理的视图为:InternalResourceView或者JstlView)

<bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="" />
    <property name="suffix" value="http://www.mamicode.com/.jsp" />
    <property name="contentType" value="http://www.mamicode.com/text/html;charset=UTF-8" />
    <property name="order" value="http://www.mamicode.com/1"></property>
</bean>

配置全局的拦截器

<mvc:interceptors>
  <mvc:interceptor>
     <mvc:mapping path="/**"/>
     <bean class="com.ultrapower.bjd.web.interceptor.UserVilitorInterceptor" />
  </mvc:interceptor>
</mvc:interceptors>


其它(使用FastJson)

<mvc:annotation-driven >
       <mvc:message-converters register-defaults="true">
            <!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
            <bean id="fastJsonHttpMessageConverter"

                        class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <!-- 这里顺序不能反,一定先写text/html,不然ie下出现下载提示 -->
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
                <property name="features">
                    <list>
                        <value>WriteMapNullValue</value>
                        <value>QuoteFieldNames</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
</mvc:annotation-driven>


三:使用

@Controller
@RequestMapping(path="/demo")
public class DemoController {
 
 @RequestMapping(path="/getReportData.action")
 public ModelAndView getReportData(
       String objectType,
       @RequestParam(required=false)String dimension,
       @RequestParam(value="http://www.mamicode.com/interval",required=false) Integer interval,
       @RequestParam(defaultValue="http://www.mamicode.com/false")boolean isDownload,
       ModelMap modelMap,
       HttpSession session) {
    if(isDownload){
       modelMap.put("value", null);
       modelMap.put("headers", null);
       return new ModelAndView(new ExcelXlsView(),modelMap) ;
    }else{
       modelMap.put("value", null);
       return new ModelAndView(new FastJsonJsonView(),modelMap) ;
    }
  }


@RequestMapping(value = http://www.mamicode.com/{"**/{page}.html", "**/{page}.xhtml"})
 public ModelAndView showPage(HttpServletRequest request,
   HttpServletResponse response,
   HttpSession session,
   @PathVariable("page") String page,
   ModelMap modelMap,
   RedirectAttributes attr) throws Exception {
  
      return new ModelAndView("redirect:" + "/404.jsp");
  }


@ResponseBody
@RequestMapping(path="/getData.action")
 public List<String> getData(String objectType) {
       return new ArrayList<String>() ;
  }
}



public class ExcelXlsView extends AbstractXlsView{

 

     @Override
     protected void buildExcelDocument(Map<String, Object> model, Workbook workbook,

          HttpServletRequest request,
          HttpServletResponse response) throws Exception {

              response.setContentType("application/vnd.ms-excel;charset=utf-8");
              response.setHeader("Content-Disposition", "attachment;filename="

                           + URLEncoder.encode(fileName, "UTF-8") + ".xls");
               //TODO       

      }

}

参考:
AbstractXlsView
AbstractXlsxView
AbstractPdfView
AbstractXlsxStreamingView



部分Maven配置

<properties>
  <spring.version>4.2.4.RELEASE</spring.version>
  <drools.version>6.4.0.Final</drools.version>

</properties>
<dependencies>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-beans</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context-support</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-tx</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-aop</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-expression</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.8</version>
  </dependency>
  <dependency>
   <groupId>org.freemarker</groupId>
   <artifactId>freemarker</artifactId>
   <version>2.3.23</version>
  </dependency>
  <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-core</artifactId>
      <version>1.1.7</version>
  </dependency>
  <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <version>1.1.7</version>
  </dependency>
  <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>1.7.21</version>
  </dependency>
  <dependency>
      <groupId>org.logback-extensions</groupId>
      <artifactId>logback-ext-spring</artifactId>
      <version>0.1.1</version>
  </dependency>

</dependencies>

<build>
    <finalName>guest</finalName>
    <resources>
          <resource>
           <directory>src/main/resources</directory>
           <includes>
              <include>**/*.properties</include>
              <include>**/*.xml</include>
              <include>**/*.conf</include>
              <include>**/*.drl</include>
           </includes>
          <filtering>false</filtering>
    </resource>
    <resource>
         <directory>src/main/java</directory>
         <includes>
             <include>**/*</include>
         </includes>
         <filtering>false</filtering>
   </resource>
 </resources>
    <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.5</version>
    <configuration>
     <source>1.7</source>
     <target>1.7</target>
     <encoding>UTF-8</encoding>
    </configuration>
   </plugin>
  </plugins>
  <pluginManagement>
       <plugins>
         <plugin>
           <groupId>org.apache.tomcat.maven</groupId>
           <artifactId>tomcat6-maven-plugin</artifactId>
           <version>2.2</version>
           <configuration>
            <server>tomcat6</server>
            <path>/guest</path>
            <charset>UTF-8</charset>
            <uriEncoding>UTF-8</uriEncoding>
           </configuration>
         </plugin>
         <plugin>
           <groupId>org.apache.tomcat.maven</groupId>
           <artifactId>tomcat7-maven-plugin</artifactId>
           <version>2.2</version>
           <configuration>
            <server>tomcat7</server>
            <path>/guest</path>
            <charset>UTF-8</charset>
            <uriEncoding>UTF-8</uriEncoding>
           </configuration>
         </plugin>
       </plugins>
  </pluginManagement>
  </build>


本文出自 “因简单而自在” 博客,请务必保留此出处http://dengshuangfu.blog.51cto.com/8794650/1908370

SpringMVC+Freemarker环境搭建