`

Spring+thymeleaf小示例

阅读更多
之前一篇文章写了个简单的Spring mvc例子,界面表示层用的是jsp,本篇文章结合thymeleaf将表示层改成html。和用jsp不一样的地方会加特殊说明。
同样本示例也是在内网环境下,没有采用maven,直接将jar包放在工程里面。
一、配置web.xml(和采用jsp作为表示层没有任何改动),主要作用
1.定义了一个servlet拦截器,以及Mapping规则
2.引入spring-context配置文件
3.添加log4j配置文件
具体文件:
<?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"
	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>SpringTest</display-name>
	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
		<async-supported>true</async-supported>
	</servlet>

    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/resources/log4j/log4j.properties</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- Disables Servlet Container welcome file handling. Needed for compatibility 
		with Servlet 3.0 and Tomcat 7.0 -->
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
</web-app>


二、DispatcherServlet Context配置文件,作用
1.激活注解配置功能
2.配置资源文件路径
3.配置视图层技术
4.引入具体组件配置文档
具体文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing 
		infrastructure -->

	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven>

	</annotation-driven>

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
		up static resources in the ${webappRoot}/resources/ directory -->
	<resources mapping="/resources/**" location="/resources/" />
	
	<beans:bean id="templateResolver"
		class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".html" />
		<!-- Template cache is true by default. Set to false if you want -->
		<!-- templates to be automatically updated when modified. -->
		<beans:property name="cacheable" value="false" />
	</beans:bean>
	<!-- SpringTemplateEngine automatically applies SpringStandardDialect and -->
	<!-- enables Spring's own MessageSource message resolution mechanisms. -->
	<beans:bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
		<beans:property name="templateResolver" ref="templateResolver" />
	</beans:bean>
	
	<beans:bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
        <beans:property name="templateEngine" ref="templateEngine" />
    </beans:bean>
	
	<!-- Imports user-defined @Controller beans that process client requests -->
	<beans:import resource="controllers.xml" />

</beans:beans>



相比较于利用jsp作为视图,利用html主要是引入thymeleaf对应的模版渲染类。

三、组件配置文档,主要作用
1.配置默认页面路径
2.配置组件扫描路径
具体文件
<?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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- Maps '/' requests to the 'home' view -->
    <mvc:view-controller path="/" view-name="views/hello.html"/>
    
    <context:component-scan base-package="test.spring.mvc"/>
     
</beans>


四、controller代码
//**
 * 
 */
package test.spring.mvc;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/mvc")
public class MCVController {
	private static final Log logger = LogFactory.getLog(MCVController.class);
	@RequestMapping("/hello")
	public String hello(){
		logger.info("start to maping request hell");
        return "hello";
    }
	
	@RequestMapping(value = "/test",method =RequestMethod.GET) 
	public @ResponseBody String test(){
        return "abc";
    }
	
	@RequestMapping(value = "/test2",method =RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	public @ResponseBody  AbcTest test2(){
		AbcTest test = new AbcTest();
		test.setAge("20");
		test.setName("me");
        return test;
    }
}




html代码:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>html</title>
  </head>
  
  <body>
   <div style = "width: 200px;height: 100px;color: red">hello</div>
   <button id='buttontest' style = "width: 50px;height: 50px;color: blue"></button>
   <div>
        <label>test:</label>
         <span id="test"></span>
   </div>
   <div>
        <label>test2:</label>
        <span id="test2"></span>
   </div>
  </body>
<script type="text/javascript" th:src="@{/resources/js/jquery-2.0.3.js}"></script>
<script type="text/javascript">
$('#buttontest').click(function() {
    $.ajax({
        type: "GET",
        url: "test",
        /* headers:{
            Accept: "text/plain"
        }, */
        success: function(msg){
          console.log( "Data Saved: " + msg );
          $("#test").text(msg);
        },
        error:function(e){
            alert(e)
        }
     });
 
 $.ajax({
        type: "GET",
        url: "test2",
        success: function(msg){
          console.log( "Data Saved: " + msg );
          $("#test2").text("age:"+msg.age+",name"+msg.name);
        },
        error:function(e){
            alert(e)
        }
     });
})

</script>
</html>




最终的工程目录:


通过和前一遍用jsp作为视图层做比较,可以发现,采用html作为视图层,只是增加了上图中红框内的几个依赖的jar,然后修改下配置文件Servlet-context.xml中的视图模版,代码完全不用做改变,所以采用spring mvc可以方便的在不同的视图层技术间转换。


工程的具体代码请参考附件
  • 大小: 125.2 KB
分享到:
评论

相关推荐

    全注解 spring boot +spring security + mybatis+druid+thymeleaf+mysql+bootstrap

    标题中的"全注解 spring boot +spring security + mybatis+druid+thymeleaf+mysql+bootstrap"是一个集成开发环境的配置,涉及到的主要技术有Spring Boot、Spring Security、MyBatis、Druid、Thymeleaf、MySQL以及...

    spring+springmvc+hibernate+thymeleaf 练习demo项目源码

    本项目"spring+springmvc+hibernate+thymeleaf 练习demo"是一个整合了这四个框架的实践示例,旨在帮助学习者理解它们如何协同工作。下面我们将深入探讨这些技术及其在项目中的应用。 1. Spring框架: - **依赖注入...

    Spring+Spring Boot+JPA+Thymeleaf+Bootstrap+Mysql实现的一个单表crud

    这个应用的核心技术包括Spring、Spring Boot、JPA(Java Persistence API)、Thymeleaf模板引擎、Bootstrap前端框架以及Mysql数据库。下面将详细解释这些技术及其在项目中的作用。 **Spring** 是一个开源的应用程序...

    springboot框架+thymeleaf模板引擎+layui前端框架+数据库

    而"springboot-upload"可能是一个与SpringBoot上传功能相关的模块或示例代码,展示了如何在SpringBoot应用中处理文件上传。 综上所述,这个开源项目利用SpringBoot的便利性,结合Thymeleaf的模板渲染,Layui的前端...

    springboot+mybatis+redis+thymeleaf学习整合web项目demo源码

    这是一个基于Spring Boot、MyBatis、Redis和Thymeleaf技术栈构建的Web项目示例。这个源码库提供了一个全面的学习平台,帮助开发者理解如何将这些流行的技术整合到一个实际的应用中。以下是对这些技术及其整合方式的...

    Spring boot+mybatis+thymeleaf 实现登录注册增删改查功能的示例代码

    在本示例中,我们将探讨如何使用Spring Boot、MyBatis和Thymeleaf构建一个包含登录注册以及增删改查功能的应用。首先,我们从项目结构和依赖开始。 1. **项目创建与依赖管理**: 使用Maven创建一个Spring Boot项目...

    springboot+mybatis+mysql+thymeleaf 实现最基本数据库操作demo

    在本项目中,我们主要探讨的是如何利用SpringBoot框架与MyBatis相结合,再辅以MySQL数据库和Thymeleaf模板引擎,构建一个基础的数据库操作示例。这个"springboot+mybatis+mysql+thymeleaf 实现最基本数据库操作demo...

    spring boot+hibernate+thymeleaf 练习demo项目源码

    在本项目中,"spring boot+hibernate+thymeleaf 练习demo项目源码" 是一个基于Spring Boot框架、Hibernate ORM工具和Thymeleaf模板引擎的实践示例。这个小而精简的Demo旨在帮助学习者理解如何整合这三个核心技术来...

    Springboot 整合Mybatis +thymeleaf 实现增删改查,包含前端HTML页面

    在本教程中,我们将深入探讨如何使用Spring Boot整合Mybatis和Thymeleaf来实现一个基本的CRUD(创建、读取、更新、删除)应用。这个实例特别适合初学者,因为它提供了一个从前端到后端完全功能的示例。 首先,...

    spring mvc整合thymeleaf示例

    thymeleaf,我个人认为是个比较好的模板,性能也比一般的,比如freemaker的要高,而且把将美工和程序员能够结合起来,美工能够在浏览器中查看静态效果,程序员可以在应用服务器查看带数据的效果。 thymeleaf是一个...

    SpringBoot+Thymeleaf跳转的简单实例

    当运行Spring Boot应用并访问`http://localhost:8080/`时,Thymeleaf会根据`home.html`中的表达式将模型数据渲染到页面上,显示“欢迎来到 SpringBoot + Thymeleaf 跳转实例”和“这是一个简单的页面跳转示例”。...

    SpringBootMybatis+poi+Thymeleaf实现excel文件数据导入到数据库以及从数据库将数据导出成excel.zip

    在Spring Boot应用中,Thymeleaf通常用于生成动态的Web页面,提供前后端分离的解决方案。 5. **Excel数据导入到数据库**: 使用Apache POI,我们可以解析Excel文件,获取工作表和单元格的数据。然后,通过MyBatis的...

    spring与thymeleaf小示例

    在本示例中,我们将探讨如何使用IntelliJ IDEA(简称IDEA)集成Spring框架与Thymeleaf模板引擎来创建一个小型Web应用程序。Thymeleaf是一个强大的、直观的前端技术,它允许开发者在HTML中直接编写模板,然后由Spring...

    Spring3+ThymeLeaf

    通过这个标签,我们可以理解这是一个关于如何在Spring应用中使用Thymeleaf进行邮件内容动态生成和发送的示例或教程。 至于压缩包中的文件"SpringEmail",可能包含了实现上述功能的源代码、配置文件或其他相关资源。...

    springboot+shiro+mybatis+Thymeleaf实现用户权限框架

    2. `26-spring-boot-shiro-mybatis认证与授权与加密`: 这可能是一个教程文档或代码示例,详细解释了如何集成Spring Boot、Shiro和MyBatis来实现用户认证、授权和加密功能。 通过以上技术的整合,这个框架实现了请求...

    springboot+jpa+thymeleaf增删改查示例

    在本示例中,我们探讨的是如何利用Spring Boot、JPA(Java Persistence API)和Thymeleaf模板引擎实现一个基本的CRUD(创建、读取、更新、删除)应用程序。Spring Boot是Java领域的一个轻量级框架,它简化了新Spring...

    Spring Boot + thymeleaf 实现文件上传下载功能

    Spring Boot + Thymeleaf 实现文件上传下载功能 在本文中,我们将学习如何使用...这些知识点可以帮助开发者快速了解如何使用 Spring Boot 和 Thymeleaf 实现文件上传下载功能,并提供一个完整的示例项目供开发者参考。

    Spring boot + thymeleaf 后端直接给onclick函数赋值的实现代码

    "Spring Boot + Thymeleaf 实现后端直接给 onclick 函数赋值的知识点" Spring Boot 是一个基于 Java 的框架,用于构建基于 Web 的应用程序,而 Thymeleaf 是一个基于 XML 的模板引擎,用于生成 HTML 内容。在 ...

    SpringBoot+Thymeleaf+SSM+Vue.js实现简单的增删改查

    在本项目中,我们主要利用SpringBoot框架与Thymeleaf模板引擎,结合传统的SSM(Spring、SpringMVC、MyBatis)架构以及前端Vue.js技术,来实现一个基本的增删改查功能。这是一个典型的后端服务与前端交互的示例,适合...

Global site tag (gtag.js) - Google Analytics