Spring SpEL – Map

Spring SpEL – Map ”; Previous Next SpEL expression supports accessing map. Following example shows the various use cases. Example Let”s update the project created in Spring SpEL – Create Project chapter. We”re adding/updating following files − Employee.java − Employee class. MainApp.java − Main application to run and test. Here is the content of Employee.java file − package com.tutorialspoint; import java.util.Map; public class Employee { private Map<String, String> offices; public Map<String, String> getOffices() { return offices; } public void setOffices(Map<String, String> offices) { this.offices = offices; } } Here is the content of MainApp.java file − package com.tutorialspoint; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import org.springframework.expression.EvaluationContext; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; public class MainApp { public static void main(String[] args) throws ParseException { ExpressionParser parser = new SpelExpressionParser(); Employee employee = new Employee(); Map<String, String> officeMap = new HashMap(); officeMap.put(“IN”, “Hyderabad”); officeMap.put(“UK”, “London”); employee.setOffices(officeMap); EvaluationContext employeeContext = new StandardEvaluationContext(employee); // evaluates to “Hyderabad” String city = parser.parseExpression(“offices[”IN”]”).getValue(employeeContext, String.class); System.out.println(city); } } Output Hyderabad Print Page Previous Next Advertisements ”;

Spring SpEL – Methods

Spring SpEL – Methods ”; Previous Next SpEL expression supports accessing methods of an object. Following example shows the various use cases. Example Let”s update the project created in Spring SpEL – Create Project chapter. We”re adding/updating following files − Employee.java − Employee class. MainApp.java − Main application to run and test. Here is the content of Employee.java file − package com.tutorialspoint; public class Employee { private List<String> awards; public List<String> getAwards() { return awards; } public void setAwards(List<String> awards) { this.awards = awards; } public boolean isAwardee() { return awards != null && awards.size() > 0; } } Here is the content of MainApp.java file − package com.tutorialspoint; import java.text.ParseException; import java.util.Arrays; import org.springframework.expression.EvaluationContext; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; public class MainApp { public static void main(String[] args) throws ParseException { ExpressionParser parser = new SpelExpressionParser(); Employee employee = new Employee(); employee.setAwards(Arrays.asList(“Star of the Month”, “Champion”, “Accelerator”)); EvaluationContext employeeContext = new StandardEvaluationContext(employee); // string literal, evaluates to “t” String t = parser.parseExpression(“”Tutorials”.substring(2, 3)”).getValue(String.class); System.out.println(t); // evaluates to true boolean isAwardee = parser.parseExpression(“isAwardee()”).getValue(employeeContext, Boolean.class); System.out.println(isAwardee); } } Output t true Print Page Previous Next Advertisements ”;

Spring SpEL – Relational Operators

Spring SpEL – Relational Operators ”; Previous Next SpEL expression supports relational operators like <, >, equals etc. It also support instance of and matches operators. Following example shows the various use cases. Example Let”s update the project created in Spring SpEL – Create Project chapter. We”re adding/updating following files − MainApp.java − Main application to run and test. Here is the content of MainApp.java file − package com.tutorialspoint; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import org.springframework.expression.EvaluationContext; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; public class MainApp { public static void main(String[] args) throws ParseException { ExpressionParser parser = new SpelExpressionParser(); // evaluates to true boolean result = parser.parseExpression(“2 == 2”).getValue(Boolean.class); System.out.println(result); // evaluates to false result = parser.parseExpression(“2 < -5.0”).getValue(Boolean.class); System.out.println(result); // evaluates to true result = parser.parseExpression(“”black” < ”block””).getValue(Boolean.class); System.out.println(result); // evaluates to false result = parser.parseExpression(“”xyz” instanceof T(int)”).getValue(Boolean.class); System.out.println(result); // evaluates to false result = parser.parseExpression(“”5.0067” matches ”^-?\d+(\.\d{2})?$””).getValue(Boolean.class); System.out.println(result); } } Output true false true false false Print Page Previous Next Advertisements ”;

Spring AOP – Around Advice

Spring AOP – XML Based Around Advice ”; Previous Next Around is an advice type which ensures that an advice runs before and after the method execution. Following is the syntax of around advice. Syntax <aop:config> <aop:aspect id = “log” ref = “logging”> <aop:pointcut id = “PointCut-id” expression = “execution( expression )”/> <aop:around pointcut-ref = “PointCut-id” method = “methodName”/> </aop:aspect> </aop:config> Where, PointCut-id − id of the PointCut. methodName − Method name of the function to be called before a called function. To understand the above-mentioned concepts related to Around Advice, let us write an example which will implement Around Advice. To write our example with few advices, let us have a working Eclipse IDE in place and use the following steps to create a Spring application − Step Description 1 Update the project Student created under chapter Spring AOP – Application. 2 Update the bean configuration and run the application as explained below. Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points. package com.tutorialspoint; import org.aspectj.lang.ProceedingJoinPoint; public class Logging { /** * This is the method which I would like to execute * around a selected method execution. */ public String aroundAdvice(ProceedingJoinPoint jp) throws Throwable{ System.out.println(“Around advice”); Object[] args = jp.getArgs(); if(args.length>0){ System.out.print(“Arguments passed: ” ); for (int i = 0; i < args.length; i++) { System.out.print(“arg “+(i+1)+”: “+args[i]); } } Object result = jp.proceed(args); System.out.println(“Returning ” + result); return result.toString(); } } Following is the content of the Student.java file. package com.tutorialspoint; public class Student { private Integer age; private String name; public void setAge(Integer age) { this.age = age; } public Integer getAge() { System.out.println(“Age : ” + age ); return age; } public void setName(String name) { this.name = name; } public String getName() { System.out.println(“Name : ” + name ); return name; } public void printThrowException(){ System.out.println(“Exception raised”); throw new IllegalArgumentException(); } } Following is the content of the MainApp.java file. package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”); Student student = (Student) context.getBean(“student”); student.getName(); } } Following is the configuration file Beans.xml. <?xml version = “1.0” encoding = “UTF-8”?> <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xmlns:aop = “http://www.springframework.org/schema/aop” xsi:schemaLocation = “http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “> <aop:config> <aop:aspect id = “log” ref = “logging”> <aop:pointcut id = “selectName” expression = “execution(* com.tutorialspoint.Student.getName(..))”/> <aop:around pointcut-ref = “selectName” method = “aroundAdvice”/> </aop:aspect> </aop:config> <!– Definition for student bean –> <bean id = “student” class = “com.tutorialspoint.Student”> <property name = “name” value = “Zara” /> <property name = “age” value = “11”/> </bean> <!– Definition for logging aspect –> <bean id = “logging” class = “com.tutorialspoint.Logging”/> </beans> Run Project Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message. Around advice Name : Zara Returning Zara Print Page Previous Next Advertisements ”;

Example – Color Choosers

Swing Examples – Color Choosers ”; Previous Next Learn how to play with Color Choosers in Swing UI programming. Here are most commonly used examples − How to create and use a Color Chooser in Swing? How to create a Color Chooser in a Dialog in Swing? How to customized a standard color chooser of Java Swing? How to remove/replace the Preview Panel of Color Chooser in Java Swing? Print Page Previous Next Advertisements ”;

Example – Combo Boxes

Swing Examples – Comboboxes ”; Previous Next Learn how to play with Comboboxes in Swing UI programming. Here are most commonly used examples − How to use combo boxes in a Java Swing application? How to add a separator in a combo box in swing? Print Page Previous Next Advertisements ”;

Spring SpEL – EvaluationContext

Spring SpEL – EvaluationContext ”; Previous Next EvaluationContext is an interface of Spring SpEL which helps to execute an expression string in a context. References are resolved in this context when encountered during expression evaluation. Syntax Following is an example of creating an EvaluationContext and using its object to get a value. ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression(“”name””); EvaluationContext context = new StandardEvaluationContext(employee); String name = (String) exp.getValue(); It should print the result as follows: Mahesh Here the result is the value of the name field of the employee object, Mahesh. The StandardEvaluationContext class specifies the object against which the expression is evaluated. StandardEvaluationContext cannot be changed once context object is created. It caches the state and allows expression evaluation to be performed quickly. Following example shows the various usecases. Example The following example shows a class MainApp. Let”s update the project created in Spring SpEL – Create Project chapter. We”re adding following files − Employee.java − Employee class. MainApp.java − Main application to run and test. Here is the content of Employee.java file − package com.tutorialspoint; public class Employee { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Here is the content of MainApp.java file − package com.tutorialspoint; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; public class MainApp { public static void main(String[] args) { Employee employee = new Employee(); employee.setId(1); employee.setName(“Mahesh”); ExpressionParser parser = new SpelExpressionParser(); EvaluationContext context = new StandardEvaluationContext(employee); Expression exp = parser.parseExpression(“name”); // evaluate object using context String name = (String) exp.getValue(context); System.out.println(name); Employee employee1 = new Employee(); employee1.setId(2); employee1.setName(“Rita”); // evaluate object directly name = (String) exp.getValue(employee1); System.out.println(name); exp = parser.parseExpression(“id > 1″); // evaluate object using context boolean result = exp.getValue(context, Boolean.class); System.out.println(result); // evaluates to false result = exp.getValue(employee1, Boolean.class); System.out.println(result); // evaluates to true } } Output Mahesh Rita false true Print Page Previous Next Advertisements ”;

Spring MVC – Generate XML

Spring MVC – Generate XML Example ”; Previous Next The following example shows how to generate XML using the Spring Web MVC Framework. To begin with, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework. Step Description 1 Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create Java classes User and UserController under the com.tutorialspointpackage. 3 The final step is to create the content of the source and configuration files and export the application as explained below. User.java package com.tutorialspoint; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = “user”) public class User { private String name; private int id; public String getName() { return name; } @XmlElement public void setName(String name) { this.name = name; } public int getId() { return id; } @XmlElement public void setId(int id) { this.id = id; } } UserController.java package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(“/user”) public class UserController { @RequestMapping(value=”{name}”, method = RequestMethod.GET) public @ResponseBody User getUser(@PathVariable String name) { User user = new User(); user.setName(name); user.setId(1); return user; } } TestWeb-servlet.xml <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:context = “http://www.springframework.org/schema/context” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xmlns:mvc = “http://www.springframework.org/schema/mvc” xsi:schemaLocation = ” http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <mvc:annotation-driven /> </beans> Here, we have created an XML Mapped POJO User and in the UserController, we have returned the User. Spring automatically handles the XML conversion based on RequestMapping. Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your TestWeb.war file in Tomcat”s webapps folder. Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL – http://localhost:8080/TestWeb/mahesh and we will see the following screen. Print Page Previous Next Advertisements ”;

Spring DI – Non-Static Factory

Spring DI – Non-Static Factory ”; Previous Next Spring provides an option to inject dependency using factory-method along with factory-bean attributes in case of non-static factory methods. Example The following example shows a class TextEditor that can only be dependency-injected using pure setter-based injection. Let”s update the project created in Spring DI – Create Project chapter. We”re adding following files − TextEditor.java − A class containing a SpellChecker as dependency. SpellChecker.java − A dependency class. MainApp.java − Main application to run and test. Here is the content of TextEditor.java file − package com.tutorialspoint; public class TextEditor { private SpellChecker spellChecker; private String name; public void setSpellChecker( SpellChecker spellChecker ){ this.spellChecker = spellChecker; } public SpellChecker getSpellChecker() { return spellChecker; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void spellCheck() { spellChecker.checkSpelling(); } } Following is the content of another dependent class file SpellChecker.java − This class constructor is private. So its object can not be created directly using new operator by other object. It has a non-static factory method to get an instance. package com.tutorialspoint; public class SpellChecker { private SpellChecker(){ System.out.println(“Inside SpellChecker constructor.” ); } public SpellChecker getInstance() { System.out.println(“Inside SpellChecker getInstance.” ); return new SpellChecker(); } public void checkSpelling(){ System.out.println(“Inside checkSpelling.” ); } } Following is the content of the MainApp.java file − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“applicationcontext.xml”); TextEditor te = (TextEditor) context.getBean(“textEditor”); te.spellCheck(); } } Following is the configuration file applicationcontext.xml which has configuration for autowiring byName − <?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-3.0.xsd”> <!– Definition for textEditor bean –> <bean id = “textEditor” class = “com.tutorialspoint.TextEditor” autowire = “byName”> <property name = “name” value = “Generic Text Editor” /> </bean> <bean id = “spellCheckFactory” class = “com.tutorialspoint.SpellChecker”></bean> <!– Definition for spellChecker bean –> <bean id = “spellChecker” class = “com.tutorialspoint.SpellChecker” factory-method=”getInstance”>< factory-bean=”spellCheckFactory”/bean> </beans> Output Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − Inside SpellChecker constructor. Inside SpellChecker getInstance. Inside SpellChecker constructor. Inside checkSpelling. Print Page Previous Next Advertisements ”;

Spring SpEL – Environment Setup

Spring SpEL – Environment Setup ”; Previous Next This chapter will guide you on how to prepare a development environment to start your work with Spring Framework. It will also teach you how to set up JDK, Maven and Eclipse on your machine before you set up Spring Framework − Setup Java Development Kit (JDK) You can download the latest version of SDK from Oracle”s Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and have installed the JDK in C:jdk-11.0.11, you would have to put the following line in your C:autoexec.bat file. set PATH=C:jdk-11.0.11;%PATH% set JAVA_HOME=C:jdk-11.0.11 Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-11.0.11 and you use the C shell, you will have to put the following into your .cshrc file. setenv PATH /usr/local/jdk-11.0.11/bin:$PATH setenv JAVA_HOME /usr/local/jdk-11.0.11 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE. Setup Eclipse IDE All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine. To install Eclipse IDE, download the latest Eclipse binaries from www.eclipse.org/downloads. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately. Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe %C:eclipseeclipse.exe Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $/usr/local/eclipse/eclipse After a successful startup, if everything is fine then it should display the following result − Set Maven In this tutorial, we are using maven to run and build the spring based examples. Follow the Maven – Environment Setup to install maven. We”ll cover each and every topic in next chapters. Print Page Previous Next Advertisements ”;