Spring Boot – Quick Guide ”; Previous Next Spring Boot – Introduction 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> <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> <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); } } Spring Boot – Quick Start This chapter will teach you how to create a Spring Boot application using Maven and Gradle. Prerequisites Your system need to have the following minimum requirements to create a Spring Boot application − Java 7 Maven 3.2 Gradle 2.5 Spring Boot CLI The Spring Boot CLI is a command line tool and it allows us to run the Groovy scripts. This is the easiest way to create a Spring Boot application by using the Spring Boot Command Line Interface. You can create, run and test the application in command prompt itself. This section explains you the steps involved in manual installation of Spring Boot CLI. For further help, you can use the following link: https://docs.spring.io/springboot/ docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-installing-springboot You can also download the Spring CLI distribution from the Spring Software repository at: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-manual-cli-installation For manual installation, you need to use the following two folders − spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.zip spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.tar.gz After the download, unpack
Category: Java
Struts2 – Exception Handling
Struts 2 – Exception Handling ”; Previous Next Struts provides an easier way to handle uncaught exception and redirect users to a dedicated error page. You can easily configure Struts to have different error pages for different exceptions. Struts makes the exception handling easy by the use of the “exception” interceptor. The “exception” interceptor is included as part of the default stack, so you don”t have to do anything extra to configure it. It is available out-of-the-box ready for you to use. Let us see a simple Hello World example with some modification in HelloWorldAction.java file. Here, we deliberately introduced a NullPointer Exception in our HelloWorldAction action code. package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; public class HelloWorldAction extends ActionSupport{ private String name; public String execute(){ String x = null; x = x.substring(0); return SUCCESS; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Let us keep the content of HelloWorld.jsp as follows − <%@ page contentType = “text/html; charset = UTF-8” %> <%@ taglib prefix = “s” uri = “/struts-tags” %> <html> <head> <title>Hello World</title> </head> <body> Hello World, <s:property value = “name”/> </body> </html> Following is the content of index.jsp − <%@ 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>Hello World</title> </head> <body> <h1>Hello World From Struts2</h1> <form action = “hello”> <label for = “name”>Please enter your name</label><br/> <input type = “text” name = “name”/> <input type = “submit” value = “Say Hello”/> </form> </body> </html> Your struts.xml should look like − <?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 = “hello” class = “com.tutorialspoint.struts2.HelloWorldAction” method = “execute”> <result name = “success”>/HelloWorld.jsp</result> </action> </package> </struts> 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 value “Struts2” and submit the page. You should see the following page − As shown in the above example, the default exception interceptor does a great job of handling the exception. Let us now create a dedicated error page for our Exception. Create a file called Error.jsp with the following contents − <%@ 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></title> </head> <body> This is my custom error page </body> </html> Let us now configure Struts to use this this error page in case of an exception. Let us modify the 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” /> <package name = “helloworld” extends = “struts-default”> <action name = “hello” class = “com.tutorialspoint.struts2.HelloWorldAction” method = “execute”> <exception-mapping exception = “java.lang.NullPointerException” result = “error” /> <result name = “success”>/HelloWorld.jsp</result> <result name = “error”>/Error.jsp</result> </action> </package> </struts> As shown in the example above, now we have configured Struts to use the dedicated Error.jsp for the NullPointerException. If you rerun the program now, you shall now see the following output − In addition to this, Struts2 framework comes with a “logging” interceptor to log the exceptions. By enabling the logger to log the uncaught exceptions, we can easily look at the stack trace and work out what went wrong Global Exception Mappings We have seen how we can handle action specific exception. We can set an exception globally which will apply to all the actions. For example, to catch the same NullPointerException exceptions, we could add <global-exception-mappings…> tag inside <package…> tag and its <result…> tag should be added inside the <action…> tag in struts.xml 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”> <global-exception-mappings> <exception-mapping exception = “java.lang.NullPointerException” result = “error” /> </global-exception-mappings> <action name = “hello” class = “com.tutorialspoint.struts2.HelloWorldAction” method = “execute”> <result name = “success”>/HelloWorld.jsp</result> <result name = “error”>/Error.jsp</result> </action> </package> </struts> Print Page Previous Next Advertisements ”;
Struts2 – Data Tags
Struts 2 – Data Tags ”; Previous Next The Struts 2 data tags are primarily used to manipulate the data displayed on a page. Listed below are the important data tags: <Start here> The Action Tag This tag enables developers to call actions directly from a JSP page by specifying the action name and an optional namespace. The body content of the tag is used to render the results from the Action. Any result processor defined for this action in struts.xml will be ignored, unless the executeResult parameter is specified. <div>Tag to execute the action</div> <br /> <s:action name = “actionTagAction” executeresult = “true” /> <br /> <div>To invokes special method in action class</div> <br /> <s:action name = “actionTagAction!specialMethod” executeresult = “true” /> Check Detailed Example The Include Tag These include will be used to include a JSP file in another JSP page. <– First Syntax –> <s:include value = “myJsp.jsp” /> <– Second Syntax –> <s:include value = “myJsp.jsp”> <s:param name = “param1” value = “value2” /> <s:param name = “param2” value = “value2” /> </s:include> <– Third Syntax –> <s:include value = “myJsp.jsp”> <s:param name = “param1”>value1</s:param> <s:param name = “param2″>value2</s:param> </s:include> Check Detailed Example The Bean Tag These bean tag instantiates a class that conforms to the JavaBeans specification. This tag has a body which can contain a number of Param elements to set any mutator methods on that class. If the var attribute is set on the BeanTag, it will place the instantiated bean into the stack”s Context. <s:bean name = “org.apache.struts2.util.Counter” var = “counter”> <s:param name = “first” value = “20”/> <s:param name = “last” value = “25” /> </s:bean> Check Detailed Example The Date Tag These date tag will allow you to format a Date in a quick and easy way. You can specify a custom format (eg. “dd/MM/yyyy hh:mm”), you can generate easy readable notations (like “in 2 hours, 14 minutes”), or you can just fall back on a predefined format with key ”struts.date.format” in your properties file. <s:date name = “person.birthday” format = “dd/MM/yyyy” /> <s:date name = “person.birthday” format = “%{getText(”some.i18n.key”)}” /> <s:date name = “person.birthday” nice=”true” /> <s:date name = “person.birthday” /> Check Detailed Example The Param Tag These param tag can be used to parameterize other tags. This tag has the following two parameters. name (String) − the name of the parameter value (Object) − the value of the parameter <pre> <ui:component> <ui:param name = “key” value = “[0]”/> <ui:param name = “value” value = “[1]”/> <ui:param name = “context” value = “[2]”/> </ui:component> </pre> Check Detailed Example The Property Tag These property tag is used to get the property of a value, which will default to the top of the stack if none is specified. <s:push value = “myBean”> <!– Example 1: –> <s:property value = “myBeanProperty” /> <!– Example 2: –>TextUtils <s:property value = “myBeanProperty” default = “a default value” /> </s:push> Check Detailed Example The Push Tag These push tag is used to push value on stack for simplified usage. <s:push value = “user”> <s:propery value = “firstName” /> <s:propery value = “lastName” /> </s:push> Check Detailed Example The Set Tag These set tag assigns a value to a variable in a specified scope. It is useful when you wish to assign a variable to a complex expression and then simply reference that variable each time rather than the complex expression. The scopes available are application, session, request, page and action. <s:set name = “myenv” value = “environment.name”/> <s:property value = “myenv”/> Check Detailed Example The Text Tag These text tag is used to render a I18n text message. <!– First Example –> <s:i18n name = “struts.action.test.i18n.Shop”> <s:text name = “main.title”/> </s:i18n> <!– Second Example –> <s:text name = “main.title” /> <!– Third Examlpe –> <s:text name = “i18n.label.greetings”> <s:param >Mr Smith</s:param> </s:text> Check Detailed Example The URL Tag These url tag is used to create a URL. <– Example 1 –> <s:url value = “editGadget.action”> <s:param name = “id” value = “%{selected}” /> </s:url> <– Example 2 –> <s:url action = “editGadget”> <s:param name = “id” value = “%{selected}” /> </s:url> <– Example 3–> <s:url includeParams=”get”> <s:param name = “id” value = “%{”22”}” /> </s:url> Check Detailed Example Print Page Previous Next Advertisements ”;
Struts2 – Tiles
Struts 2 & Tiles Integration ”; Previous Next In this chapter, let us go through the steps involved in integrating the Tiles framework with Struts2. Apache Tiles is a templating framework built to simplify the development of web application user interfaces. First of all we need to download the tiles jar files from the Apache Tiles website. You need to add the following jar files to the project”s class path. tiles-api-x.y.z.jar tiles-compat-x.y.z.jar tiles-core-x.y.z.jar tiles-jsp-x.y.z.jar tiles-servlet-x.y.z.jar In addition to the above, we have to copy the following jar files from the struts2 download in your WEB-INF/lib. commons-beanutils-x.y.zjar commons-digester-x.y.jar struts2-tiles-plugin-x.y.z.jar Now let us setup the web.xml for the Struts-Tiles integration as given below. There are two important point to note here. First, we need to tell tiles, where to find tiles configuration file tiles.xml. In our case, it will be under /WEB-INF folder. Next we need to initiliaze the Tiles listener that comes with Struts2 download. <?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_2_5.xsd” id = “WebApp_ID” version = “2.5”> <display-name>Struts2Example15</display-name> <context-param> <param-name> org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG </param-name> <param-value> /WEB-INF/tiles.xml </param-value> </context-param> <listener> <listener-class> org.apache.struts2.tiles.StrutsTilesListener </listener-class> </listener> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> Next let us create tiles.xml under /WEB-INF folder with the following contents − <?xml version = “1.0” Encoding = “UTF-8” ?> <!DOCTYPE tiles-definitions PUBLIC “-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN” “http://tiles.apache.org/dtds/tiles-config_2_0.dtd”> <tiles-definitions> <definition name = “baseLayout” template=”/baseLayout.jsp”> <put-attribute name = “title” value = “Template”/> <put-attribute name = “banner” value = “/banner.jsp”/> <put-attribute name = “menu” value = “/menu.jsp”/> <put-attribute name = “body” value = “/body.jsp”/> <put-attribute name = “footer” value = “/footer.jsp”/> </definition> <definition name = “tiger” extends = “baseLayout”> <put-attribute name = “title” value = “Tiger”/> <put-attribute name = “body” value = “/tiger.jsp”/> </definition> <definition name = “lion” extends = “baseLayout”> <put-attribute name = “title” value = “Lion”/> <put-attribute name = “body” value = “/lion.jsp”/> </definition> </tiles-definitions> Next, we define a basic skeleton layout in the baseLayout.jsp. It has five reusable / overridable areas. Namely title, banner, menu, body and footer. We provide the default values for the baseLayout and then we create two customizations that extend from the default layout. The tiger layout is similar to the basic layout, except it uses the tiger.jsp as its body and the text “Tiger” as the title. Similarly, the lion layout is similar to the basic layout, except it uses the lion.jsp as its body and the text “Lion” as the title. Let us have a look at the individual jsp files. Following is the content of baseLayout.jsp file − <%@ taglib uri = “http://tiles.apache.org/tags-tiles” prefix = “tiles”%> <!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> <html> <head> <meta http-equiv=”Content-Type” content=”text/html; charset = UTF-8″> <title> <tiles:insertAttribute name = “title” ignore=”true” /> </title> </head> <body> <tiles:insertAttribute name = “banner” /><br/> <hr/> <tiles:insertAttribute name = “menu” /><br/> <hr/> <tiles:insertAttribute name = “body” /><br/> <hr/> <tiles:insertAttribute name = “footer” /><br/> </body> </html> Here, we just put together a basic HTML page that has the tiles attributes. We insert the tiles attributes in the places where we need them to be. Next, let us create a banner.jsp file with the following content − <img src=”http://www.tutorialspoint.com/images/tp-logo.gif”/> The menu.jsp file will have the following lines which are the links – to the TigerMenu.action and the LionMenu.action struts actions. <%@taglib uri = “/struts-tags” prefix = “s”%> <a href = “<s:url action = “tigerMenu”/>” Tiger</a><br> <a href = “<s:url action = “lionMenu”/>” Lion</a><br> The lion.jsp file will have following content − <img src=”http://upload.wikimedia.org/wikipedia/commons/d/d2/Lion.jpg”/> The lion The tiger.jsp file will have following content − <img src=”http://www.freewebs.com/tigerofdarts/tiger.jpg”/> The tiger Next, let us create the action class file MenuAction.java which contains the following − package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; public class MenuAction extends ActionSupport { public String tiger() { return “tiger”; } public String lion() { return “lion”; } } This is a pretty straight forward class. We declared two methods tiger() and lion() that return tiger and lion as outcomes respectively. Let us put it all together in the struts.xml file − <!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” “http://struts.apache.org/dtds/struts-2.0.dtd”> <struts> <package name = “default” extends = “struts-default”> <result-types> <result-type name = “tiles” class=”org.apache.struts2.views.tiles.TilesResult” /> </result-types> <action name = “*Menu” method = “{1}” class = “com.tutorialspoint.struts2.MenuAction”> <result name = “tiger” type = “tiles”>tiger</result> <result name = “lion” type = “tiles”>lion</result> </action> </package> </struts> Let us check what we did in above file. First of all, we declared a new result type called “tiles” as we are now using tiles instead of plain jsp for the view technology. Struts2 has its support for the Tiles View result type, so we create the result type “tiles” to be of the “org.apache.struts2.view.tiles.TilesResult” class. Next, we want to say if the request is for /tigerMenu.action take the user to the tiger tiles page and if the request is for /lionMenu.action take the user to the lion tiles page. We achieve this using a bit of regular expression. In our action definition, we say anything that matches the pattern “*Menu” will be handled by this action. The matching method will be invoked in the MenuAction class. That is, tigerMenu.action will invoke tiger() and lionMenu.action will invoke lion(). We then need to map the outcome of the result to the appropriate tiles pages. 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/tigerMenu.jsp. This will produce the following screen − Similarly, if you goto the lionMenu.action page, you will see the lion page which uses the same tiles layout. Print Page Previous Next Advertisements ”;
Example – Password Fields
Swing Examples – TextFields and Password Fields ”; Previous Next Learn how to play with TextFields and Password Fields in Swing UI programming. Here are most commonly used examples − How to create and use a password field in Swing? How to create and use a text field in Swing? How to change the echo character of password field in Swing? Print Page Previous Next Advertisements ”;
Struts2 – Themes/Templates
Struts 2 – Themes & Templates ”; Previous Next Before starting actual tutorial for this chapter, let us look into few definition as given by https://struts.apache.org− Sr.No Term & Description 1 TAG A small piece of code executed from within JSP, FreeMarker, or Velocity. 2 TEMPLATE A bit of code, usually written in FreeMarker, that can be rendered by certain tags (HTML tags). 3 THEME A collection of templates packaged together to provide common functionality. I would also suggest going through the Struts2 Localization chapter because we will take same example once again to perform our excercise. When you use a Struts 2 tag such as <s:submit…>, <s:textfield…> etc in your web page, the Struts 2 framework generates HTML code with a preconfigured style and layout. Struts 2 comes with three built-in themes − Sr.No Theme & Description 1 SIMPLE theme A minimal theme with no “bells and whistles”. For example, the textfield tag renders the HTML <input/> tag without a label, validation, error reporting, or any other formatting or functionality. 2 XHTML theme This is the default theme used by Struts 2 and provides all the basics that the simple theme provides and adds several features like standard two-column table layout for the HTML, Labels for each of the HTML, Validation and error reporting etc. 3 CSS_XHTML theme This theme provides all the basics that the simple theme provides and adds several features like standard two-column CSS-based layout, using <div> for the HTML Struts Tags, Labels for each of the HTML Struts Tags, placed according to the CSS stylesheet. As mentioned above, if you don’t specify a theme, then Struts 2 will use the xhtml theme by default. For example, this Struts 2 select tag − <s:textfield name = “name” label = “Name” /> generates following HTML markup − <tr> <td class=”tdLabel”> <label for = “empinfo_name” class=”label”>Name:</label> </td> <td> <input type = “text” name = “name” value = “” id = “empinfo_name”/> </td> </tr> Here empinfo is the action name defined in struts.xml file. Selecting Themes You can specify the theme on as per Struts 2, tag basis or you can use one of the following methods to specify what theme Struts 2 should use − The theme attribute on the specific tag The theme attribute on a tag”s surrounding form tag The page-scoped attribute named “theme” The request-scoped attribute named “theme” The session-scoped attribute named “theme” The application-scoped attribute named “theme” The struts.ui.theme property in struts.properties (defaults to xhtml) Following is the syntax to specify them at tag level if you are willing to use different themes for different tags − <s:textfield name = “name” label = “Name” theme=”xhtml”/> Because it is not very much practical to use themes on per tag basis, so simply we can specify the rule in struts.properties file using the following tags − # Standard UI theme struts.ui.theme = xhtml # Directory where theme template resides struts.ui.templateDir = template # Sets the default template type. Either ftl, vm, or jsp struts.ui.templateSuffix = ftl Following is the result we picked up from localization chapter where we used the default theme with a setting struts.ui.theme = xhtml in struts-default.properties file which comes by default in struts2-core.xy.z.jar file. How a Theme Works? For a given theme, every struts tag has an associated template like s:textfield → text.ftl and s:password → password.ftl etc. These template files come zipped in struts2-core.xy.z.jar file. These template files keep a pre-defined HTML layout for each tag. In this way, Struts 2 framework generates final HTML markup code using Sturts tags and associated templates. Struts 2 tags + Associated template file = Final HTML markup code. Default templates are written in FreeMarker and they have an extension .ftl. You can also design your templates using velocity or JSP and accordingly set the configuration in struts.properties using struts.ui.templateSuffix and struts.ui.templateDir. Creating New Themes The simplest way to create a new theme is to copy any of the existing theme/template files and do required modifications. Let us start with creating a folder called template in WebContent/WEBINF/classes and a sub-folder with the name of our new theme. For example, WebContent/WEB-INF/classes/template/mytheme. From here, you can start building templates from scratch, or you can also copy the templates from the Struts2 distribution where you can modify them as required in future. We are going to modify existing default template xhtml for learning purpose. Now, let us copy the content from struts2-core-x.y.z.jar/template/xhtml to our theme directory and modify only WebContent/WEBINF/classes/template/mytheme/control.ftl file. When we open control.ftl which will have the following lines − <table class=”${parameters.cssClass?default(”wwFormTable”)?html}”<#rt/> <#if parameters.cssStyle??> style=”${parameters.cssStyle?html}”<#rt/> </#if> > Let us change above file control.ftl to have the following content − <table style = “border:1px solid black;”> If you will check form.ftl then you will find that control.ftl is used in this file, but form.ftl is referring this file from xhtml theme. So let us change it as follows − <#include “/${parameters.templateDir}/xhtml/form-validate.ftl” /> <#include “/${parameters.templateDir}/simple/form-common.ftl” /> <#if (parameters.validate?default(false))> onreset = “${parameters.onreset?default(”clearErrorMessages(this); clearErrorLabels(this);”)}” <#else> <#if parameters.onreset??> onreset=”${parameters.onreset?html}” </#if> </#if> #include “/${parameters.templateDir}/mytheme/control.ftl” /> I assume that, you would not have much understanding of the FreeMarker template language, still you can get a good idea of what is to be done by looking at the .ftl files. However, let us save above changes, and go back to our localization example and create the WebContent/WEB-INF/classes/struts.properties file with the following content # Customized them struts.ui.theme = mytheme # Directory where theme template resides struts.ui.templateDir = template # Sets the template type to ftl. struts.ui.templateSuffix = ftl Now after this change, 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. This will produce the following screen − You can see a border around the form component which is a result of the change we did in out theme after copying it from xhtml theme. If you put little effort in learning FreeMarker, then
Example – Editor Panes
Swing Examples – EditorPanes ”; Previous Next Learn how to play with EditorPanes in Swing UI programming. Here are most commonly used examples − How to read a URL to display its page in Swing? How to use a JEditorPane to display an HTML page in Swing? Print Page Previous Next Advertisements ”;
Struts2 – Form Tags
Struts 2 – The Form Tags ”; Previous Next The list of form tags is a subset of Struts UI Tags. These tags help in the rendering of the user interface required for the Struts web applications and can be categorised into three categories. This chapter will take you thorugh all the three types of UI tags − Simple UI Tags We have used these tags in our examples already, we will brush them in this chapter. Let us look a simple view page email.jsp with several simple UI tags − <%@ 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> <s:head/> <title>Hello World</title> </head> <body> <s:div>Email Form</s:div> <s:text name = “Please fill in the form below:” /> <s:form action = “hello” method = “post” enctype = “multipart/form-data”> <s:hidden name = “secret” value = “abracadabra”/> <s:textfield key = “email.from” name = “from” /> <s:password key = “email.password” name = “password” /> <s:textfield key = “email.to” name = “to” /> <s:textfield key = “email.subject” name = “subject” /> <s:textarea key = “email.body” name = “email.body” /> <s:label for = “attachment” value = “Attachment”/> <s:file name = “attachment” accept = “text/html,text/plain” /> <s:token /> <s:submit key = “submit” /> </s:form> </body> </html> If you are aware of HTML, then all the tags used are very common HTML tags with an additional prefix s: along with each tag and different attributes. When we execute the above program, we get the following user interface provided you have setup proper mapping for all the keys used. As shown, the s:head generates the javascript and stylesheet elements required for the Struts2 application. Next, we have the s:div and s:text elements. The s:div is used to render a HTML Div element. This is useful for people who do not like to mix HTML and Struts tags together. For those people, they have the choice to use s:div to render a div. The s:text as shown is used to render a text on the screen. Next we have the famiilar s:form tag. The s:form tag has an action attribute that determines where to submit the form. Because we have a file upload element in the form, we have to set the enctype to multipart. Otherwise, we can leave this blank. At the end of the form tag, we have the s:submit tag. This is used to submit the form. When the form is submitted, all the form values are submitted to the the action specified in the s:form tag. Inside the s:form, we have a hidden attribute called secret. This renders a hidden element in the HTML. In our case, the “secret” element has the value “abracadabra”. This element is not visible to the end user and is used to carry the state from one view to another. Next we have the s:label, s:textfield, s:password and s:textarea tags. These are used to render the label, input field, password and the text area respectively. We have seen these in action in the “Struts – Sending Email” example. The important thing to note here is the use of “key” attribute. The “key” attribute is used to fetch the label for these controls from the property file. We have already covered this feature in the Struts2 Localization, internationalization chapter. Then, we have the s:file tag which renders a input file upload component. This component allows the user to upload files. In this example, we have used the “accept” parameter of the s:file tag to specify which file types are allowed to be uploaded. Finally we have the s:token tag. The token tag generates an unique token which is used to find out whether a form has been double submitted When the form is rendered, a hidden variable is placed as the token value. Let us say, for example that the token is “ABC”. When this form is submitted, the Struts Fitler checks the token against the token stored in the session. If it matches, it removes the token from the session. Now, if the form is accidentally resubmitted (either by refreshing or by hitting the browser back button), the form will be resubmitted with “ABC” as the token. In this case, the filter checks the token against the token stored in the session again. But because the token “ABC” has been removed from the session, it will not match and the Struts filter will reject the request. Group UI Tags The group UI tags are used to create radio button and the checkbox. Let us look a simple view page HelloWorld.jsp with check box and radio button tags − <%@ page contentType = “text/html; charset = UTF-8″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <html> <head> <title>Hello World</title> <s:head /> </head> <body> <s:form action = “hello.action”> <s:radio label = “Gender” name = “gender” list=”{”male”,”female”}” /> <s:checkboxlist label = “Hobbies” name = “hobbies” list = “{”sports”,”tv”,”shopping”}” /> </s:form> </body> </html> When we execute the above program, our output will look similar to the following − Let us look at the example now. In the first example, we are creating a simple radio button with the label “Gender”. The name attribute is mandatory for the radio button tag, so we specify a name which is “gender”. We then supply a list to the gender. The list is populated with the values “male” and “female”. Therefore, in the output we get a radio button with two values in it. In the second example, we are creating a checkbox list. This is to gather the user”s hobbies. The user can have more than one hobby and therefore we are using the checkbox instead of the radiobutton. The checkbox is populated with the list “sports”, “TV” and “Shopping”. This presents the hobbies as a checkbox list. Select UI Tags Let us explore the different variations of the Select Tag offered by Struts. Let us look a simple view page
Spring Boot – Scheduling
Spring Boot – Scheduling ”; Previous Next Scheduling is a process of executing the tasks for the specific time period. Spring Boot provides a good support to write a scheduler on the Spring applications. Java Cron Expression Java Cron expressions are used to configure the instances of CronTrigger, a subclass of org.quartz.Trigger. For more information about Java cron expression you can refer to this link − https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm The @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file. @SpringBootApplication @EnableScheduling public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } The @Scheduled annotation is used to trigger the scheduler for a specific time period. @Scheduled(cron = “0 * 9 * * ?”) public void cronJobSch() throws Exception { } The following is a sample code that shows how to execute the task every minute starting at 9:00 AM and ending at 9:59 AM, every day package com.tutorialspoint.demo.scheduler; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class Scheduler { @Scheduled(cron = “0 * 9 * * ?”) public void cronJobSch() { SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”); Date now = new Date(); String strDate = sdf.format(now); System.out.println(“Java cron job expression:: ” + strDate); } } The following screenshot shows how the application has started at 09:03:23 and for every one minute from that time the cron job scheduler task has executed. Fixed Rate Fixed Rate scheduler is used to execute the tasks at the specific time. It does not wait for the completion of previous task. The values should be in milliseconds. The sample code is shown here − @Scheduled(fixedRate = 1000) public void fixedRateSch() { } A sample code for executing a task on every second from the application startup is shown here − package com.tutorialspoint.demo.scheduler; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class Scheduler { @Scheduled(fixedRate = 1000) public void fixedRateSch() { SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”); Date now = new Date(); String strDate = sdf.format(now); System.out.println(“Fixed Rate scheduler:: ” + strDate); } } Observe the following screenshot that shows the application that has started at 09:12:00 and after that every second fixed rate scheduler task has executed. Fixed Delay Fixed Delay scheduler is used to execute the tasks at a specific time. It should wait for the previous task completion. The values should be in milliseconds. A sample code is shown here − @Scheduled(fixedDelay = 1000, initialDelay = 1000) public void fixedDelaySch() { } Here, the initialDelay is the time after which the task will be executed the first time after the initial delay value. An example to execute the task for every second after 3 seconds from the application startup has been completed is shown below − package com.tutorialspoint.demo.scheduler; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class Scheduler { @Scheduled(fixedDelay = 1000, initialDelay = 3000) public void fixedDelaySch() { SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss.SSS”); Date now = new Date(); String strDate = sdf.format(now); System.out.println(“Fixed Delay scheduler:: ” + strDate); } } Observe the following screenshot which shows the application that has started at 09:18:39 and after every 3 seconds, the fixed delay scheduler task has executed on every second. Print Page Previous Next Advertisements ”;
Spring Boot – Hystrix
Spring Boot – Hystrix ”; Previous Next Hystrix is a library from Netflix. Hystrix isolates the points of access between the services, stops cascading failures across them and provides the fallback options. For example, when you are calling a 3rd party application, it takes more time to send the response. So at that time, the control goes to the fallback method and returns the custom response to your application. In this chapter you are going to see How to implement the Hystrix in a Spring Boot application. First, we need to add the Spring Cloud Starter Hystrix dependency in our build configuration file. Maven users can add the following dependency in the pom.xml file − <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency> Gradle users can add the following dependency in the build.gradle file − compile(”org.springframework.cloud:spring-cloud-starter-hystrix”) Now, add the @EnableHystrix annotation into your main Spring Boot application class file. The @EnableHystrix annotation is used to enable the Hystrix functionalities into your Spring Boot application. The main Spring Boot application class file code is given below − package com.tutorialspoint.hystrixapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.hystrix.EnableHystrix; @SpringBootApplication @EnableHystrix public class HystrixappApplication { public static void main(String[] args) { SpringApplication.run(HystrixappApplication.class, args); } } Now write a simple Rest Controller such that it returns the String after 3 seconds from the requested time. @RequestMapping(value = “/”) public String hello() throws InterruptedException { Thread.sleep(3000); return “Welcome Hystrix”; } Now, add the @Hystrix command and @HystrixProperty for the Rest API and define the timeout in milliseconds value. @HystrixCommand(fallbackMethod = “fallback_hello”, commandProperties = { @HystrixProperty(name = “execution.isolation.thread.timeoutInMilliseconds”, value = “1000”) }) Next, define the fallback method fallback_hello() if the request takes a long time to respond. private String fallback_hello() { return “Request fails. It takes long time to response”; } The complete Rest Controller class file that contains REST API and Hystrix properties is shown here − @RequestMapping(value = “/”) @HystrixCommand(fallbackMethod = “fallback_hello”, commandProperties = { @HystrixProperty(name = “execution.isolation.thread.timeoutInMilliseconds”, value = “1000”) }) public String hello() throws InterruptedException { Thread.sleep(3000); return “Welcome Hystrix”; } private String fallback_hello() { return “Request fails. It takes long time to response”; } In this example, REST API written in main Spring Boot application class file itself. package com.tutorialspoint.hystrixapp; import org.springframework.boot.SpringApplication; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.hystrix.EnableHystrix; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; @SpringBootApplication @EnableHystrix @RestController public class HystrixappApplication { public static void main(String[] args) { SpringApplication.run(HystrixappApplication.class, args); } @RequestMapping(value = “/”) @HystrixCommand(fallbackMethod = “fallback_hello”, commandProperties = { @HystrixProperty(name = “execution.isolation.thread.timeoutInMilliseconds”, value = “1000”) }) public String hello() throws InterruptedException { Thread.sleep(3000); return “Welcome Hystrix”; } private String fallback_hello() { return “Request fails. It takes long time to response”; } } The complete build configuration file is given below. Maven – pom.xml file <?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>hystrixapp</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>hystrixapp</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> <spring-cloud.version>Edgware.RELEASE</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <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() } ext { springCloudVersion = ”Edgware.RELEASE” } dependencies { compile(”org.springframework.cloud:spring-cloud-starter-hystrix”) compile(”org.springframework.boot:spring-boot-starter-web”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } dependencyManagement { imports { mavenBom “org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}” } } You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands − For Maven, use the command as shown − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, use the command as shown − 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 command given below − java –jar <JARFILE> This will start the application on the Tomcat port 8080 as shown below − Now, hit the URL http://localhost:8080/ from your web browser, and see the Hystrix response. The API takes 3 seconds to respond, but Hystrix timeout is 1 second. Print Page Previous Next Advertisements ”;