Spring MVC: Tutorial

This is a step-by-step instruction on how to create a Spring MVC web application. In order to follow it, you only need a Maven and JDK 18+. Starting from simple hello world, you will add more and more modules.

If you want to have more straight-forward experience following this instruction, you can use Powershell to create files and folders. To install Powershell, run  and launch it in your project's folder by typing   in explorers address bar. In this tutorial Powershell is optional and you can ignore provided  commands. You can create files and folders as you wish. If you want to execute Powershell command from CMD, use this:.

Regarding data access there are different concepts: JDBC, ORM, JPA, Spring Data Accessundefined and different Spring modules: spring-jdbc, spring-orm, spring-data-jdbcundefined, spring-data-jpaundefined.

Spring MVC
1. Create :


 * Copy from above and execute

2. Create :
 * Copy from above and execute
 * Namespaces can differ if you're using Spring < 6undefined.

3. Create :

4. Create :

5. Run your app:

6. Visit localhost:8080/raw in your browser, you'll see: hello there! UTF-8 ?? ???????? ? Encoding doesn't work, but this problem will go away when you'll choose a template engine for your View layer - proceed to or  section.

To stop server, press. Similar steps can be found in defferent sources.

JSP
1. Add ViewResolver bean to / undefined:
 * If you'll uncomment  property, this ViewResolver will be called only if view name you are returning from controller method ends with  . If this is what you need, comment out   property.

2. Add this method to :

3. Create  page:

4. Restart server and visit localhost:8080/jsp, you'll see: ? This is complete jsp сообщение ?. To fix encoding issue you can add  as the first line of your   file or you can change encoding globally by adding following lines to  :

Thymeleaf
Similar guides can be found in different sourcesundefined.

1. In your  add this dependency:

2. Add this beans to your undefined:
 * Comment out  property or set it to true, and you will have to restart server every time you change your templates.
 * Uncomment  property and Spring will use Thymeleaf only if view name you're returning in your controller ends with.

3. Create :

4. Add this method to :

5.  and visit localhost:8080/thy.

For your convenience you can add to your template a list of all links avaiable in your application:

6.1 In your /  add this: 6.2 In your  add this:

CSS
1. In your /  add this element: 2. Create :

3. Thymeleaf: to your /  add this element: 3. JSP: to your /  add this element:

4.  and visit your page.

Spring Security
This section consists of four subsections, but you will need to follow only two of them - one way of configuration and one template engine.

Spring Security can be configured via Java code or XML files. First two steps are common for both flows, but then you should choose only one flow - XML or JAVA - and follow it only. XML flow is almost never used and probably should be ignored, but it's provided here as demonstration.

1. Add this property and dependencies to your undefined:

2. Add Spring Security filter chain to your / :

Java configuration
3. Create a undefined:
 * This is a new API. You can find example of defining both of this security beans from Spring itself: ;
 * Different way of java configuration can be found in book Mastering Springundefined, through overriding methods in WebSecurityConfigurerAdapter, which has been removed from API in Spring 6.
 * Different way of java configuration can be found in book Mastering Springundefined, through overriding methods in WebSecurityConfigurerAdapter, which has been removed from API in Spring 6.

XML configuration
3. To your /  add ContextLoaderListener:

4. Create undefined:

Now your application is protected and you can learn how to interact with Spring Security from View layer.

Spring Security + Thymeleaf
At this point you should already have Spring Security and Thymeleaf both working, this section will show you how to call security layer from Thymeleaf templates.

1. Add this dependency to your :

2. In your  to the bean with the   add this property:

3. In your /  add this line:

4. Visit this page, you will see: Your name is user, if I'm not mistaken. 🔑

Spring Security + JSP
At this point you should already have Spring Security and JSP both working, this section will show you how to call security layer from view layer.

1. Add this dependency to your :

2. Add this line as the first line in : and this line to the :
 * First line will result in exception being thrown if you will open this page not being logged in, while second line wouldn't.

3. Visit this page, you will see: 🔑 Glad to see you, user. There are multiple ways to obtain username, user.

Logging
1. In your  add this dependency higher than thymeleaf:

2. Create :

3. To any of your classes, add following imports and a class variable, and you can write logsundefined:

Internationalization
1. To /  add this elementsundefined:

2. Create : welcome=You are welcome! 3. Create : welcome=Добро пожаловать! 4. In your Thymeleaf template /  add this line: 4. In your JSP add this linesundefined:

5. Visit this page and change language of message by appending  or   parameters to URL.

Aspect Oriented Programming
Consult book Spring Start Here, Chapter 6.

1. Add this dependency to your pom.xml: 2. Add these namespace and element to your :

3. Create :

H2 DataSource with spring-jdbc
1. To your  add this dependencies:

2. To your  add this namespace and a beanundefined:

3. Create :

4. If you will start your application you will see a log: Starting embedded database: url='jdbc:h2:mem:dataSource;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa' Now you have a working dataSource bean.

JdbcTemplate Usage
At this point you should have a working dataSource bean.

1. Create : 2. Create :

3. Create :
 * You can find an example of how to use JdbcTemplate in an external source: Using JdbcTemplate to work with persisted data.

4. In your  add this import, class variable and a method:

5. Visit https://localhost:8080/all, you will see contents of your Message table.

Spring Data Repository
Spring Data Repositories require a working dataSource bean, if you don't have it - follow this subsection:.

1. To your  add this property and dependency:
 * If you have  dependency you can remove it (you've added it at  step).

2. Create undefined:
 * This is where you enable discovering of Spring Repositories. You don't need this class if you've already configured Hibernate as in section.

3. Create :
 * Some lines are commented out, because they are used in different flow:.

4. Create undefined:

5. Create :

5. In your  add these imports, class variable and methods: 6. Create new messages: localhost:8080/save?msg=ilovetomato, or get message with id=1 by following localhost:8080/find?id=1.

H2 DataSource
Follow this section to obtain a dataSource bean.

1. To your  add this dependencies: 2. To your  add this bean:
 * As you can see, there is a one long ugly commented-out connectionInitSqls property. You don't need it with Hibernate, but if you will wonder how you can provide initializing SQL script to XML-defined dataSource bean - that's how you can do it. If you'll want something more readable and concise, uncomment  element and add   dependency and   namespace as in this section:.

Now you have a working dataSource bean, which you can use to interact with database.

Hibernate Configuration
At this point you should have a working dataSource bean.

1. To your  add this property and dependency:

2. To your  add this namespace and elements:
 * Note  element- this is where you enable Spring Data Repository lookup, this is why you wouldn't need   class in  section. If you are not going to use Spring Repositories you can remove this element and   namespace.
 * Both Spring 5 and Spring 6 use Hibernate through  package, even if it's Hibernate 6.
 * If you're using Hibernate 6, you can remove  line - Hibernate 6 will automatically resolve dialect from the JDBC DatabaseMetaDataundefined.

Now your Hibernate is configured, but it's not being used by your application. You can proceed to section in which you should skip the optional step with creation of   class. When you will create  comment out all   imports and   annotation. Also uncomment all  imports,   and   line.

Spring Security JDBC
At this point you should have a working DataSource bean. This is how you can use your database in Spring Security:

In  remove   method and instead add this two methodsundefined:

REST
1. Add this dependency to :

2. Add this element to your :

3. Create :
 * These are two ways which you can use to marshall an object to json, they produce different output for chars which are not in Basic Multilingual Plane, this is an issue of Jackson library.

4. Invoke these endpoints with curl or Powershell: curl "http://localhost:8080/greeting0" 0..1 | % { Invoke-WebRequest -Uri "http://localhost:8080/greeting$($_)" } | select -ExpandProperty Content

Spring 5
You can switch all of the above to Spring 5 and Hibernate 5.

1. In  use second group of dependency versions:
 * First group provided here for convenience, you will get it by following tutorial.

2. In  replace digit in   and   artifacts.

3. In  replace digit in   and.

4. In all your entity classes (only  in this tutorial) change your imports from   to.

5. If you have replace it with

If you want to get rid of  properties, for all   dependencies you can remove their   lines and add this properties and   element to  :