Spring ORM – Environment Setup

Spring ORM – 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 − Install MySQL Database The most important thing you will need, of course is an actual running database with a table that you can query and modify. MySQL DB − MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation. In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier. Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. For the purpose of this tutorial we will assume that you have installed the driver at C:Program FilesMySQLmysql-connector-java-5.1.8. Accordingly, set CLASSPATH variable to C:Program FilesMySQLmysql-connector-java-5.1.8mysql-connector-java-5.1.8-bin.jar. Your driver version may vary based on your installation. Set Database Credential When we install MySQL database, its administrator ID is set to root and it gives provision to set a password of your choice. Using root ID and password you can either create another user ID and password, or you can use root ID and password for your JDBC application. There are various database operations like database creation and deletion, which would need administrator ID and password. If you do not have sufficient privilege to create new users, then you can ask your Database Administrator (DBA) to create a user ID and password for you. Create Database To create the TUTORIALSPOINT database, use the following steps − Step 1 Open a Command Prompt and change to the installation directory as follows − C:> C:>cd Program FilesMySQLbin C:Program FilesMySQLbin> Note − The path to mysqld.exe may vary depending on the install location of MySQL on your system. You can also check documentation on how to start and stop your database server. Step 2 Start the database server by executing the following command, if it is already not running. C:Program FilesMySQLbin>mysqld C:Program FilesMySQLbin> Step 3 Create the TUTORIALSPOINT database by executing the following command − C:Program FilesMySQLbin> create database TUTORIALSPOINT; Note − The path to mysqld.exe may vary depending on the install location of MySQL on your system. You can also check documentation on how to start and stop your database server. For a complete understanding on MySQL database, study the MySQL Tutorial. 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. Print Page Previous Next Advertisements ”;

Spring SpEL – Useful Resources

Spring SpEL – Useful Resources ”; Previous Next The following resources contain additional information on Spring SpEL. Please use them to get more in-depth knowledge on this topic. Useful Links on Spring SpEL SpEL −Spring Expression Language Documentation. 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. To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

Spring SpEL – Elvis Operator

Spring SpEL – Elvis Operator ”; Previous Next SpEL expression supports Elvis operator which is a short form of ternary operator. // Using ternary operator String result = name != null ? name: “unknown”; // Using Elvis Operator result = name?:”unknown”; 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 String name; 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 java.text.ParseException; 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(); EvaluationContext employeeContext = new StandardEvaluationContext(employee); // Evaluates to “unknown” String result = parser.parseExpression(“name?:”unknown””).getValue(employeeContext, String.class); System.out.println(result); employee.setName(“Mahesh”); // Evaluates to “Mahesh” result = parser.parseExpression(“name?:”unknown””).getValue(employeeContext, String.class); System.out.println(result); } } Output unknown Mahesh Print Page Previous Next Advertisements ”;

Spring SpEL – Collection Selection

Spring SpEL – Collection Selection ”; Previous Next SpEL expression supports Collection Selection which is a very powerful expression allowing to transform source collection into another by selecting the entries from the source collection. Syntax ?[selectionExpresion] Following example shows the usage. List<Employee> list = (List<Employee>) parser.parseExpression(“employees.?[country == ”USA”]”).getValue(deptContext); Here SpEL will return only those employees from the list of employees whose country is USA. 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 name; private String country; public Employee(String name, String country) { this.name = name; this.country = country; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String toString() { return “[” +name+ “, “+country + “]”; } } Here is the content of Dept.java file − package com.tutorialspoint; import java.util.List; public class Dept { private List<Employee> employees; public List<Employee> getEmployees() { return employees; } public void setEmployees(List<Employee> employees) { this.employees = employees; } } Here is the content of MainApp.java file − package com.tutorialspoint; import java.text.ParseException; import java.util.ArrayList; import java.util.List; 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 employee1 = new Employee(“Robert”, “USA”); Employee employee2 = new Employee(“Julie”, “USA”); Employee employee3 = new Employee(“Ramesh”, “India”); List<Employee> employees = new ArrayList<Employee>(); employees.add(employee1); employees.add(employee2); employees.add(employee3); Dept dept = new Dept(); dept.setEmployees(employees); EvaluationContext deptContext = new StandardEvaluationContext(dept); // Select list of employees who are living in USA List<Employee> list = (List<Employee>) parser.parseExpression(“employees.?[country == ”USA”]”).getValue(deptContext); System.out.println(list); } } Output [[Robert, USA], [Julie, USA]] Print Page Previous Next Advertisements ”;

Spring SpEL – Variables

Spring SpEL – Variables ”; Previous Next SpEL expression allows to create and use variables specific to expression using #variable-name syntax. A variable is set using setVariable on EvaluationContext. There are two types of inbuilt variables as well, #this and #root. #this variable always refers to current evaluation object where as #root variable refers to the root object of the evaluation context. Syntax context.setVariable(“newName”, “Mahesh Kumar”); 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 String name; private String country; public Employee(String name, String country) { this.name = name; this.country = country; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String toString() { return “[” +name+ “, “+country + “]”; } } Here is the content of MainApp.java file − package com.tutorialspoint; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; 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(“Mahesh”, “INDIA”); EvaluationContext context = new StandardEvaluationContext(employee); context.setVariable(“newName”, “Mahesh Parashar”); parser.parseExpression(“Name = #newName”).getValue(context); // Evaluate to “Mahesh Parashar” System.out.println(employee.getName()); List<Integer> primes = new ArrayList<Integer>(); primes.addAll(Arrays.asList(2,3,5,7,11,13,17)); context.setVariable(“primes”,primes); List<Integer> filteredList = (List<Integer>) parser.parseExpression(“#primes.?[#this>10]”).getValue(context); // Evaluate to [11, 13, 17], prime numbers greater than 10 System.out.println(filteredList); } } Output Mahesh Parashar [11, 13, 17] 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 ”;

Parameterizable View Controller

Spring MVC – Parameterizable View Controller Example ”; Previous Next The following example shows how to use the Parameterizable View Controller method of a Multi Action Controller using the Spring Web MVC framework. The Parameterizable View allows mapping a webpage with a request. package com.tutorialspoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; public class UserController extends MultiActionController{ public ModelAndView home(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Home”); return model; } } <bean class=”org.springframework.web.servlet.handler.SimpleUrlHandlerMapping”> <property name=”mappings”> <value> index.htm=userController </value> </property> </bean> <bean id=”userController” class=”org.springframework.web.servlet.mvc.ParameterizableViewController”> <property name=”viewName” value=”user”/> </bean> For example, using the above configuration, if URI. /index.htm is requested, DispatcherServlet will forward the request to the UserController controller with viewName set as user.jsp. To start with it, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using 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 a Java class UserController under the com.tutorialspoint package. 3 Create a view file user.jsp under the jsp sub-folder. 4 The final step is to create the content of the source and configuration files and export the application as explained below. UserController.java package com.tutorialspoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; public class UserController extends MultiActionController{ public ModelAndView home(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Home”); return model; } } 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” 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”> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/”/> <property name = “suffix” value = “.jsp”/> </bean> <bean class = “org.springframework.web.servlet.handler.SimpleUrlHandlerMapping”> <property name = “mappings”> <value> index.htm = userController </value> </property> </bean> <bean id = “userController” class = “org.springframework.web.servlet.mvc.ParameterizableViewController”> <property name = “viewName” value=”user”/> </bean> </beans> user.jsp <%@ page contentType=”text/html; charset=UTF-8″ %> <html> <head> <title>Hello World</title> </head> <body> <h2>Hello World</h2> </body> </html> 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 the TestWeb.war file in Tomcat”s webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Now, try a URL – http://localhost:8080/TestWeb/index.htm and you will see the following screen, if everything is fine with the Spring Web Application. Print Page Previous Next Advertisements ”;

Internal Resource View Resolver

Spring MVC – Internal Resource View Resolver Example ”; Previous Next The InternalResourceViewResolver is used to resolve the provided URI to actual URI. The following example shows how to use the InternalResourceViewResolver using the Spring Web MVC Framework. The InternalResourceViewResolver allows mapping webpages with requests. package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.ui.ModelMap; @Controller @RequestMapping(“/hello”) public class HelloController{ @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/”/> <property name = “suffix” value = “.jsp”/> </bean> For example, using the above configuration, if URI /hello is requested, DispatcherServlet will forward the request to the prefix + viewname + suffix = /WEB-INF/jsp/hello.jsp. To start with, let us have a working Eclipse IDE in place and then consider 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.tutorialspointas explained in the Spring MVC – Hello World Example chapter. 2 Create a Java classes HelloController under the com.tutorialspointpackage. 3 Create a view file hello.jsp under jsp sub-folder. 4 The final step is to create the content of the source and configuration files and export the application as explained below. HelloController.java package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.ui.ModelMap; @Controller @RequestMapping(“/hello”) public class HelloController{ @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } 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” 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”> <context:component-scan base-package = “com.tutorialspoint” /> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> </beans> hello.jsp <%@ page contentType = “text/html; charset = UTF-8″ %> <html> <head> <title>Hello World</title> </head> <body> <h2>${message}</h2> </body> </html> 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 the TestWeb.war file in Tomcat”s webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try to access the URL – http://localhost:8080/TestWeb/hello and if everything is fine with the Spring Web Application, we will see the following screen. Print Page Previous Next Advertisements ”;

Spring SpEL – Ternary Operator

Spring SpEL – Ternary Operator ”; Previous Next SpEL expression supports ternary operator to perform if-then-else logic. 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 org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; public class MainApp { public static void main(String[] args) throws ParseException { ExpressionParser parser = new SpelExpressionParser(); String result = parser.parseExpression(“true ? ”Yes” : ”No””).getValue(String.class); System.out.println(result); result = parser.parseExpression(“false ? ”Yes” : ”No””).getValue(String.class); System.out.println(result); } } Output Yes No Print Page Previous Next Advertisements ”;