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可以方便的在不同的视图层技术间转换。


工程的具体代码请参考附件

猜你喜欢

转载自fengyilin.iteye.com/blog/2338830
今日推荐