Spring Boot – Flyway Database

Spring Boot – Flyway Database ”; Previous Next Flyway is a version control application to evolve your Database schema easily and reliably across all your instances. To learn more about Flyway, you can use the link − www.flywaydb.org Many software projects use relational databases. This requires the handling of database migrations, also often called schema migrations. In this chapter, you are going to learn in detail about how to configure Flyway database in your Spring Boot application. Configuring Flyway Database First, download the Spring Boot project from Spring Initializer page www.start.spring.io and choose the following dependencies − Spring Boot Starter Web Flyway MySQL JDBC Maven users can add the following dependencies in pom.xml file. <dependency> <groupId>org.flywaydb</groupId> <artifactId>flyway-core</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> Gradle users can add the following dependencies in build.gradle file. compile(”org.flywaydb:flyway-core”) compile(”org.springframework.boot:spring-boot-starter-jdbc”) compile(”org.springframework.boot:spring-boot-starter-web”) compile(”mysql:mysql-connector-java”) In application properties, we need to configure the database properties for creating a DataSource and also flyway properties we need to configure in application properties. For properties file users, add the below properties in the application.properties file. spring.application.name = flywayapp spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect=true spring.datasource.username = root spring.datasource.password = root spring.datasource.testOnBorrow = true spring.datasource.testWhileIdle = true spring.datasource.timeBetweenEvictionRunsMillis = 60000 spring.datasource.minEvictableIdleTimeMillis = 30000 spring.datasource.validationQuery = SELECT 1 spring.datasource.max-active = 15 spring.datasource.max-idle = 10 spring.datasource.max-wait = 8000 flyway.url = jdbc:mysql://localhost:3306/mysql flyway.schemas = USERSERVICE flyway.user = root flyway.password = root YAML users can add the following properties in application.yml file. spring: application: name: flywayapp datasource: driverClassName: com.mysql.jdbc.Driver url: “jdbc:mysql://localhost:3306/USERSERVICE?autoreconnect=true” password: “root” username: “root” testOnBorrow: true testWhileIdle: true timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 30000 validationQuery: SELECT 1 max-active: 15 max-idle: 10 max-wait: 8000 flyway: url: jdbc:mysql://localhost:3306/mysql schemas: USERSERVICE user: “root” password: “root” Now, create a SQL file under the src/main/resources/db/migration directory. Name the SQL file as “V1__Initial.sql” CREATE TABLE USERS (ID INT AUTO_INCREMENT PRIMARY KEY, USERID VARCHAR(45)); INSERT INTO USERS (ID, USERID) VALUES (1, ”tutorialspoint.com”); The main Spring Boot application class file code is given below − package com.tutorialspoint.flywayapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class FlywayappApplication { public static void main(String[] args) { SpringApplication.run(FlywayappApplication.class, args); } } The complete build configuration file is given below. Maven – pom.xml <?xml version = “1.0” encoding = “UTF-8”?> <project xmlns = “http://maven.apache.org/POM/4.0.0” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>flywayapp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>flywayapp</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.flywaydb</groupId> <artifactId>flyway-core</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle – build.gradle buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile(”org.flywaydb:flyway-core”) compile(”org.springframework.boot:spring-boot-starter-jdbc”) compile(”org.springframework.boot:spring-boot-starter-web”) compile(”mysql:mysql-connector-java”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below − For Maven, you can use the command shown here − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command shown here − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Now, run the JAR file by using the following command − java –jar <JARFILE> Now, Tomcat started on the port 8080 and in the console window you can see the flyway database logs as shown here. You can now go to the database and do the select queries. Print Page Previous Next Advertisements ”;

Spring MVC – Useful Resources

Spring MVC – Useful Resources ”; Previous Next The following resources contain additional information on Spring MVC. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Learn ASP.Net MVC and Entity Framework (Database First) Most Popular 20 Lectures 5 hours Trevoir Williams More Detail ASP.Net Core MVC Training Course 53 Lectures 3 hours Skillbakery More Detail Spring MVC Essentials: A Primary Course for Java Spring MVC 25 Lectures 3.5 hours TELCOMA Global More Detail .Net Developer Course Using ASP.NET MVC Core, C#, OOP, SQL Entity Framework Best Seller 89 Lectures 7.5 hours Mustafa Radaideh More Detail Spring MVC With Spring Boot and Project 94 Lectures 8 hours Packt Publishing More Detail ASP.NET Core MVC Webforms – A Project method from scratch 70 Lectures 6 hours Metla Sudha Sekhar More Detail Print Page Previous Next Advertisements ”;

Struts2 – Localization

Struts2 – Localization, internationalization (i18n) ”; Previous Next Internationalization (i18n) is the process of planning and implementing products and services so that they can easily be adapted to specific local languages and cultures, a process called localization. The internationalization process is called translation or localization enablement. Internationalization is abbreviated i18n because the word starts with the letter “i” and ends with “n”, and there are 18 characters between the first i and the last n. Struts2 provides localization, i.e., internationalization (i18n) support through resource bundles, interceptors and tag libraries in the following places − The UI Tags Messages and Errors. Within action classes. Resource Bundles Struts2 uses resource bundles to provide multiple language and locale options to the users of the web application. You don”t need to worry about writing pages in different languages. All you have to do is to create a resource bundle for each language that you want. The resource bundles will contain titles, messages, and other text in the language of your user. Resource bundles are the file that contains the key/value pairs for the default language of your application. The simplest naming format for a resource file is − bundlename_language_country.properties Here, bundlename could be ActionClass, Interface, SuperClass, Model, Package, Global resource properties. Next part language_country represents the country locale for example, Spanish (Spain) locale is represented by es_ES, and English (United States) locale is represented by en_US etc. where you can skip country part which is optional. When you reference a message element by its key, Struts framework searches for a corresponding message bundle in the following order − ActionClass.properties Interface.properties SuperClass.properties model.properties package.properties struts.properties global.properties To develop your application in multiple languages, you should maintain multiple property files corresponding to those languages/locale and define all the content in terms of key/value pairs. For example, if you are going to develop your application for US English (Default), Spanish, and French, then you would have to create three properties files. Here I will use global.properties file only, you can also make use of different property files to segregate different type of messages. global.properties − By default English (United States) will be applied global_fr.properties − This will be used for Franch locale. global_es.properties − This will be used for Spanish locale. Access the messages There are several ways to access the message resources, including getText, the text tag, key attribute of UI tags, and the i18n tag. Let us see them in brief − To display i18n text, use a call to getText in the property tag, or any other tag, such as the UI tags as follows − <s:property value = “getText(”some.key”)” /> The text tag retrieves a message from the default resource bundle, i.e., struts.properties <s:text name = “some.key” /> The i18n tag pushes an arbitrary resource bundle on to the value stack. Other tags within the scope of the i18n tag can display messages from that resource bundle− <s:i18n name = “some.package.bundle”> <s:text name = “some.key” /> </s:i18n> The key attribute of most UI tags can be used to generate a message from a resource bundle − <s:textfield key = “some.key” name = “textfieldName”/> Localization Example Let us target to create index.jsp from the previous chapter in multiple languages. Same file would be written as follows − <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <title>Employee Form with Multilingual Support</title> </head> <body> <h1><s:text name = “global.heading”/></h1> <s:url id = “indexEN” namespace=”/” action = “locale” > <s:param name = “request_locale” >en</s:param> </s:url> <s:url id = “indexES” namespace=”/” action = “locale” > <s:param name = “request_locale” >es</s:param> </s:url> <s:url id = “indexFR” namespace=”/” action = “locale” > <s:param name = “request_locale” >fr</s:param> </s:url> <s:a href=”%{indexEN}” >English</s:a> <s:a href=”%{indexES}” >Spanish</s:a> <s:a href=”%{indexFR}” >France</s:a> <s:form action = “empinfo” method = “post” namespace = “/”> <s:textfield name = “name” key = “global.name” size = “20” /> <s:textfield name = “age” key = “global.age” size = “20” /> <s:submit name = “submit” key = “global.submit” /> </s:form> </body> </html> We will create success.jsp file which will be invoked in case defined action returns SUCCESS. <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <title>Success</title> </head> <body> <s:property value = “getText(”global.success”)” /> </body> </html> Here we would need to create the following two actions. (a) First action a to take care of Locale and display same index.jsp file with different language (b) Another action is to take care of submitting form itself. Both the actions will return SUCCESS, but we will take different actions based on return values because our purpose is different for both the actions Action to take care of Locale package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; public class Locale extends ActionSupport { public String execute() { return SUCCESS; } } Action To Submit The Form package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; public class Employee extends ActionSupport{ private String name; private int age; public String execute() { return SUCCESS; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } Now let us create the following three global.properties files and put the in CLASSPATH − global.properties global.name = Name global.age = Age global.submit = Submit global.heading = Select Locale global.success = Successfully authenticated global_fr.properties global.name = Nom d”utilisateur global.age = l”âge global.submit = Soumettre des global.heading = Sé lectionnez Local global.success = Authentifi é avec succès global_es.properties global.name = Nombre de usuario global.age = Edad global.submit = Presentar global.heading = seleccionar la configuracion regional global.success = Autenticado correctamente We will create our struts.xml with two actions as follows − <?xml version = “1.0” Encoding = “UTF-8”?> <!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” “http://struts.apache.org/dtds/struts-2.0.dtd”> <struts> <constant name

Struts2 – Environment Setup

Struts 2 – Environment Setup ”; Previous Next Our first task is to get a minimal Struts 2 application running. This chapter will guide you on how to prepare a development environment to start your work with Struts 2. I assume that you already have JDK (5+), Tomcat and Eclipse installed on your machine. If you do not have these components installed, then follow the given steps on fast track − Step 1 – 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 installed the SDK in C:jdk1.5.0_20, you should be inputting the following line in your C:autoexec.bat file. set PATH = C:jdk1.5.0_20bin;%PATH% set JAVA_HOME = C:jdk1.5.0_20 Alternatively, on Windows NT/2000/XP − You can right-click on My Computer, Select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you would put the following into your .cshrc file. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you would put the following into your .cshrc file. setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.5.0_20 Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java, otherwise do proper setup as per the given document of IDE. Step 2 – Setup Apache Tomcat You can download the latest version of Tomcat from https://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:apache-tomcat-6.0.33 on windows, or /usr/local/apachetomcat-6.0.33 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations. You can start Tomcat by executing the following commands on windows machine, or you can simply double click on startup.bat %CATALINA_HOME%binstartup.bat or C:apache-tomcat-6.0.33binstartup.bat Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine − $CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-6.0.33/bin/startup.sh After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine, then it should display the following result − Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat website: https://tomcat.apache.org/ Tomcat can be stopped by executing the following commands on windows machine − %CATALINA_HOME%binshutdown or C:apache-tomcat-5.5.29binshutdown Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine − $CATALINA_HOME/bin/shutdown.sh or /usr/local/apache-tomcat-5.5.29/bin/shutdown.sh Step 3 – Setup Eclipse (IDE) All the examples in this tutorial are written using Eclipse IDE. I suggest that, you have the latest version of Eclipse installed in your machine. To install Eclipse Download the latest Eclipse binaries from https://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, it should display the following result − Step 4 – Setup Struts2 Libraries Now if everything is fine, then you can proceed to setup your Struts2 framemwork. Following are the simple steps to download and install Struts2 on your machine. Make a choice whether you want to install Struts2 on Windows, or Unix and then proceed to the next step to download .zip file for windows and .tz file for Unix. Download the latest version of Struts2 binaries from https://struts.apache.org/download.cgi. At the time of writing this tutorial, I downloaded struts-2.0.14-all.zip and when you unzip the downloaded file it will give you directory structure inside C:struts-2.2.3 as follows. Second step is to extract the zip file in any location, I downloaded & extracted struts-2.2.3-all.zip in c: folder on my Windows 7 machine so that I have all the jar files into C:struts-2.2.3lib. Make sure you set your CLASSPATH variable properly otherwise you will face problem while running your application. Print Page Previous Next Advertisements ”;

Struts2 – File Uploads

Struts 2 – File Uploads ”; Previous Next The Struts 2 framework provides built-in support for processing file upload using “Form-based File Upload in HTML”. When a file is uploaded, it will typically be stored in a temporary directory and they should be processed or moved by your Action class to a permanent directory to ensure the data is not lost. Note − Servers may have a security policy in place that prohibits you from writing to directories other than the temporary directory and the directories that belong to your web application. File uploading in Struts is possible through a pre-defined interceptor called FileUpload interceptor which is available through the org.apache.struts2.interceptor.FileUploadInterceptor class and included as part of thedefaultStack. Still you can use that in your struts.xml to set various paramters as we will see below. Create View Files Let us start with creating our view which will be required to browse and upload a selected file. So let us create an index.jsp with plain HTML upload form that allows the user to upload a file − <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <title>File Upload</title> </head> <body> <form action = “upload” method = “post” enctype = “multipart/form-data”> <label for = “myFile”>Upload your file</label> <input type = “file” name = “myFile” /> <input type = “submit” value = “Upload”/> </form> </body> </html> There is couple of points worth noting in the above example. First, the form”s enctype is set to multipart/form-data. This should be set so that file uploads are handled successfully by the file upload interceptor. The next point noting is the form”s action method upload and the name of the file upload field – which is myFile. We need this information to create the action method and the struts configuration. Next, let us create a simple jsp file success.jsp to display the outcome of our file upload in case it becomes success. <%@ page contentType = “text/html; charset = UTF-8” %> <%@ taglib prefix = “s” uri = “/struts-tags” %> <html> <head> <title>File Upload Success</title> </head> <body> You have successfully uploaded <s:property value = “myFileFileName”/> </body> </html> Following will be the result file error.jsp in case there is some error in uploading the file − <%@ page contentType = “text/html; charset = UTF-8” %> <%@ taglib prefix = “s” uri = “/struts-tags” %> <html> <head> <title>File Upload Error</title> </head> <body> There has been an error in uploading the file. </body> </html> Create Action Class Next, let us create a Java class called uploadFile.java which will take care of uploading file and storing that file at a secure location − package com.tutorialspoint.struts2; import java.io.File; import org.apache.commons.io.FileUtils; import java.io.IOException; import com.opensymphony.xwork2.ActionSupport; public class uploadFile extends ActionSupport { private File myFile; private String myFileContentType; private String myFileFileName; private String destPath; public String execute() { /* Copy file to a safe location */ destPath = “C:/apache-tomcat-6.0.33/work/”; try { System.out.println(“Src File name: ” + myFile); System.out.println(“Dst File name: ” + myFileFileName); File destFile = new File(destPath, myFileFileName); FileUtils.copyFile(myFile, destFile); } catch(IOException e) { e.printStackTrace(); return ERROR; } return SUCCESS; } public File getMyFile() { return myFile; } public void setMyFile(File myFile) { this.myFile = myFile; } public String getMyFileContentType() { return myFileContentType; } public void setMyFileContentType(String myFileContentType) { this.myFileContentType = myFileContentType; } public String getMyFileFileName() { return myFileFileName; } public void setMyFileFileName(String myFileFileName) { this.myFileFileName = myFileFileName; } } The uploadFile.java is a very simple class. The important thing to note is that the FileUpload interceptor along with the Parameters Interceptor does all the heavy lifting for us. The FileUpload interceptor makes three parameters available for you by default. They are named in the following pattern − [your file name parameter] − This is the actual file that the user has uploaded. In this example it will be “myFile” [your file name parameter]ContentType − This is the content type of the file that was uploaded. In this example it will be “myFileContentType” [your file name parameter]FileName − This is the name of the file that was uploaded. In this example it will be “myFileFileName” The three parameters are available for us, thanks to the Struts Interceptors. All we have to do is to create three parameters with the correct names in our Action class and automatically these variables are auto wired for us. So, in the above example, we have three parameters and an action method that simply returns “success” if everything goes fine otherwise it returns “error”. Configuration Files Following are the Struts2 configuration properties that control file uploading process − Sr.No Properties & Description 1 struts.multipart.maxSize The maximum size (in bytes) of a file to be accepted as a file upload. Default is 250M. 2 struts.multipart.parser The library used to upload the multipart form. By default is jakarta 3 struts.multipart.saveDir The location to store the temporary file. By default is javax.servlet.context.tempdir. In order to change any of these settings, you can use constant tag in your applications struts.xml file, as I did to change the maximum size of a file to be uploaded. Let us have our struts.xml as follows − <?xml version = “1.0” Encoding = “UTF-8”?> <!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” “http://struts.apache.org/dtds/struts-2.0.dtd”> <struts> <constant name = “struts.devMode” value = “true” /> <constant name = “struts.multipart.maxSize” value = “1000000” /> <package name = “helloworld” extends = “struts-default”> <action name = “upload” class = “com.tutorialspoint.struts2.uploadFile”> <result name = “success”>/success.jsp</result> <result name = “error”>/error.jsp</result> </action> </package> </struts> Since, FileUpload interceptor is a part of the default Stack of interceptors, we do not need to configure it explicity. But, you can add <interceptor-ref> tag inside <action>. The fileUpload interceptor takes two parameters (a) maximumSize and (b) allowedTypes. The maximumSize parameter sets the maximum file size allowed (the default is approximately 2MB). The allowedTypes parameter is a comma-separated list of accepted content (MIME) types as shown below − <action name = “upload”

Struts2 – Basic MVC Architecture

Basic MVC Architecture ”; Previous Next Model View Controller or MVC as it is popularly called, is a software design pattern for developing web applications. A Model View Controller pattern is made up of the following three parts − Model − The lowest level of the pattern which is responsible for maintaining data. View − This is responsible for displaying all or a portion of the data to the user. Controller − Software Code that controls the interactions between the Model and View. MVC is popular as it isolates the application logic from the user interface layer and supports separation of concerns. Here the Controller receives all requests for the application and then works with the Model to prepare any data needed by the View. The View then uses the data prepared by the Controller to generate a final presentable response. The MVC abstraction can be graphically represented as follows. The Model The model is responsible for managing the data of the application. It responds to the request from the view and it also responds to instructions from the controller to update itself. The View It means presentation of data in a particular format, triggered by a controller”s decision to present the data. They are script-based templating systems like JSP, ASP, PHP and very easy to integrate with AJAX technology. The Controller The controller is responsible for responding to the user input and perform interactions on the data model objects. The controller receives the input, it validates the input and then performs the business operation that modifies the state of the data model. Struts2 is a MVC based framework. In the coming chapters, let us see how we can use the MVC methodology within Struts2. Print Page Previous Next Advertisements ”;

Struts2 – Database Access

Struts 2 – Database Access ”; Previous Next This chapter will teach you how to access a database using Struts 2 in simple steps. Struts is a MVC framework and not a database framework but it provides excellent support for JPA/Hibernate integration. We shall look at the hibernate integration in a later chapter, but in this chapter we shall use plain old JDBC to access the database. The first step in this chapter is to setup and prime our database. I am using MySQL as my database for this example. I have MySQL installed on my machine and I have created a new database called “struts_tutorial”. I have created a table called login and populated it with some values. Below is the script I used to create and populate the table. My MYSQL database has the default username “root” and “root123” password CREATE TABLE `struts_tutorial`.`login` ( `user` VARCHAR( 10 ) NOT NULL , `password` VARCHAR( 10 ) NOT NULL , `name` VARCHAR( 20 ) NOT NULL , PRIMARY KEY ( `user` ) ) ENGINE = InnoDB; INSERT INTO `struts_tutorial`.`login` (`user`, `password`, `name`) VALUES (”scott”, ”navy”, ”Scott Burgemott”); Next step is to download the MySQL Connector jar file and placing this file in the WEB-INFlib folder of your project. After we have done this, we are now ready to create the action class. Create Action The action class has the properties corresponding to the columns in the database table. We have user, password and name as String attributes. In the action method, we use the user and password parameters to check if the user exists, if so, we display the user name in the next screen. If the user has entered wrong information, we send them to the login screen again. Following is the content of LoginAction.java file − package com.tutorialspoint.struts2; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport { private String user; private String password; private String name; public String execute() { String ret = ERROR; Connection conn = null; try { String URL = “jdbc:mysql://localhost/struts_tutorial”; Class.forName(“com.mysql.jdbc.Driver”); conn = DriverManager.getConnection(URL, “root”, “root123”); String sql = “SELECT name FROM login WHERE”; sql+=” user = ? AND password = ?”; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, user); ps.setString(2, password); ResultSet rs = ps.executeQuery(); while (rs.next()) { name = rs.getString(1); ret = SUCCESS; } } catch (Exception e) { ret = ERROR; } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { } } } return ret; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Create Main Page Now, let us create a JSP file index.jsp to collect the username and password. This username and password will be checked against the database. <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <title>Login</title> </head> <body> <form action = “loginaction” method = “post”> User:<br/><input type = “text” name = “user”/><br/> Password:<br/><input type = “password” name = “password”/><br/> <input type = “submit” value = “Login”/> </form> </body> </html> Create Views Now let us create success.jsp file which will be invoked in case action returns SUCCESS, but we will have another view file in case of an ERROR is returned from the action. <%@ page contentType = “text/html; charset = UTF-8” %> <%@ taglib prefix = “s” uri = “/struts-tags” %> <html> <head> <title>Successful Login</title> </head> <body> Hello World, <s:property value = “name”/> </body> </html> Following will be the view file error.jsp in case of an ERROR is returned from the action. <%@ page contentType = “text/html; charset = UTF-8” %> <%@ taglib prefix = “s” uri = “/struts-tags” %> <html> <head> <title>Invalid User Name or Password</title> </head> <body> Wrong user name or password provided. </body> </html> Configuration Files Finally, let us put everything together using the struts.xml configuration file as follows − <?xml version = “1.0” Encoding = “UTF-8”?> <!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” “http://struts.apache.org/dtds/struts-2.0.dtd”> <struts> <constant name = “struts.devMode” value = “true” /> <package name = “helloworld” extends = “struts-default”> <action name = “loginaction” class = “com.tutorialspoint.struts2.LoginAction” method = “execute”> <result name = “success”>/success.jsp</result> <result name = “error”>/error.jsp</result> </action> </package> </struts> Following is the content of web.xml file − <?xml version = “1.0” Encoding = “UTF-8”?> <web-app xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xmlns = “http://java.sun.com/xml/ns/javaee” xmlns:web = “http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd” xsi:schemaLocation = “http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd” id = “WebApp_ID” version = “3.0”> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> Now, right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat”s webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen − Enter a wrong user name and password. You should see the next page. Now enter scott as user name and navy as password. You should see the next page. Print Page Previous Next Advertisements ”;

Example – Borders

Swing Examples – Borders ”; Previous Next Learn how to play with Borders in Swing UI programming. Here are most commonly used examples − How to use Borders in a Java Swing application? How to add a border to Java Panel in Swing? How to add a border to Java Label in Swing? How to add a title to JPanel border in Swing? Print Page Previous Next Advertisements ”;

Example – Home

Swing Programming Examples Find the best practical and ready to use JAVA Swing Examples. JAVA provides a rich set of libraries to create Graphical User Interface in a platform independent way. These examples would be very useful for your projects, thesis and learning. Audience This reference is designed for software professionals who are willing to learn JAVA GUI Programming in simple and easy steps. Prerequisites Before you start doing practice with various types of examples given in this reference, I”m making an assumption that you are already aware about what is a Java Programming and it”s concepts. Print Page Previous Next Advertisements ”;

Spring Boot – Introduction

Spring Boot – Introduction ”; Previous Next Spring Boot is an open source Java-based framework used to create a micro Service. It is developed by Pivotal Team and is used to build stand-alone and production ready spring applications. This chapter will give you an introduction to Spring Boot and familiarizes you with its basic concepts. What is Micro Service? Micro Service is an architecture that allows the developers to develop and deploy services independently. Each service running has its own process and this achieves the lightweight model to support business applications. Advantages Micro services offers the following advantages to its developers − Easy deployment Simple scalability Compatible with Containers Minimum configuration Lesser production time What is Spring Boot? Spring Boot provides a good platform for Java developers to develop a stand-alone and production-grade spring application that you can just run. You can get started with minimum configurations without the need for an entire Spring configuration setup. Advantages Spring Boot offers the following advantages to its developers − Easy to understand and develop spring applications Increases productivity Reduces the development time Goals Spring Boot is designed with the following goals − To avoid complex XML configuration in Spring To develop a production ready Spring applications in an easier way To reduce the development time and run the application independently Offer an easier way of getting started with the application Why Spring Boot? You can choose Spring Boot because of the features and benefits it offers as given here − It provides a flexible way to configure Java Beans, XML configurations, and Database Transactions. It provides a powerful batch processing and manages REST endpoints. In Spring Boot, everything is auto configured; no manual configurations are needed. It offers annotation-based spring application Eases dependency management It includes Embedded Servlet Container How does it work? Spring Boot automatically configures your application based on the dependencies you have added to the project by using @EnableAutoConfiguration annotation. For example, if MySQL database is on your classpath, but you have not configured any database connection, then Spring Boot auto-configures an in-memory database. The entry point of the spring boot application is the class contains @SpringBootApplication annotation and the main method. Spring Boot automatically scans all the components included in the project by using @ComponentScan annotation. Spring Boot Starters Handling dependency management is a difficult task for big projects. Spring Boot resolves this problem by providing a set of dependencies for developers convenience. For example, if you want to use Spring and JPA for database access, it is sufficient if you include spring-boot-starter-data-jpa dependency in your project. Note that all Spring Boot starters follow the same naming pattern spring-boot-starter- *, where * indicates that it is a type of the application. Examples Look at the following Spring Boot starters explained below for a better understanding − Spring Boot Starter Actuator dependency is used to monitor and manage your application. Its code is shown below − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> Spring Boot Starter Security dependency is used for Spring Security. Its code is shown below − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> Spring Boot Starter web dependency is used to write a Rest Endpoints. Its code is shown below − <dependency&gt <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> Spring Boot Starter Thyme Leaf dependency is used to create a web application. Its code is shown below − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> Spring Boot Starter Test dependency is used for writing Test cases. Its code is shown below − <dependency&gt <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> Auto Configuration Spring Boot Auto Configuration automatically configures your Spring application based on the JAR dependencies you added in the project. For example, if MySQL database is on your class path, but you have not configured any database connection, then Spring Boot auto configures an in-memory database. For this purpose, you need to add @EnableAutoConfiguration annotation or @SpringBootApplication annotation to your main class file. Then, your Spring Boot application will be automatically configured. Observe the following code for a better understanding − import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @EnableAutoConfiguration public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } Spring Boot Application The entry point of the Spring Boot Application is the class contains @SpringBootApplication annotation. This class should have the main method to run the Spring Boot application. @SpringBootApplication annotation includes Auto- Configuration, Component Scan, and Spring Boot Configuration. If you added @SpringBootApplication annotation to the class, you do not need to add the @EnableAutoConfiguration, @ComponentScan and @SpringBootConfiguration annotation. The @SpringBootApplication annotation includes all other annotations. Observe the following code for a better understanding − import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } Component Scan Spring Boot application scans all the beans and package declarations when the application initializes. You need to add the @ComponentScan annotation for your class file to scan your components added in your project. Observe the following code for a better understanding − import org.springframework.boot.SpringApplication; import org.springframework.context.annotation.ComponentScan; @ComponentScan public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } Print Page Previous Next Advertisements ”;