Spring+thymeleaf small example

The previous article wrote a simple Spring mvc example. The interface presentation layer uses jsp. In this article, combined with thymeleaf, the presentation layer is changed to html. Different places with jsp will add special instructions.
The same example is also in the intranet environment, instead of using maven, the jar package is directly placed in the project.
1. Configure web.xml (and use jsp as the presentation layer without any changes), the main functions
1. Define a servlet interceptor and Mapping rules
2. Introduce spring-context configuration file
3. Add log4j configuration file
Specific files:
<?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>


2. DispatcherServlet Context configuration file, function
1. Activate annotation configuration function
2. Configure resource file path
3. Configure view layer technology
4. Introduce specific component configuration documents
Specific files:
<?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>



Compared with using jsp as the view, using html mainly introduces the template rendering class corresponding to thymeleaf.

3. Component configuration document, the main functions
1. Configure the default page path
2. Configure the component scan path
Specific files
<?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>


Fourth, the controller code
//**
 *
 */
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 code:

<!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
        }
     });
 
 $.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
        }
     });
})

</script>
</html>




The final project directory:


By comparing with the previous use of jsp as the view layer, it can be found that using html as the view layer only adds several dependent jars in the red box in the above figure, and then modify the configuration file Servlet-context For the view template in .xml, the code does not need to be changed at all, so using spring mvc can easily convert between different view layer technologies.


Please refer to the attachment for the specific code of the project

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326925336&siteId=291194637