zoukankan      html  css  js  c++  java
  • spring-webmvc 4.3.4 与 freemarker、easyui 整合

    一、所需lib包

    二、web.xml配置

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        id="WebApp_ID" version="2.5">
        
        <filter>
            <filter-name>characterEncodingFilter</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>
        </filter>
        <filter-mapping>
            <filter-name>characterEncodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
          </filter-mapping>
        
        <!-- 配置DispatchcerServlet -->
        <servlet>
            <servlet-name>springDispatcherServlet</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!-- 配置Spring mvc下的配置文件的位置和名称 -->
            <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>

    三、src/springmvc.xml 配置

    <?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:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
          http://www.springframework.org/schema/context 
          http://www.springframework.org/schema/context/spring-context-4.0.xsd 
          http://www.springframework.org/schema/mvc 
          http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
            
            
            <!-- 配置自动扫描的包 -->
            <context:component-scan base-package="com.lixj"></context:component-scan>
            <!-- 配置以下内容以支持静态资源访问 -->
            <mvc:default-servlet-handler/>
            <mvc:annotation-driven>
              <mvc:message-converters>
                 <!-- 避免返回JSON出现下载文件 -->
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                  <property name="supportedMediaTypes">
                   <list>
                      <value>text/html;charset=UTF-8</value>
                   </list>
                  </property>
                </bean>
              </mvc:message-converters>
            </mvc:annotation-driven>
             
            <!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 
            <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                <property name = "prefix" value="/views/"></property>
                <property name = "suffix" value = ".jsp"></property>
            </bean>
            -->
            <!-- 设置freeMarker的配置文件路径 -->  
            <bean id="freemarkerConfiguration" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
                <property name="location" value="classpath:freemarker.properties"/>  
            </bean>
        
            <!-- 配置freeMarker的模板路径 -->  
            <bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
                <property name="freemarkerSettings" ref="freemarkerConfiguration"/>  
                <property name="templateLoaderPath">  
                    <value>/ftl/</value>  
                </property>  
                <property name="freemarkerVariables">
                    <map>
                        <entry key="xml_escape" value-ref="fmXmlEscape" />
                    </map>
                </property>
            </bean>
          
            <!-- 配置freeMarker视图解析器 -->  
            <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">  
                <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>  
                <property name="contentType" value="text/html; charset=utf-8"/>  
                <property name="cache" value="false"/>
                <property name = "suffix" value = ".ftl"></property>
                <property name="exposeRequestAttributes" value="true" />
                <property name="exposeSessionAttributes" value="true" />
                <property name="exposeSpringMacroHelpers" value="true" />
            </bean>
            
            <bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape" />
            
            <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
              <property name="maxUploadSize" value="1046666000"/>
              <property name="maxInMemorySize" value="4096" />
              <property name="defaultEncoding" value="UTF-8"></property>
            </bean>
            
    </beans>

    四、src/freemarker.properties 配置

    #设置标签类型:square_bracket:[]     auto_detect:[]<>    
    tag_syntax=auto_detect
    #模版缓存时间,单位:秒
    template_update_delay=0
    default_encoding=UTF-8
    output_encoding=UTF-8
    locale=zh_CN
    #设置数字格式 ,防止出现 000.00    
    number_format=#
    #变量为空时,不会报错 
    classic_compatible=true
    #这个表示每个freemarker的视图页面都会自动引入这个ftl文件。里面定议的就是一些宏,如text文本框,各种form元素   
    #auto_import="/WEB-INF/templates/index.ftl" as do 

    五、FreemarkerController.java 代码

    package com.lixj;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    import org.springframework.web.multipart.MultipartFile;
    
    @Controller
    public class FreemarkerController {
        
         @RequestMapping("/hi")
         public String sayHello(ModelMap map){
             System.out.println("say hi....");
             map.put("name","kimi");
             map.put("name2","李");
             return "hi";
         }
         
        @RequestMapping(value = "/hi/{id}/{name}")
        public String helloPathVar(@PathVariable(value = "id") Integer id,
                @PathVariable(value = "name") String name, ModelMap map) {
            System.out.println("PathVariable  id=" + id + "   name=" + name);
            map.put("id",id);
            map.put("name",name);
            return "hi";
        }
        
        @RequestMapping(value = "/testPojo") //, method = RequestMethod.POST
        public String testPojo(@RequestParam(value = "flag", required = false, defaultValue = "yes") String flag,
                User user, ModelMap map) {
            System.out.println("flag: " + flag);
            System.out.println("testPojo: " + user.toString());
            map.put("name", user.getUsername());
            return "hi";
        }
        
        @RequestMapping(value="/json")
        @ResponseBody
        public Object getJson(){
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            List list = new ArrayList();
            Map<String, Object> map1 = new HashMap<String, Object>();
            map1.put("text", "LIXJ");
            map1.put("id", "123");
            list.add(map1);
            
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("text", "测试");
            map2.put("id", "222");
            list.add(map2);
            return list;
        }
        
        @RequestMapping("/fileUpload")
        public String fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
            if (!file.isEmpty()) {
                     try {
                        String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"
                           + file.getOriginalFilename();
                         file.transferTo(new File(filePath));
                    } catch (IllegalStateException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
            }
            return "redirect:/index.jsp";
        }
    }

    六、index.jsp代码

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'index.jsp' starting page</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta name="content-type" content="text/html; charset=UTF-8">
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
        <link rel="stylesheet" type="text/css" href="/easyui/themes/default/easyui.css">
        <link rel="stylesheet" type="text/css" href="/easyui/themes/icon.css">
        <script type="text/javascript" src="/easyui/jquery.min.js"></script>
        <script type="text/javascript" src="/easyui/jquery.easyui.min.js"></script>
        
      </head>
      
      <body>
    
    <form action="/fileUpload" method="post" accept-charset="utf-8" enctype="multipart/form-data">
         <input type="file" name="file" >
         <input type="hidden" name="flag" value="update"><br>
        username: <input type="text" name="username"><br>
    
        password: <input type="password" name="password"><br>
    
        email: <input type="text" name="email"><br>
    
        age: <input type="text" name="age"><br>
    
        city: <input type="text" name="address.city"><br>
    
        province: <input type="text" name="address.province"><br>
    
        <input type="submit" value="submit">
    
    </form><br/><br/>
    <div style="margin-bottom:20px">
         <input id="language" class="easyui-combobox" name="language" style="120px" data-options="
                        url:'/json',
                        method:'get',
                        valueField: 'id',
                        textField: 'text',
                        label: 'Language:',
                        labelPosition: 'top'
                        " />
    </div>
    
      </body>
    </html>

    七、webRoot/ftl/hi.ftl  代码:
    <html>
    <body>
        <h1>id=${id} : name=${name}  name2=${name2}</h1><br/>
    </body>
    </html>

    八、页面访问地址  http://localhost:90/hi/1/33

  • 相关阅读:
    php中防止SQL注入的方法
    谈谈asp,php,jsp的优缺点
    SSH原理与运用(一):远程登录
    优化MYSQL数据库的方法
    json_encode和json_decode区别
    静态方法与非静态方法的区别
    Java 异常的Exception e中的egetMessage()和toString()方法的区别
    $GLOBALS['HTTP_RAW_POST_DATA'] 和$_POST的区别
    HTML5开发,背后的事情你知道吗?
    使用C语言来实现模块化
  • 原文地址:https://www.cnblogs.com/101key/p/6160645.html
Copyright © 2011-2022 走看看