zoukankan      html  css  js  c++  java
  • Spring MVC : Java模板引擎 Thymeleaf (二)

    本文原计划直接介绍Thymeleaf的视图解析,但考虑到学习的方便,决定先构建一个spring-mvc。

    以下的全部过程仅仅要一个记事本和JDK就够了。

    第一步,使用maven构建一个web app。

    <span style="font-size:18px;">mvn archetype:generate -DgroupId=org.nwpu.chen -DartifactId=spring-mvc -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false</span>

    曾经没用过Maven也没关系。下载后配置好环境变量。简单使用还是非常快的。这里分别用參数给出了groupId(组织名),artifactID(项目名),关键是archetypeArtifactId,指出了项目类型是 maven-archetype-webapp,最后指出不启用交互模式(启用批处理模式)。

    完毕后。会自己主动生成文件夹结构。

    <span style="font-size:18px;">└──spring-mvc
       └── src
           └── main
                └── resouces
                └── webapp
        pom.xml</span>

    webapp以下就是我们web应用的部分。


    第二步。改动pom.xml

    随着之后项目的变化,pom还是要改动的。这里先加入编译的插件,和tomcat插件(意味着你不须要安装tomcat)

    <span style="font-size:18px;"><build>
        <finalName>spring-mvc</finalName>
        <plugins>
               <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
              <source>1.7</source>
              <target>1.7</target>
            </configuration>
          </plugin>
                <plugin>
              <groupId>org.apache.tomcat.maven</groupId>
              <artifactId>tomcat7-maven-plugin</artifactId>
              <version>2.2</version>
          </plugin>
        </plugins>
      </build></span>

    就这么简单,不借助IDE(甚至没有事先安装tomcat)。仅仅要记事本就能构建好一个web app。

    执行 mvn clean tomcat7:run,就能够再浏览器打开 http://localhost:8080/spring-mvc/


    第三步。加入spring-mvc的依赖

    開始使用maven開始spring的朋友,可能对究竟该加入 spring-context、spring-core、spring-web、spring-webmvc...混淆不清,事实上非常easy。我们能够在类似 http://mvnrepository.com/的站点上查看我们加入的依赖的直接依赖。当然你也能够使用maven里面的命令查看。

    以spring-webmvc为例,有以下的依赖(当然,依赖有其范围。这里不展开讨论)


    或者。执行 mvn dependency:list,



    说明,此时你仅依赖srping-webmvc是足够的。

    所以,在pom.xml加入,

    <span style="font-size:18px;">      <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-webmvc</artifactId>
    	<version>4.0.6.RELEASE</version>
    </dependency></span>


    第四步。spring-mvc的配置

    这方面最好的教程应该就是 http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html。

    MVC的过程实际就是一个请求流动的过程。在Spring,接受请求的开端就是 DispatcherServlet,可看成一个前端控制器。

    看名字,它就是分派的作用。即把请求分派给合适的控制器。

    接下来就是处理请求,返回视图了。

    所以,在web.xml里面配置DispatcherServlet,


    <span style="font-size:18px;">  <servlet>
      	  <servlet-name>webmvc</servlet-name>
          <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
          </servlet-class>
          <load-on-startup>1</load-on-startup>
      </servlet></span>
    这里的servlet-name非常重要。由于默认情况下,Spring会让DispatcherServlet在载入时从一个基这个名字的xml文件载入上下文。

    本例中,就去载入 webmvc-servlet.xml。

    (既然有默认,肯定能够自己定义。之后的文章会介绍到)

    以下我们匹配该servlet处理的URL,一般推荐直接使用 / 来匹配。

    <span style="font-size:18px;">  <servlet-mapping>
            <servlet-name>webmvc</servlet-name>
            <url-pattern>/</url-pattern>
      </servlet-mapping></span>

    这时,你得考虑一个问题。不能使DispatcherServlet处理静态资源(css,js等)。Spring 3.0.4之后,能够使用<mvc:resources/>解决这一困扰。

    尽管我们如今的Web项目还没有资源。有备无患,在和WEB-INF平行的文件夹下新建一个resources文件夹。

    然后在webapp/WEB-INF下编辑webmvc-servlet.xml。

    <span style="font-size:18px;"><?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: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/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        
        <mvc:resources mapping="/resources/**"
                      location="/resources/" />
    </beans></span>


    mapping的值 /resources/** 表明匹配以/resouces開始的随意子路径,location指出资源实际文件夹。


    上面提到,DispatcherServlet会选择合适的控制器去分派请求,这个过程是控制器映射去完毕的(细节能够去 http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html了解)。这里仅仅使用Spring MVC的注解功能,

    <span style="font-size:18px;"><mvc:annotation-driven /></span>

    一句话就够了。


    第四步。编写控制器

    在和webapp平行的文件夹下,新建java文件夹,

    └── src
        └── main
            └── java
            └── webapp
    包名 package org.webmvc.controller;
    @Controller
    public class HomeController{
    
         @RequestMapping("/home")
         public String showHomePage(Model model){
    
            model.addAttribute("name","spring-mvc");
            return "home";
         }
    
    }

    为实现自己主动检測和装配,我们在配置文件加上:

    <context:component-scan base-package="org.webmvc.controller" />

    以下的重点来了。就是逻辑视图如何和物理视图映射的问题。本例中。home这个字符串如何和一个物理文件发生关联?


    第五步,视图解析

    因为这里讲的是Thymeleaf和Spring的整合,先把thymeleaf-spring4-{version}.jar 放在Build Path以下,或加入以下的依赖:

    (spring4表明是和spring4.0+整合,也有spring3)。


    <dependency>
    	<groupId>org.thymeleaf</groupId>
    	<artifactId>thymeleaf-spring4</artifactId>
    	<version>2.1.2.RELEASE</version>
    </dependency>

    首先。要实例化一个 org.thymeleaf.spring4.SpringTemplateEngine的模板引擎,

    <bean id="templateResolver"
           class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
      <property name="prefix" value="/WEB-INF/templates/" />
      <property name="suffix" value=".html" />
      <property name="templateMode" value="HTML5" />
    </bean>
        
    <bean id="templateEngine"
          class="org.thymeleaf.spring4.SpringTemplateEngine">
      <property name="templateResolver" ref="templateResolver" />
    </bean>

    而典型的JSP + JSTL的视图,一个典型的配置是:

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
      <property name="prefix" value="/WEB-INF/jsps/" />
      <property name="suffix" value=".jsp" />
      <property name="order" value="2" />
      <property name="viewNames" value="*jsp" />
    </bean>

    当中InternalResourceViewResolver是org.springframework.web.servlet.ViewResolver的一个实现,而在Thymeleaf这个工作是由org.thymeleaf.spring4.view.ThymeleafViewResolver完毕,

    <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
      <property name="templateEngine" ref="templateEngine" />
      <property name="order" value="1" />
      <property name="viewNames" value="*.html,*.xhtml" />
    </bean>

    完整的一个配置例如以下,

    <!-- **************************************************************** -->
      <!--  THYMELEAF-SPECIFIC ARTIFACTS                                    -->
      <!--  TemplateResolver <- TemplateEngine <- ViewResolver              -->
      <!-- **************************************************************** -->
    
      <bean id="templateResolver"
            class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".html" />
        <property name="templateMode" value="HTML5" />
      </bean>
        
      <bean id="templateEngine"
            class="org.thymeleaf.spring4.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver" />
      </bean>
       
      <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine" />
      </bean>    
    

    在WEB-INF下新建views文件夹,并新建home.html,内容非常easy:

    <!DOCTYPE HTML>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Spring MVC with thymeleaf</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
        <p th:text="'Hello, ' + ${name} + ' with thymeleaf !'" /> <br/>
        run ok....
    </body>
    </html>

    当中。xmlns:th="http://www.thymeleaf.org"是引入命名空间。也就th标签的使用。


    到此,一个完整的MVC app 创建成功。

    执行 mvn tomcat7:run。在浏览器输入 http://localhost:8080/spring-mvc/home,



  • 相关阅读:
    Jqurey 得到url参数 getUrlParam
    JQUERY获取当前页面的URL信息
    TextView,imageView属性讲解
    滑动解锁
    显示界面跳转,隐式跳转
    代码进行Relativelayout,constraintLayout布局
    代码布局-LinearLayout
    实例xml拖拽详细方法布局
    layout布局
    AS资源了解
  • 原文地址:https://www.cnblogs.com/brucemengbm/p/6872344.html
Copyright © 2011-2022 走看看