Jakarta Expression Language API Development Example in Java Library

Jakarta Expression Language (EL) API is a powerful tool in the Java class library for development and processing of expression in JSP, JSF and Servlet and other Java Ee applications.EL provides a concise and intuitive expression language that allows developers to use expressions similar to JavaScript or JSP scripts in the Java code. This article will introduce how to use the Jakarta El API in Java applications to develop instances.We will use a simple example to demonstrate how to use EL expressions to calculate and operate variables. First of all, we need to introduce the relevant library and classes: import javax.el.ExpressionFactory; import javax.el.ValueExpression; import javax.el.ELContext; import javax.el.ELProcessor; Next, we need to create an EL expression factory object: ExpressionFactory factory = ExpressionFactory.newInstance(); Then, we can create an EL expression through the factory object, such as calculating the two numbers: String expression = "2 + 3"; ValueExpression valueExpression = factory.createValueExpression(expression, Integer.class); Next, we need to create an EL context: ELProcessor processor = new ELProcessor(); ELContext context = processor.getELManager().getELContext(); Then, we can use the context object to calculate and obtain the value of the expression: Integer result = (Integer) valueExpression.getValue(context); System.out.println ("expression calculation result:" + result); In addition to basic mathematical operations, EL also supports various operators and functions, so we can use more complex expressions to achieve various functions. Let us assume that we have a list of names and want to use EL expressions to filter out the name containing specific letters: List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Emily"); String filterExpression = "names.stream().filter(name -> name.contains('a')).collect(Collectors.toList())"; ValueExpression filteredExpression = factory.createValueExpression(context, filterExpression, List.class); List<String> filteredNames = (List<String>) filteredExpression.getValue(context); System.out.println ("List of names containing letters 'a':" + Filterednames); By using EL expressions, we can easily calculate complex expressions in Java applications, thereby simplifying the development process. To sum up, this article introduces how to use Jakarta Expression Language API in Java applications.We discussed the basic use of EL expressions and provided example code to help readers better understand and use EL expressions.By using EL, developers can more easily perform expressions and processing of Java EE applications.