Spring SpEL – Array

Spring SpEL – Array ”; Previous Next SpEL expression supports accessing arrays and using their indexes of an array of an object. We can access nested arrays as well within an SpEL expression. 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. Dept.java − Department 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[] awards; public String[] getAwards() { return awards; } public void setAwards(String[] awards) { this.awards = awards; } } Here is the content of Dept.java file − package com.tutorialspoint; public class Dept { private Employee[] employees; public Employee[] getEmployees() { return employees; } public void setEmployees(Employee[] employees) { this.employees = employees; } } Here is the content of MainApp.java file − package com.tutorialspoint; import java.text.ParseException; import java.text.SimpleDateFormat; 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(); String[] awards = {“Star of the Month”, “Champion”, “Accelerator”}; employee.setAwards(awards); Employee[] employees = { employee }; Dept dept = new Dept(); dept.setEmployees(employees); EvaluationContext employeeContext = new StandardEvaluationContext(employee); // evaluates to “Accelerator” String award = parser.parseExpression(“awards[2]”).getValue(employeeContext, String.class); System.out.println(award); EvaluationContext deptContext = new StandardEvaluationContext(dept); // evaluates to “Champion” award = parser.parseExpression(“employees[0].awards[1]”).getValue(deptContext, String.class); System.out.println(award); } } Output Accelerator Champion Print Page Previous Next Advertisements ”;

Spring MVC – Home

Spring MVC Tutorial PDF Version Quick Guide Resources Job Search Discussion Spring MVC framework is an open source Java platform that provides comprehensive infrastructure support for developing robust Java based Web applications very easily and very rapidly. Spring framework was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003. This tutorial has been written based on Spring Framework version 5.1.34 released in Dec 2021. Audience This tutorial is designed for Java programmers with a need to understand the Spring MVC framework in detail along with its architecture and actual usage. This tutorial will bring you at intermediate level of expertise from where you can take yourself at higher level of expertise. Prerequisites Before proceeding with this tutorial you should have a good understanding of Java programming language. A basic understanding of Eclipse IDE is also required because all the examples have been compiled using Eclipse IDE. Questions and Answers Spring Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations – Study Spring Questions and Answers 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 ”;

Spring SpEL – Expression Interface

Spring SpEL – Expression Interface ”; Previous Next ExpressionParser is the main interface of Spring SpEL which helps parsing expression strings into compiled expressions. These compiled expressions can be evaluated and supports parsing templates as well as standard expression string. Syntax Following is an example of creating an ExpressionParser and using its object to get a value. ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression(“”Welcome to Tutorialspoint””); String message = (String) exp.getValue(); It should print the result as follows − Welcome to Tutorialspoint ExpressionParser − An interface responsible to parse an expression string. Expression − An interface responsible to evaluate an expression string. Exceptions − ParseException and EvaluationException can be thrown during parseExpression and getValue method invokation. SpEL supports calling methods, calling constructors and accessing properties. Following example shows the various use cases. 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 − MainApp.java − Main application to run and test. Here is the content of MainApp.java file − package com.tutorialspoint; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; public class MainApp { public static void main(String[] args) { ExpressionParser parser = new SpelExpressionParser(); // parse a plain text Expression exp = parser.parseExpression(“”Welcome to tutorialspoint””); String message = (String) exp.getValue(); System.out.println(message); // invoke a method exp = parser.parseExpression(“”Welcome to tutorialspoint”.concat(”!”)”); message = (String) exp.getValue(); System.out.println(message); // get a property exp = parser.parseExpression(“”Welcome to tutorialspoint”.bytes”); byte[] bytes = (byte[]) exp.getValue(); System.out.println(bytes.length); // get nested properties exp = parser.parseExpression(“”Welcome to tutorialspoint”.bytes.length”); int length = (Integer) exp.getValue(); System.out.println(length); //Calling constructor exp = parser.parseExpression(“new String(”Welcome to tutorialspoint”).toUpperCase()”); message = (String) exp.getValue(); System.out.println(message); } } Output Welcome to tutorialspoint Welcome to tutorialspoint! 25 25 WELCOME TO TUTORIALSPOINT Print Page Previous Next Advertisements ”;

Spring ORM – Run & Test EclipseLink

Spring ORM – Test EclipseLink ”; Previous Next Now in eclipse, right click on the MainApp.java, select Run As context menu, and select Java Application. Check the console logs in the eclipse. You can see the below logs − … Sep 28, 2021 8:56:13 AM org.springframework.orm.jpa.LocalEntityManagerFactoryBean createNativeEntityManagerFactory INFO: Building JPA EntityManagerFactory for persistence unit ”EclipseLink_JPA” [EL Config]: metadata: 2021-09-28 08:56:13.763–ServerSession(712627377)–Thread(Thread[main,5,main])–The access type for the persistent class [class com.tutorialspoint.jpa.entity.Employee] is set to [FIELD]. [EL Config]: metadata: 2021-09-28 08:56:13.787–ServerSession(712627377)–Thread(Thread[main,5,main])–The alias name for the entity class [class com.tutorialspoint.jpa.entity.Employee] is being defaulted to: Employee. [EL Config]: metadata: 2021-09-28 08:56:13.802–ServerSession(712627377)–Thread(Thread[main,5,main])–The column name for element [id] is being defaulted to: ID. Sep 28, 2021 8:56:13 AM org.springframework.orm.jpa.LocalEntityManagerFactoryBean buildNativeEntityManagerFactory INFO: Initialized JPA EntityManagerFactory for persistence unit ”EclipseLink_JPA” [EL Info]: 2021-09-28 08:56:14.102–ServerSession(712627377)–Thread(Thread[main,5,main])–EclipseLink, version: Eclipse Persistence Services – 2.5.1.v20130918-f2b9fc5 [EL Fine]: connection: 2021-09-28 08:56:14.403–Thread(Thread[main,5,main])–Detected database platform: org.eclipse.persistence.platform.database.MySQLPlatform [EL Config]: connection: 2021-09-28 08:56:14.423–ServerSession(712627377)–Connection(741883443)–Thread(Thread[main,5,main])–connecting(DatabaseLogin( platform=>MySQLPlatform user name=> “root” datasource URL=> “jdbc:mysql://localhost:3306/tutorialspoint?useSSL=false” )) [EL Config]: connection: 2021-09-28 08:56:14.469–ServerSession(712627377)–Connection(2134915053)–Thread(Thread[main,5,main])–Connected: jdbc:mysql://localhost:3306/tutorialspoint?useSSL=false User: root@localhost Database: MySQL Version: 8.0.23 Driver: MySQL Connector/J Version: mysql-connector-java-8.0.13 (Revision: 66459e9d39c8fd09767992bc592acd2053279be6) [EL Info]: connection: 2021-09-28 08:56:14.539–ServerSession(712627377)–Thread(Thread[main,5,main])–file:/F:/Workspace/springorm/target/classes/_EclipseLink_JPA login successful [EL Fine]: sql: 2021-09-28 08:56:14.602–ServerSession(712627377)–Connection(2134915053)–Thread(Thread[main,5,main])–CREATE TABLE Employees (ID INTEGER AUTO_INCREMENT NOT NULL, DESIGNATION VARCHAR(255), NAME VARCHAR(255), SALARY DOUBLE, PRIMARY KEY (ID)) [EL Fine]: sql: 2021-09-28 08:56:14.836–ClientSession(181326224)–Connection(2134915053)–Thread(Thread[main,5,main])–INSERT INTO Employees (DESIGNATION, NAME, SALARY) VALUES (?, ?, ?) bind => [Technical Manager, Julie, 10000.0] [EL Fine]: sql: 2021-09-28 08:56:14.855–ClientSession(181326224)–Connection(2134915053)–Thread(Thread[main,5,main])–SELECT LAST_INSERT_ID() [EL Fine]: sql: 2021-09-28 08:56:14.883–ClientSession(1573125303)–Connection(2134915053)–Thread(Thread[main,5,main])–INSERT INTO Employees (DESIGNATION, NAME, SALARY) VALUES (?, ?, ?) bind => [Senior Manager, Robert, 20000.0] [EL Fine]: sql: 2021-09-28 08:56:14.885–ClientSession(1573125303)–Connection(2134915053)–Thread(Thread[main,5,main])–SELECT LAST_INSERT_ID() [EL Fine]: sql: 2021-09-28 08:56:14.893–ClientSession(2054787417)–Connection(2134915053)–Thread(Thread[main,5,main])–INSERT INTO Employees (DESIGNATION, NAME, SALARY) VALUES (?, ?, ?) bind => [Software Engineer, Anil, 5000.0] [EL Fine]: sql: 2021-09-28 08:56:14.896–ClientSession(2054787417)–Connection(2134915053)–Thread(Thread[main,5,main])–SELECT LAST_INSERT_ID() [EL Fine]: sql: 2021-09-28 08:56:14.929–ServerSession(712627377)–Connection(2134915053)–Thread(Thread[main,5,main])–SELECT ID, DESIGNATION, NAME, SALARY FROM Employees Id : 1 Name : Julie Salary = 10000.0 Designation = Technical Manager Id : 2 Name : Robert Salary = 20000.0 Designation = Senior Manager Id : 3 Name : Anil Salary = 5000.0 Designation = Software Engineer Sep 28, 2021 8:56:14 AM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@5383967b: startup date [Tue Sep 28 08:56:12 IST 2021]; root of context hierarchy [EL Config]: connection: 2021-09-28 08:56:14.935–ServerSession(712627377)–Connection(2134915053)–Thread(Thread[main,5,main])–disconnect Sep 28, 2021 8:56:14 AM org.springframework.orm.jpa.LocalEntityManagerFactoryBean destroy INFO: Closing JPA EntityManagerFactory for persistence unit ”EclipseLink_JPA” [EL Info]: connection: 2021-09-28 08:56:14.936–ServerSession(712627377)–Thread(Thread[main,5,main])–file:/F:/Workspace/springorm/target/classes/_EclipseLink_JPA logout successful [EL Config]: connection: 2021-09-28 08:56:14.936–ServerSession(712627377)–Connection(741883443)–Thread(Thread[main,5,main])–disconnect Here project is built and run using spring configurations. A table Employee is created and have three records. You can verify the same using MySQL console. Enter password: ******** Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 41 Server version: 8.0.23 MySQL Community Server – GPL Copyright (c) 2000, 2021, Oracle and/or its affiliates. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type ”help;” or ”h” for help. Type ”c” to clear the current input statement. mysql> use tutorialspoint; Database changed mysql> select * from employees; +—-+——————-+——–+——–+ | id | DESIGNATION | NAME | SALARY | +—-+——————-+——–+——–+ | 1 | Technical Manager | Julie | 10000 | | 2 | Senior Manager | Robert | 20000 | | 3 | Software Engineer | Anil | 5000 | +—-+——————-+——–+——–+ 3 rows in set (0.00 sec) mysql> Print Page Previous Next Advertisements ”;

Spring ORM – Useful Resources

Spring ORM – Useful Resources ”; Previous Next The following resources contain additional information on Spring ORM. Please use them to get more in-depth knowledge on this topic. Useful Links on Spring ORM Spring Source − Find latest news about Spring Framework, download section and all about Spring. Spring Framework Documentation − Complete Spring Framework reference covering all the modules. Oracle”s Site on JDBC − Sun Developer Network giving link on JDBC material. MySQL Connector/J − MySQL Connector/J is the official JDBC driver for MySQL. The JavaTM Tutorials − The Java Tutorials are practical guides for programmers who want to use the Java programming language to create applications. JavaTM 2 SDK, Standard Edition − Official site for JavaTM 2 SDK, Standard Edition Free Java Download − Download Java for your desktop computer now! Java Technology Reference − Sun Microsystem”s official website listing down all the API documentation, latest Java Technologies, Books and other resource. Useful Books on Spring ORM To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

Spring WS – Discussion

Discuss Spring Web Services ”; Previous Next Spring Web Services (Spring-WS) is one of the project developed by the Spring Community. Its prime focus is to create document-driven Web Services. The Spring Web Services project facilitates contract-first SOAP service development, provides multiple ways to create flexible web services, which can manipulate XML payloads in multiple ways. Being Spring based, Spring Web Services uses Spring Concepts like Dependency Injection and Configurations seamlessly. Spring-WS requires Spring 3.0 version. Spring Framework was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003. This tutorial has been written based on the Spring Framework Version 4.1.6 released in March 2015. Print Page Previous Next Advertisements ”;