Merge pull request #297 from gmaipady/master

Add spring-thymeleaf example
This commit is contained in:
David Morley 2015-12-28 20:42:09 -06:00
commit e4e8042d73
16 changed files with 658 additions and 0 deletions

View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

42
spring-thymeleaf/.project Normal file
View File

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>spring-thymeleaf</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
<nature>org.eclipse.wst.jsdt.core.jsNature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,23 @@
=========
## Spring Thymeleaf Example Project
### Relevant Articles:
### Build the Project
mvn clean install
### Run the Project
mvn cargo:run
- **note**: starts on port '8082'
Access the pages using the URLs:
http://localhost:8082/spring-thymeleaf/
http://localhost:8082/spring-thymeleaf/addStudent/
http://localhost:8082/spring-thymeleaf/listStudents/
The first URL is the home page of the application. The home page has links to the other two pages.

148
spring-thymeleaf/pom.xml Normal file
View File

@ -0,0 +1,148 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>spring-thymeleaf</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<java-version>1.7</java-version>
<!-- spring -->
<org.springframework-version>4.1.8.RELEASE</org.springframework-version>
<javax.servlet-version>3.0.1</javax.servlet-version>
<!-- logging -->
<org.slf4j.version>1.7.12</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<!-- thymeleaf -->
<org.thymeleaf-version>2.1.4.RELEASE</org.thymeleaf-version>
<!-- validation -->
<javax.validation-version>1.1.0.Final</javax.validation-version>
<org.hibernate-version>5.1.2.Final</org.hibernate-version>
<!-- Maven plugins -->
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
<cargo-maven2-plugin.version>1.4.15</cargo-maven2-plugin.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- Thymeleaf -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>${org.thymeleaf-version}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>${org.thymeleaf-version}</version>
</dependency>
<!-- Logging -->
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-version}</version>
<scope>provided</scope>
</dependency>
<!-- Validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${javax.validation-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${org.hibernate-version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
</excludes>
<systemPropertyVariables>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>${cargo-maven2-plugin.version}</version>
<configuration>
<wait>true</wait>
<container>
<containerId>jetty8x</containerId>
<type>embedded</type>
<systemProperties>
</systemProperties>
</container>
<configuration>
<properties>
<cargo.servlet.port>8082</cargo.servlet.port>
</properties>
</configuration>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,27 @@
package org.baeldung.thymeleaf.controller;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*
*/
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String getHome(Model model) {
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.getDefault());
model.addAttribute("serverTime", dateFormat.format(new Date()));
return "home";
}
}

View File

@ -0,0 +1,70 @@
package org.baeldung.thymeleaf.controller;
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.baeldung.thymeleaf.model.Student;
/**
* Handles requests for the student model.
*
*/
@Controller
public class StudentController {
@RequestMapping(value = "/saveStudent", method = RequestMethod.POST)
public String saveStudent(@Valid @ModelAttribute Student student, BindingResult errors, Model model) {
if (!errors.hasErrors()) {
// get mock objects
List<Student> students = buildStudents();
// add current student
students.add(student);
model.addAttribute("students", students);
}
return ((errors.hasErrors()) ? "addStudent" : "listStudents");
}
@RequestMapping(value = "/addStudent", method = RequestMethod.GET)
public String addStudent(Model model) {
model.addAttribute("student", new Student());
return "addStudent";
}
@RequestMapping(value = "/listStudents", method = RequestMethod.GET)
public String listStudent(Model model) {
model.addAttribute("students", buildStudents());
return "listStudents";
}
private List<Student> buildStudents() {
List<Student> students = new ArrayList<Student>();
Student student1 = new Student();
student1.setId(1001);
student1.setName("John Smith");
student1.setGender('M');
student1.setPercentage(Float.valueOf("80.45"));
students.add(student1);
Student student2 = new Student();
student2.setId(1002);
student2.setName("Jane Williams");
student2.setGender('F');
student2.setPercentage(Float.valueOf("60.25"));
students.add(student2);
return students;
}
}

View File

@ -0,0 +1,30 @@
package org.baeldung.thymeleaf.formatter;
import java.text.ParseException;
import java.util.Locale;
import org.springframework.format.Formatter;
import org.thymeleaf.util.StringUtils;
/**
*
* Name formatter class that implements the Spring Formatter interface.
* Formats a name(String) and return the value with spaces replaced by commas.
*
*/
public class NameFormatter implements Formatter<String> {
@Override
public String print(String input, Locale locale) {
return formatName(input, locale);
}
@Override
public String parse(String input, Locale locale) throws ParseException {
return formatName(input, locale);
}
private String formatName(String input, Locale locale) {
return StringUtils.replace(input, " ", ",");
}
}

View File

@ -0,0 +1,60 @@
package org.baeldung.thymeleaf.model;
import java.io.Serializable;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
/**
*
* Simple student POJO with few fields
*
*/
public class Student implements Serializable {
private static final long serialVersionUID = -8582553475226281591L;
@NotNull(message = "Student ID is required.")
@Min(value = 1000, message = "Student ID must be at least 4 digits.")
private Integer id;
@NotNull(message = "Student name is required.")
private String name;
@NotNull(message = "Student gender is required.")
private Character gender;
private Float percentage;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Character getGender() {
return gender;
}
public void setGender(Character gender) {
this.gender = gender;
}
public Float getPercentage() {
return percentage;
}
public void setPercentage(Float percentage) {
this.percentage = percentage;
}
}

View File

@ -0,0 +1,20 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,9 @@
msg.id=ID
msg.name=Name
msg.gender=Gender
msg.percent=Percentage
welcome.message=Welcome Student !!!
msg.AddStudent=Add Student
msg.ListStudents=List Students
msg.Home=Home

View File

@ -0,0 +1,53 @@
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven conversion-service="conversionService" />
<!-- Standard Spring formatting-enabled implementation -->
<beans:bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<beans:property name="formatters">
<beans:set>
<beans:bean class="org.baeldung.thymeleaf.formatter.NameFormatter" />
</beans:set>
</beans:property>
</beans:bean>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Message source -->
<beans:bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basename" value="messages" />
</beans:bean>
<!-- Resolves views selected for rendering by @Controllers to .html resources
in the /WEB-INF/views directory -->
<beans:bean id="templateResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".html" />
<beans:property name="templateMode" value="HTML5" />
</beans:bean>
<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:property name="order" value="1" />
<beans:property name="viewNames" value="*" />
</beans:bean>
<context:component-scan base-package="org.baeldung.thymeleaf.controller" />
</beans:beans>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
</beans>

View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Add Student</title>
</head>
<body>
<h1>Add Student</h1>
<form action="#" th:action="@{/saveStudent}" th:object="${student}"
method="post">
<ul>
<li th:errors="*{id}" />
<li th:errors="*{name}" />
<li th:errors="*{gender}" />
<li th:errors="*{percentage}" />
</ul>
<table border="1">
<tr>
<td><label th:text="#{msg.id}" /></td>
<td><input type="number" th:field="*{id}" /></td>
</tr>
<tr>
<td><label th:text="#{msg.name}" /></td>
<td><input type="text" th:field="*{name}" /></td>
</tr>
<tr>
<td><label th:text="#{msg.gender}" /></td>
<td><select th:field="*{gender}">
<option th:value="'M'" th:text="Male"></option>
<option th:value="'F'" th:text="Female"></option>
</select></td>
</tr>
<tr>
<td><label th:text="#{msg.percent}" /></td>
<td><input type="text" th:field="*{percentage}" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>

View File

@ -0,0 +1,23 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home</title>
</head>
<body>
<h1>
<span th:text="#{welcome.message}" />
</h1>
<p>
Current time is <span th:text="${serverTime}" />
</p>
<table>
<tr>
<td><a th:href="@{/addStudent}" th:text="#{msg.AddStudent}" /></td>
</tr>
<tr>
<td><a th:href="@{/listStudents}" th:text="#{msg.ListStudents}" /></td>
</tr>
</table>
</body>
</html>

View File

@ -0,0 +1,36 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Student List</title>
</head>
<body>
<h1>Student List</h1>
<table border="1">
<thead>
<tr>
<th th:text="#{msg.id}" />
<th th:text="#{msg.name}" />
<th th:text="#{msg.gender}" />
<th th:text="#{msg.percent}" />
</tr>
</thead>
<tbody>
<tr th:each="student: ${students}">
<td th:text="${student.id}" />
<td th:text="${{student.name}}" />
<td th:switch="${student.gender}"><span th:case="'M'"
th:text="Male" /> <span th:case="'F'" th:text="Female" /></td>
<td th:text="${#conversions.convert(student.percentage, 'Integer')}" />
</tr>
</tbody>
</table>
<div>
<p>
<a th:href="@{/}" th:text="#{msg.Home}" />
</p>
</div>
</body>
</html>

View File

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name></display-name>
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 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/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>