spring upload multiple file

spring upload multiple files

Spring upload multiple files with restful API

Spring upload multiple files with restful api is one of the most requires task. If you are working with spring, chances are high that you are working with file as well.

If you are doing registration, you might need to have multiple files to be uploaded to your server. So how to do spring upload multiple files is what I will be showing you.
Continue reading spring upload multiple files

custom spring validator

custom spring validator

creating custom spring validator

Spring boot comes with lots of validation out of the box, Min, Max, NotNull. But, those are not enough as custom validations are important and needed.

When to use custom spring validator

When there is specific business logic that needs to be validated, custom validation will be to the rescue.

An example of creating a custom spring validator can be the following scenario. On your application there is a registration page.

Let’s say you have a survey sent out before registration and you want a user to fill out a survey using their email associated with it before registration.

When the user comes to your website for registration, one criteria as validated user is a completion of the survey. Here, you can create this validator and use it on more than one forms.

What do I need for custom spring validator

A basic knowledge of java and spring framework is good enough for this. Also make sure if it is worth creating spring custom validator. This is also the same if you are considering custom spring boot validator

Custom Spring validator example, spring validator tutorial

Let us extend the above example and work on it. We would like to have a unique email to be read from database as custom spring validator.

Let’s call it UniqueEmailValidator. This is will be checked mostly during registration and we can assume it can also used in a couple of other places.

First, we need to create a custom target interface


/**
 * Custom email validation
 * Checks if the email already exists or not.
 * 
 * @author Kaleb Woldearegay 
 *
 */
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueEmailValidator.class)
public @interface UniqueEmail {
    String message() default "{Email already exists}";
    Class[] groups() default {};
    Class[] payload() default {};
}

You can find the full code on github here.

Then we will need a concrete class that implements the interface


/**
 * Custom email validation. Check if the provided email is unique or not.
 * @author Kaleb Woldearegay 
 *
 */
@Configurable
public class UniqueEmailValidator implements ConstraintValidator {

    private MemberService memberService; //this is injected to the class
    
    public UniqueEmailValidator() {}
    
    @Autowired
    public UniqueEmailValidator(MemberService memberService) {
        this.memberService = memberService;
    }
    
    public void initialize(UniqueEmail constraint) {
    }
 
    public boolean isValid(String email, ConstraintValidatorContext context) {
        if (email == null) {
            return false;
        }
        //actual logic of search for the member goes here..
        Optional member = this.memberService.findByEmail(email);
        return !member.isPresent();
    }

You can see the full class here

The important part of the implementation is the isValid one. That should return the boolean outcome.

That is it, now you have the a full-fledged custom spring validator in created.

You can use it using the annotation @UniqueEmailValidator in your controller or wherever you need to validate.

If you have any questions or comments, let me know.

spring boot validation

spring boot validation

Spring boot validation and Custom Validations

Spring boot validation is probably one of the cool features spring has to provide. Not only spring provided validations but also, it allows custom validation as well.

Custom Spring boot validator will allow you to act like the native validator in your application. Not only that, once you create custom spring validator, you can reuse it.

What is spring validator

Spring validator allows validating the data of the request. The validator will handle basic logic of handling validation than re-inventing the wheel.
Continue reading spring boot validation

java class not found exception

spring error ClassNotFoundException org.springframework.web.context.ContextLoaderList

ClassNotFoundException org.springframework.web.context.ContextLoaderList

When working on spring framework, you might get this error specially on eclipse. I am assuming you are working on maven and eclipse environment.

The ClassNotFound exception is a bit self explanatory that eclipse could not find the mentioned class ContextLoaderList

The web.xml file for the spring configuration might look like


<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>/WEB-INF/application-context.xml</param-value>
 </context-param>

 <listener>
   <listener-class>
         org.springframework.web.context.ContextLoaderListener
   </listener-class>
 </listener>

With this, you might have similar file like application-context in the WEB-INF path

How to fix ClassNotFoundException for ContextLoaderList

The problem will during deployment. It is not basically compile time error. It is rather runtime error.

So, we have to make sure the jar responsible for this class is available in the classpath that eclipse is reading.

Pom dependency check

Make sure you have the same/similar configuration as the one listed below on your pom file.


		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
	
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
	
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

You can have the right version for your spring in the parameter section or you can just replace it with the current version you have.

Using Deployment Assembly fix in eclipse

As we know, it is a deployment time problem, hence we have to tell the assembly where it can get its dependencies.

      Right click on the project
      Go to/search for Deployment Assembly
      Click on Add
      Select on Java Build path entries
      Select all the maven dependencies
      Finish
      Clean and build the project

Either of the above methods should fix the problem