Posts

Showing posts with the label spring mvc

Injecting authenticated user into Spring MVC @Controllers

Injecting injecting authenticated user into Spring MVC handler method can be done with @AuthenticationPrincipal annotation and AuthenticationPrincipalArgumentResolver that is an implementation of Spring MVS MethodArgumentResolver . AuthenticationPrincipalArgumentResolver is registered by default with web security configuration (e.g. when you enable security with @EnableWebSecurity ).

Spring MVC: Trgger manual validation of a form object

Sometimes it may be needed to use manual validation in Spring MVC @Controller. This is very simple with Spring’s org.springframework.validation.ValidationUtils class. Learn how to invoke a validator in two different scenarios. Scenario 1 - invoke validation In this scenario, I have a user form with username field. Username field is validated with custom validator in order to verify the existance in e.g. database. public class User { @UserExists private String username; } In controller class I have a method that handles POST method of that object: @Autowired private org.springframework.validation.Validator validator; @RequestMapping(value = "/user", method = RequestMethod.POST) public String validate(@ModelAttribute User user, Errors errors) { ValidationUtils.invokeValidator(validator, user, errors); if (errors.hasErrors()) { // error, show errors to the user } // success, form is valid! } org.springframework.validatio...

Spring MVC 4 Quickstart Maven Archetype Improved - More Java 8 Features

For all those developers interested in bootstrapping Spring 4 application quickly without Spring Boot, please check my Spring MVC 4 Quickstart Maven Archetype that just got updated. Archetype uses Java 8 as target platform for some time already but no specific Java 8 features were supported. Recent changes bring (apart from some bug fixing) support for Java 8 Data & Time API in Thymeleaf, Jackson and JPA.

Spring MVC 4 Quickstart Maven Archetype Improved

Spring Boot allows getting started with Spring extremely easy. But there are still people interested in not using Spring Boot and bootstrap the application in a more classical way. Several years ago, I created an archetype (long before Spring Boot) that simplifies bootstrapping Spring web applications. Although Spring Boot is already some time on the market, Spring MVC 4 Quickstart Maven Archetype is still quite popular project on GitHub . With some recent additions I hope it is even better.

Validation groups in Spring MVC

Image
All constraints in Bean Validation may be added to one or more groups via groups attribute. This allows you to restrict the set of constraints applied during validation. It can be handy in cases where some groups should be validated before others like e.g. in wizards. As of Spring MVC 3.1, automatic validation utilizing validation groups is possible with org.springframework.validation.annotation.Validated annotation. In this article I will use simple Spring MVC application to demonstrate how easily you can use validation groups to validate Spring’s MVC model attributes. Form Let’s start with the form class that will be validated in steps. Firstly, we define interfaces that represents constraint groups: public class Account implements PasswordAware { interface ValidationStepOne { // validation group marker interface } interface ValidationStepTwo { // validation group marker interface } } Validation contraints Next we assign constra...

Spring MVC Integration Testing: Assert the given model attribute(s) have global errors

Image
In order to report a global error in Spring MVC using Bean Validation we can create a custom class level constraint annotation. Global errors are not associated with any specific fields in the validated bean. In this article I will show how to write a test with Spring Test that verifies if the given model attribute has global validation errors.

Better error messages with Bean Validation 1.1 in Spring MVC application

Image
Bean Validation 1.1 , among many new features, introduced error message interpolation using Unified Expression Language (EL) expressions. This allows to define error messages based on conditional logic and also enables advanced formatting options . Added to a Spring MVC application let you display more friendly error messages quite simply. In the first part of this article I will shortly describe message interpolation with EL expressions, in the second part we will build a simple web application with Spring Boot and Thymeleaf that runs on Tomcat 8.

Spring MVC and Thymeleaf: how to acess data from templates

Spring MVC and Thymeleaf: how to acess data from templates I wrote this article for thymeleaf.org, with a great help of Daniel Fernández. You can find it here: http://www.thymeleaf.org/doc/articles/springmvcaccessdata.html ” 12/11/2016: Updated to Thymeleaf 3.0. Find the examples used in this article in this repository: https://github.com/kolorobot/spring-boot-thymeleaf ( http://blog.codeleak.pl/2014/04/how-to-spring-boot-and-thymeleaf-with-maven.html ) In a typical Spring MVC application, @Controller classes are responsible for preparing a model map with data and selecting a view to be rendered. This model map allows for the complete abstraction of the view technology and, in the case of Thymeleaf, it is transformed into a Thymeleaf context object (part of the Thymeleaf template execution context ) that makes all the defined variables available to expressions executed in templates. Spring model attributes Spring MVC calls the pieces of data that can be accessed during ...

CSRF protection in Spring MVC, Thymeleaf, Spring Security application

Cross-Site Request Forgery (CSRF) is an attack which forces an end user to execute unwanted actions on a web application in which he/she is currently authenticated. Preventing CSRF attacks in Spring MVC / Thymeleaf application is fairly easy if you use Spring Security 3.2 and above.

Configure favicon.ico in Spring MVC based application

Favicon is an icon (favicon.ico) associated with your website. Not every website is using favicon though. But most browsers do not care about it and they make request for it anyways. When favicon is not in place the server will return unnecessary 404 Not Found error.

Thymeleaf Page Layouts

Usually websites share common page components like the header, footer, menu and possibly many more. These page components can be used by the same or different layouts. There are two main styles of organizing layouts in projects: include style and hierarchical style. Both styles can be easily utilized with Thymeleaf without losing its biggest value: natural templating .

HOW-TO: Using @PropertySource annotation in Spring 4 with Java 7

Image
Today I migrated one of my projects, that I am currently working on, to Spring 4.0. Since it is a really simple web application I use to learn and demo Spring features, I only needed to update the POM file of my project and change the Spring version. I deployed the project to Tomcat 7 server and apparently the application did not start. I saw this message in IntelliJ console: Failed to load bean class: pl.codeleak.t.config.RootConfig; nested exception is org.springframework.core.NestedIOException: Unable to collect imports; nested exception is java.lang.ClassNotFoundException: java.lang.annotation.Repeatable . What the ...?

Thymeleaf template layouts in Spring MVC application with no extensions

After some years with JSP/JSTL and Apache Tiles I started discovering Thymeleaf for my Spring MVC applications. Thymeleaf is a really great view engine and it simplifies and speeds up the development despite that lack of good IntelliJ (vote here: http://youtrack.jetbrains.com/issue/IDEABKL-6713 ) support at the moment (there is an Eclipse plugin though). While learning how to use Thymeleaf I investigated different possibilities of working with layouts. Apart from the native fragment inclusion mechanism there are at least two options to work with layouts: Thymeleaf integration with Apache Tile and Thymeleaf Layout Dialect . Both seem to work fine, but inspired by this comment about a simple and custom option, I gave it a try. In this post I will show I created the solution.

Is it worth upgrading to Thymeleaf 2.1?

Thymeleaf 2.1 release arrived. The new version brings plenty of new features in its core as well as in Spring Integration module like improvements of fragments inclusions, rendering view fragments directly from @Controller, improved form validation error reporting to name a few. But is it worth upgrading to Thymeleaf 2.1? Let's see.

Different ways of validating @RequestBody in Spring MVC with @Valid annotation

In Spring MVC the @RequestBody annotation indicates a method parameter should be bound to a body of the request. @RequestBody parameter can treated as any other parameter in a @RequestMapping method and therefore it can also be validated by a standard validation mechanism. In this post I will show 3 ways of validating the @RequestBody parameter in your Spring MVC application.

Spring MVC @PathVariable Tips

@PathVariable annotation is one of the Spring MVC features that allows creating RESTful Web application much easier. It indicates that a handler method parameter should be bound to a URI template. In this post I will present two useful tips for working with this annotation.