SpringMVC+FreeMarker

 前言:

   最近在学习SpringMVC,模板引擎用的是FreeMarker,之前没有接触过。利用SpringMVC开发其实还有许多的步骤,比如控制层,服务层,持久化层,实体等等,先弄了一个小demo来总结一下SpringMVC的开发流程。

一、web.xml

xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <servlet>
    
    <servlet-name>springmvcservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
       <param-name>contextConfigLocationparam-name>
       <param-value>/WEB-INF/spring-mvc.xml,classpath*:/applicationContext.xmlparam-value>
     init-param>
      
      <load-on-startup>1load-on-startup>
  servlet>
  
  <servlet-mapping>
    <servlet-name>springmvcservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jspwelcome-file>
  welcome-file-list>
web-app>

二、spring-mvc.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/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    
    <context:component-scan base-package="uap.web,uap.iweb" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    context:component-scan>
    
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8" />
            bean>
            
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="prettyPrint" value="true"/>
            bean>            
          mvc:message-converters>
    mvc:annotation-driven>
    
      
    <bean id="freemarkerConfigurer"  
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">  
        <property name="templateLoaderPath" value="/WEB-INF/views/" />  
        <property name="defaultEncoding" value="UTF-8" />  
        <property name="freemarkerSettings">  
            <props>  
                <prop key="template_update_delay">10prop>  
                <prop key="locale">zh_CNprop>  
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ssprop>  
                <prop key="date_format">yyyy-MM-ddprop>
            props>  
        property>  
        <property name="freemarkerVariables">
              <map>  
                <entry key="ctx" value="/web_example" />                
            map>            
        property>
    bean>      
    
      
    <bean id="viewResolver"  
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">  
        <property name="viewClass"  
            value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />  
        <property name="suffix" value=".ftl" />  
        <property name="contentType" value="text/html;charset=UTF-8" />  
        <property name="exposeRequestAttributes" value="true" />  
        <property name="exposeSessionAttributes" value="true" />  
        <property name="exposeSpringMacroHelpers" value="true" />  
        <property name="requestContextAttribute" value="request" />
    bean>  
    
     
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    bean>    
            
        
    <mvc:default-servlet-handler/>
beans>

三、Controler类

@Controller
@RequestMapping("/home")
public class FreeMarkerController {

    @RequestMapping("/getUser")
    public ModelAndView Add(HttpServletRequest request, HttpServletResponse response) {

        User user = new User();
        user.setUsername("hjzgg");
        user.setPassword("5211314");
        List users = new ArrayList();
        users.add(user);
        return new ModelAndView("index", "users", users);
    }

}

四、实体类

public class User {

    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

五、ftl模板(index.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=UTF-8">
<title>yonyoutitle>
head>
<body>
  <#list users as user>
    username : ${user.username}<br/>
    password : ${user.password}
  #list>
body>
html>

 

六、访问路径

  http://localhost:port/项目名称/home/getUser

七、流程说明

  摘自:http://jinnianshilongnian.iteye.com/blog/1594806

SpringMVC+FreeMarker_第1张图片

1、  首先用户发送请求——>DispatcherServlet,前端控制器收到请求后自己不进行处理,而是委托给其他的解析器进行处理,作为统一访问点,进行全局的流程控制;

2、  DispatcherServlet——>HandlerMapping, HandlerMapping将会把请求映射为HandlerExecutionChain对象(包含一个Handler处理器(页面控制器)对象、多个HandlerInterceptor拦截器)对象,通过这种策略模式,很容易添加新的映射策略;

3、  DispatcherServlet——>HandlerAdapter,HandlerAdapter将会把处理器包装为适配器,从而支持多种类型的处理器,即适配器设计模式的应用,从而很容易支持很多类型的处理器;

4、  HandlerAdapter——>处理器功能处理方法的调用,HandlerAdapter将会根据适配的结果调用真正的处理器的功能处理方法,完成功能处理;并返回一个ModelAndView对象(包含模型数据、逻辑视图名);

5、  ModelAndView的逻辑视图名——> ViewResolver, ViewResolver将把逻辑视图名解析为具体的View,通过这种策略模式,很容易更换其他视图技术;

6、  View——>渲染,View会根据传进来的Model模型数据进行渲染,此处的Model实际是一个Map数据结构,因此很容易支持其他视图技术;渲染的过程用到了相应的视图解析器,关于视图解析器的优先级的配置(http://www.cnblogs.com/rollenholt/archive/2012/12/27/2836035.html)。本例中,得到的默认视图解析器是FreeMarker的视图解析器,然后根据ModelAndView中的viewName或者Controler的返回值(对应ftl模板的名字)到FreeMarkerConfigurer配置的templateLoaderPath目录下寻找对应的模板文件,然后进行渲染。

7、返回控制权给DispatcherServlet,由DispatcherServlet返回响应给用户,到此一个流程结束。

  注:如果想要更清楚SpringMVC的流程,就要看一下DispatcherServlet的源码。

 

  学习中遇到的问题:http://www.cnblogs.com/hujunzheng/p/5293050.html

你可能感兴趣的:(SpringMVC+FreeMarker)