How do I do pattern matching using regular expression in Spring EL?

In this Spring Expression Language example we are going to learn how to use regular expression or regex to check if a text matches a certain pattern. Spring EL support regular expression using the matches operator.

The matches operator will check if the value has a pattern defined by the regex string and it returns the evaluation result as a boolean value true if the text matches the regex or false if otherwise.

For example we can use the matches operator to check is a the given email address is a valid email address. As can be seen in the following example:

<property name="emailValid" 
          value="#{user.email matches '^[_A-Za-z0-9-]+(.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(.[A-Za-z0-9]+)*(.[A-Za-z]{2,})$'}"/>

This configuration will evaluate the user.email property to check if the email pattern matches with the given regular expression. If matches then the emailValid property will be set to true otherwise it will be false.

Let’s see the complete example. Here are the spring configuration file, the User bean and a simple class for running the configuration file.

<?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">

    <bean id="user" class="org.kodejava.example.spring.el.User">
        <constructor-arg name="email" value="kodejava@gmail.com"/>
        <property name="emailValid"
                  value="#{user.email matches '^[_A-Za-z0-9-]+(.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(.[A-Za-z0-9]+)*(.[A-Za-z]{2,})$'}"/>
    </bean>

    <bean id="user2" class="org.kodejava.example.spring.el.User">
        <constructor-arg name="email" value="kodejava.at.gmail.dot.com"/>
        <property name="emailValid"
                  value="#{user2.email matches '^[_A-Za-z0-9-]+(.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(.[A-Za-z0-9]+)*(.[A-Za-z]{2,})$'}"/>
    </bean>

</beans>

The User bean is a simple pojo with two properties, a string email property and a boolean validEmail property.

package org.kodejava.example.spring.el;

public class User {
    private String email;
    private boolean emailValid;

    public User() {
    }

    public User(String email) {
        this.email = email;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isEmailValid() {
        return emailValid;
    }

    public void setEmailValid(boolean emailValid) {
        this.emailValid = emailValid;
    }
}

And finally the application class.

package org.kodejava.example.spring.el;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELRegexExample {
    public static void main(String[] args) {
        ApplicationContext context =
            new ClassPathXmlApplicationContext("spel-regex.xml");

        User user = (User) context.getBean("user");
        System.out.println("user.getEmail()     = " + user.getEmail());
        System.out.println("user.isEmailValid() = " + user.isEmailValid());

        User user2 = (User) context.getBean("user2");
        System.out.println("user.getEmail()     = " + user2.getEmail());
        System.out.println("user.isEmailValid() = " + user2.isEmailValid());
    }
}

When we run the code we will obtain the following result:

user.getEmail()     = kodejava@gmail.com
user.isEmailValid() = true
user.getEmail()     = kodejava.at.gmail.dot.com
user.isEmailValid() = false

How do I handle or avoid null value in Spring EL?

In this example you will learn how to avoid a null value, which causing a NullPointerException thrown in a Spring EL expression. To avoid this from happening we can use the null-safe accessor, using the ?. operator.

We are using the previous example, How do I inject bean’s property using Spring EL? classes, which are the Student class and the Grade class. What we need is to create a new spring configuration file to demonstrate this feature. So, here is the configuration file:

<?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">

    <bean id="student" class="org.kodejava.example.spring.el.Student">
        <property name="name" value="Alice"/>
        <property name="grade" value="#{grade.getName()?.toUpperCase()}"/>
    </bean>

    <bean id="grade" class="org.kodejava.example.spring.el.Grade">
        <property name="name">
            <null/>
        </property>
        <property name="description" value="A beginner grade."/>
    </bean>

</beans>

The use of null-safe accessor can be seen on the student bean’s grade property. We are calling the grade.getName() method and convert it to uppercase. We deliberately set the grade.name property to null. Calling toUpperCase on a null value will throw the NullPointerException. But because we are using the null-safe accessor the exception is not thrown, because the expression will not execute the code after the null-safe accessor. In this case when getName() return null, the toUpperCase() method will never get called.

Below is the demo program code:

package org.kodejava.example.spring.el;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELNullSafeExpressionDemo {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spel-null-safe.xml");

        Student student = (Student) context.getBean("student");
        System.out.println("Name  = " + student.getName());
        System.out.println("Grade = " + student.getGrade());
    }
}

Here is the result of the code:

Name  = Alice
Grade = null

How do I get web application context path in JSP?

This example show you how to obtain web application context path in JSP using Expression Language (EL) feature of JSP. To get the context path we can utilize the pageContext, it is an implicit object that available on every JSP pages. From this object you can get access to various object such as:

  • servletContext
  • session
  • request
  • response

To get the context path value you will need to read it from the request.contextPath object. This contextPath can be useful for constructing a path to you web resources such as CSS, JavaScript and images. Some libraries that you’ll need to enable the JSP Expression Language (EL) in your JSP Pages, which usually already included in a Servlet container such as Apache Tomcat including:

  • javax.servlet-api-3.0.1
  • javax.servlet.jsp-api-2.3.1
  • javax.servlet.jsp.jstl-api-1.2.1

First let’s create the index.jsp file.

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>JSP - Context Path</title>
</head>

<body>
Web Application Context Path = ${pageContext.request.contextPath}
</body>
</html>

And here is you web.xml configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
        version="4.0">

  <!-- Config here. -->

</web-app>

Web Application Context Path
JSP context path example