Struts2 – Examples

Struts 2 – Hello World Example ”; Previous Next As you have already learnt from the Struts 2 architecture, when you click on a hyperlink or submit an HTML form in a Struts 2 web-application, the input is collected by the Controller which is sent to a Java class called Actions. After the Action is executed, a result selects a resource to render the response. The resource is generally a JSP, but it can also be a PDF file, an Excel spreadsheet, or a Java applet window. Assuming that you already have built your development environment. Now, let us proceed for building our first Hello World Struts2 project. The aim of this project is to build a web application that collects the user”s name and displays “Hello World” followed by the user name. We would have to create following four components for any Struts 2 project − Sr.No Components & Description 1 Action Create an action class which will contain complete business logic and control the interaction between the user, the model, and the view. 2 Interceptors Create interceptors if required, or use existing interceptors. This is part of Controller. 3 View Create a JSPs to interact with the user to take input and to present the final messages. 4 Configuration Files Create configuration files to couple the Action, View and Controllers. These files are struts.xml, web.xml, struts.properties. I am going to use Eclipse IDE, so that all the required components will be created under a Dynamic Web Project. Let us now start with creating Dynamic Web Project. Create a Dynamic Web Project Start your Eclipse and then go with File > New > Dynamic Web Project and enter project name as HelloWorldStruts2 and set rest of the options as given in the following screen − Select all the default options in the next screens and finally check Generate Web.xml deployment descriptor option. This will create a dynamic web project for you in Eclipse. Now go with Windows > Show View > Project Explorer, and you will see your project window something as below − Now copy following files from struts 2 lib folder C:struts-2.2.3lib to our project”s WEB-INFlib folder. To do this, you can simply drag and drop all the following files into WEB-INFlib folder. commons-fileupload-x.y.z.jar commons-io-x.y.z.jar commons-lang-x.y.jar commons-logging-x.y.z.jar commons-logging-api-x.y.jar freemarker-x.y.z.jar javassist-.xy.z.GA ognl-x.y.z.jar struts2-core-x.y.z.jar xwork-core.x.y.z.jar Create Action Class Action class is the key to Struts 2 application and we implement most of the business logic in action class. So let us create a java file HelloWorldAction.java under Java Resources > src with a package name com.tutorialspoint.struts2 with the contents given below. The Action class responds to a user action when user clicks a URL. One or more of the Action class”s methods are executed and a String result is returned. Based on the value of the result, a specific JSP page is rendered. package com.tutorialspoint.struts2; public class HelloWorldAction { private String name; public String execute() throws Exception { return “success”; } public String getName() { return name; } public void setName(String name) { this.name = name; } } This is a very simple class with one property called “name”. We have standard getters and setter methods for the “name” property and an execute method that returns the string “success”. The Struts 2 framework will create an object of the HelloWorldAction class and call the executed method in response to a user”s action. You put your business logic inside this method which finally returns the String constant. In other words, for each URL, you would have to implement one action class and either you can use that class name directly as your action name or you can map to some other name using struts.xml file as shown below. Create a View We need a JSP to present the final message, this page will be called by Struts 2 framework when a predefined action will happen and this mapping will be defined in struts.xml file. So let us create the below jsp file HelloWorld.jsp in the WebContent folder in your eclipse project. To do this, right click on the WebContent folder in the project explorer and select New >JSP File. <%@ 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> The taglib directive tells the Servlet container that this page will be using the Struts 2 tags and that these tags will be preceded by s. The s:property tag displays the value of action class property “name> which is returned by the method getName() of the HelloWorldAction class. Create Main Page We also need to create index.jsp in the WebContent folder. This file will serve as the initial action URL where a user can click to tell the Struts 2 framework to call a defined method of the HelloWorldAction class and render the HelloWorld.jsp view. <%@ 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> The hello action defined in the above view file will be mapped to the HelloWorldAction class and its execute method using struts.xml file. When a user clicks on the Submit button it will cause the Struts 2 framework to run the execute method defined in the HelloWorldAction class and based on the returned value of the method, an appropriate view will be selected and rendered as a response. Configuration Files We need a mapping to tie the URL, the HelloWorldAction class (Model), and the HelloWorld.jsp (the view) together. The mapping tells the Struts 2 framework which class will respond to the user”s action (the URL), which method of that class will

TestNG – Suite Test

TestNG – Suite Test ”; Previous Next A test suite is a collection of test cases intended to test a behavior or a set of behaviors of software program. In TestNG, we cannot define a suite in testing source code, but it is represented by one XML file, as suite is the feature of execution. It also allows flexible configuration of the tests to be run. A suite can contain one or more tests and is defined by the <suite> tag. <suite> is the root tag of your testng.xml. It describes a test suite, which in turn is made of several <test> sections. The following table lists all the legal attributes that <suite> accepts. Sr.No. Attribute & Description 1 name The name of this suite. It is a mandatory attribute. 2 verbose The level or verbosity for this run. 3 parallel Whether TestNG should run different threads to run this suite. 4 thread-count The number of threads to use, if parallel mode is enabled (ignored other-wise). 5 annotations The type of annotations you are using in your tests. 6 time-out The default timeout that will be used on all the test methods found in this test. In this chapter, we will show you an example having two test classes, Test1 & Test2, to run together using Test Suite. Create a Class Create a java class to be tested, say, MessageUtil.java in /work/testng/src. /* * This class prints the given message on console. */ public class MessageUtil { private String message; // Constructor // @param message to be printed public MessageUtil(String message) { this.message = message; } // prints the message public String printMessage() { System.out.println(message); return message; } // add “Hi!” to the message public String salutationMessage() { message = “Hi!” + message; System.out.println(message); return message; } } Create Test Case Classes Create a java class file named Test1.java in /work/testng/src. import org.testng.Assert; import org.testng.annotations.Test; public class Test1 { String message = “Manisha”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { System.out.println(“Inside testPrintMessage()”); Assert.assertEquals(message, messageUtil.printMessage()); } } Create a java class file named Test2.java in /work/testng/src . import org.testng.Assert; import org.testng.annotations.Test; public class Test2 { String message = “Manisha”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testSalutationMessage() { System.out.println(“Inside testSalutationMessage()”); message = “Hi!” + “Manisha”; Assert.assertEquals(message,messageUtil.salutationMessage()); } } Now, let”s write the testng.xml in /work/testng/src , which would contain the <suite> tag as follows − <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” > <suite name = “Suite1”> <test name = “exampletest1”> <classes> <class name = “Test1” /> </classes> </test> <test name = “exampletest2”> <classes> <class name = “Test2″ /> </classes> </test> </suite> Suite1 includes exampletest1 and exampletest2. Compile all java classes using javac. /work/testng/src$ javac MessageUtil.java Test1.java Test2.java Now, run the testng.xml, which will run the test case defined in the provided Test Case class. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. Manisha Inside testSalutationMessage() Hi!Manisha =============================================== Suite1 Total tests run: 2, Passes: 2, Failures: 0, Skips: 0 =============================================== You can also check the test-output folder. Under the Suite1 folder, you can see two html files created, exampletest1.html and exampletest2.html, which would look as follows − Print Page Previous Next Advertisements ”;

Spring Security – Authentication Provider

Spring Security – Authentication Provider ”; Previous Next Spring Security allows us to customize our authentication process as much as we want. Starting from a custom login page to our very own customized authentication providers and authentication filters, we can pretty much customize every aspect of the authentication process. We can define our own authentication process which can range from basic authentication using a username and a password to a complex one such as two-factor authentication using tokens and OTP’s. Also, we can use various databases – both relational and non-relational, use various password encoders, lock malicious users out of their accounts, and so on. Spring Security Architecture The basic components of Spring Security, as we can see in the above diagram are given below. We shall discuss them briefly as we go along. We shall also discuss their roles in the authentication and authorization process. AuthenticationFilter This is the filter that intercepts requests and attempts to authenticate it. In Spring Security, it converts the request to an Authentication Object and delegates the authentication to the AuthenticationManager. AuthenticationManager It is the main strategy interface for authentication. It uses the lone method authenticate() to authenticate the request. The authenticate() method performs the authentication and returns an Authentication Object on successful authentication or throw an AuthenticationException in case of authentication failure. If the method can’t decide, it will return null. The process of authentication in this process is delegated to the AuthenticationProvider which we will discuss next. AuthenticationProvider The AuthenticationManager is implemented by the ProviderManager which delegates the process to one or more AuthenticationProvider instances. Any class implementing the AuthenticationProvider interface must implement the two methods – authenticate() and supports(). First, let us talk about the supports() method. It is used to check if the particular authentication type is supported by our AuthenticationProvider implementation class. If it is supported it returns true or else false. Next, the authenticate() method. Here is where the authentication occurs. If the authentication type is supported, the process of authentication is started. Here is this class can use the loadUserByUsername() method of the UserDetailsService implementation. If the user is not found, it can throw a UsernameNotFoundException. On the other hand, if the user is found, then the authentication details of the user are used to authenticate the user. For example, in the basic authentication scenario, the password provided by the user may be checked with the password in the database. If they are found to match with each other, it is a success scenario. Then we can return an Authentication object from this method which will be stored in the Security Context, which we will discuss later. Spring Security provides following major implementations of AuthenticationProvider. DaoAuthenticationProvider − This provider is used to provide database based authentication. LdapAuthenticationProvider − This provider is specialized for LDAP(Lightweight Directory Access Protocol) based authentication. OpenIDAuthenticationProvider − This provider is used for OpenID based authentication and can be used with OpenID authentication providers like Google/Facebook etc. JwtAuthenticationProvider − For JWT(Java Web Token) based authentication, we can use JwtAuthenticationProvider class. RememberMeAuthenticationProvider − This class is used for user authentication based on remember me token of user. We”ll be creating our own AuthenticationProvider in coming section. UserDetailsService It is one of the core interfaces of Spring Security. The authentication of any request mostly depends on the implementation of the UserDetailsService interface. It is most commonly used in database backed authentication to retrieve user data. The data is retrieved with the implementation of the lone loadUserByUsername() method where we can provide our logic to fetch the user details for a user. The method will throw a UsernameNotFoundException if the user is not found. PasswordEncoder Until Spring Security 4, the use of PasswordEncoder was optional. The user could store plain text passwords using in-memory authentication. But Spring Security 5 has mandated the use of PasswordEncoder to store passwords. This encodes the user’s password using one its many implementations. The most common of its implementations is the BCryptPasswordEncoder. Also, we can use an instance of the NoOpPasswordEncoder for our development purposes. It will allow passwords to be stored in plain text. But it is not supposed to be used for production or real-world applications. Spring Security Context This is where the details of the currently authenticated user are stored on successful authentication. The authentication object is then available throughout the application for the session. So, if we need the username or any other user details, we need to get the SecurityContext first. This is done with the SecurityContextHolder, a helper class, which provides access to the security context. We can use the setAuthentication() and getAuthentication() methods for storing and retrieving the user details respectively. Custom Authenticator We can create a custom Authenticator by implementing AuthenticationProvider interface. AuthenticatorProvider interface has two methods authenticate() and supports(). authenticate() method @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = authentication.getCredentials().toString(); UserDetails user = userDetailsService.loadUserByUsername(username); if (user == null || !password.equals(user.getPassword())) { throw new BadCredentialsException(“Invalid username or password”); } List<GrantedAuthority> authorities = new ArrayList(); authorities.add(new SimpleGrantedAuthority(“ROLE_USER”)); return new UsernamePasswordAuthenticationToken(username, password, authorities); } Here in authenticate() method, we”re getting username and password using authentication object and we”re comparing username/password with the user credentials. In case user details are invalid, we”re throwing an exception as BadCredentialsException. Otherwise, a new role is prepared and UsernamePasswordAuthenticationToken is returned with required role. supports() method @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } Spring Security Configuration Use the AuthenticationProvider created in the AuthenticationManager and mark it as managed bean. @Bean public AuthenticationManager authManager(HttpSecurity http) throws Exception { AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class); WebAuthenticationProvider authProvider = new WebAuthenticationProvider(userDetailsService()); authenticationManagerBuilder.authenticationProvider(authProvider); return authenticationManagerBuilder.build(); } That”s all we need. Now let”s see the complete code in action. Before you start writing your first example using Spring framework, you have to make sure that you have set up your Spring environment properly as explained in Spring Security – Environment Setup Chapter. We also assume that you have a bit of working knowledge on Spring

Spring Boot – Internationalization

Spring Boot – Internationalization ”; Previous Next Internationalization is a process that makes your application adaptable to different languages and regions without engineering changes on the source code. In ither words, Internationalization is a readiness of Localization. In this chapter, we are going to learn in detail about How to implement the Internationalization in Spring Boot. Dependencies We need the Spring Boot Starter Web and Spring Boot Starter Thymeleaf dependency to develop a web application in Spring Boot. Maven <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> Gradle compile(”org.springframework.boot:spring-boot-starter-web”) compile group: ”org.springframework.boot”, name: ”spring-boot-starter-thymeleaf” LocaleResolver We need to determine default Locale of your application. We need to add the LocaleResolver bean in our Spring Boot application. @Bean public LocaleResolver localeResolver() { SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver(); sessionLocaleResolver.setDefaultLocale(Locale.US); return sessionLocaleResolver; } LocaleChangeInterceptor LocaleChangeInterceptor is a used to change the new Locale based on the value of the language parameter added to a request. @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName(“language”); return localeChangeInterceptor; } To take this effect, we need to add the LocaleChangeInterceptor into the application’s registry interceptor. The configuration class should extend the WebMvcConfigurerAdapter class and override the addInterceptors() method. @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } Messages Sources Spring Boot application by default takes the message sources from src/main/resources folder under the classpath. The default locale message file name should be message.properties and files for each locale should name as messages_XX.properties. The “XX” represents the locale code. All the message properties should be used as key pair values. If any properties are not found on the locale, the application uses the default property from messages.properties file. The default messages.properties will be as shown − welcome.text=Hi Welcome to Everyone The French language messages_fr.properties will be as shown − welcome.text=Salut Bienvenue à tous Note − Messages source file should be saved as “UTF-8” file format. HTML file In the HTML file, use the syntax #{key} to display the messages from the properties file. <h1 th:text = “#{welcome.text}”></h1> The complete code 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>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath /> </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.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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</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.8.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.springframework.boot:spring-boot-starter-web”) compile group: ”org.springframework.boot”, name: ”spring-boot-starter-thymeleaf” testCompile(”org.springframework.boot:spring-boot-starter-test”) } The main Spring Boot application class file is given below − package com.tutorialspoint.demo; 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); } } The controller class file is given below − package com.tutorialspoint.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ViewController { @RequestMapping(“/locale”) public String locale() { return “locale”; } } Configuration class to support the Internationalization package com.tutorialspoint.demo; import java.util.Locale; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.i18n.SessionLocaleResolver; @Configuration public class Internationalization extends WebMvcConfigurerAdapter { @Bean public LocaleResolver localeResolver() { SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver(); sessionLocaleResolver.setDefaultLocale(Locale.US); return sessionLocaleResolver; } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName(“language”); return localeChangeInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } } The Message sources – messages.properties is as shown − welcome.text = Hi Welcome to Everyone The Message sources – message_fr.properties is as shown − welcome.text = Salut Bienvenue à tous The HTML file locale.html should be placed under the templates directory on the classpath as shown − <!DOCTYPE html> <html> <head> <meta charset = “ISO-8859-1″/> <title>Internationalization</title> </head> <body> <h1 th:text = “#{welcome.text}”></h1> </body> </html> 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 following command − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, use the following command − 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 as shown − java –jar <JARFILE> You will find that the application has started on the Tomcat port 8080. Now hit the URL http://localhost:8080/locale in your web browser and you can see the following output − The URL http://localhost:8080/locale?language=fr will give you the output as shown − Print Page Previous Next Advertisements ”;

Spring Boot – Service Components

Spring Boot – Service Components ”; Previous Next Service Components are the class file which contains @Service annotation. These class files are used to write business logic in a different layer, separated from @RestController class file. The logic for creating a service component class file is shown here − public interface ProductService { } The class that implements the Interface with @Service annotation is as shown − @Service public class ProductServiceImpl implements ProductService { } Observe that in this tutorial, we are using Product Service API(s) to store, retrieve, update and delete the products. We wrote the business logic in @RestController class file itself. Now, we are going to move the business logic code from controller to service component. You can create an Interface which contains add, edit, get and delete methods using the code as shown below − package com.tutorialspoint.demo.service; import java.util.Collection; import com.tutorialspoint.demo.model.Product; public interface ProductService { public abstract void createProduct(Product product); public abstract void updateProduct(String id, Product product); public abstract void deleteProduct(String id); public abstract Collection<Product> getProducts(); } The following code will let you to create a class which implements the ProductService interface with @Service annotation and write the business logic to store, retrieve, delete and updates the product. package com.tutorialspoint.demo.service; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Service; import com.tutorialspoint.demo.model.Product; @Service public class ProductServiceImpl implements ProductService { private static Map<String, Product> productRepo = new HashMap<>(); static { Product honey = new Product(); honey.setId(“1”); honey.setName(“Honey”); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId(“2”); almond.setName(“Almond”); productRepo.put(almond.getId(), almond); } @Override public void createProduct(Product product) { productRepo.put(product.getId(), product); } @Override public void updateProduct(String id, Product product) { productRepo.remove(id); product.setId(id); productRepo.put(id, product); } @Override public void deleteProduct(String id) { productRepo.remove(id); } @Override public Collection<Product> getProducts() { return productRepo.values(); } } The code here show the Rest Controller class file, here we @Autowired the ProductService interface and called the methods. package com.tutorialspoint.demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.model.Product; import com.tutorialspoint.demo.service.ProductService; @RestController public class ProductServiceController { @Autowired ProductService productService; @RequestMapping(value = “/products”) public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productService.getProducts(), HttpStatus.OK); } @RequestMapping(value = “/products/{id}”, method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct(@PathVariable(“id”) String id, @RequestBody Product product) { productService.updateProduct(id, product); return new ResponseEntity<>(“Product is updated successsfully”, HttpStatus.OK); } @RequestMapping(value = “/products/{id}”, method = RequestMethod.DELETE) public ResponseEntity<Object> delete(@PathVariable(“id”) String id) { productService.deleteProduct(id); return new ResponseEntity<>(“Product is deleted successsfully”, HttpStatus.OK); } @RequestMapping(value = “/products”, method = RequestMethod.POST) public ResponseEntity<Object> createProduct(@RequestBody Product product) { productService.createProduct(product); return new ResponseEntity<>(“Product is created successfully”, HttpStatus.CREATED); } } The code for POJO class – Product.java is shown here − package com.tutorialspoint.demo.model; public class Product { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } A main Spring Boot application is given below − package com.tutorialspoint.demo; 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); } } The code for Maven build – pom.xml is shown below − <?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>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> </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.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> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> The code for Gradle Build – build.gradle is shown below − buildscript { ext { springBootVersion = ”1.5.8.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.springframework.boot:spring-boot-starter-web”) 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, use the command as shown below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command as shown below − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under build/libs directory. Run the JAR file by using the command given below − java –jar <JARFILE> Now, the application has started on the Tomcat port 8080 as shown in the image given below − Now hit the below URL’s in POSTMAN application and you can see the output as shown below − GET API URL is − http://localhost:8080/products POST API URL is − http://localhost:8080/products PUT API URL is − http://localhost:8080/products/3 DELETE API URL is − http://localhost:8080/products/3 Print Page Previous Next Advertisements ”;

Struts2 – Annotations

Struts 2 – Annotations ”; Previous Next As mentioned previously, Struts provides two forms of configuration. The traditional way is to use the struts.xml file for all the configurations. We have seen so many examples of that in the tutorial so far. The other way of configuring Struts is by using the Java 5 Annotations feature. Using the struts annotations, we can achieve Zero Configuration. To start using annotations in your project, make sure you have included the following jar files in your WebContent/WEB-INF/lib folder − struts2-convention-plugin-x.y.z.jar asm-x.y.jar antlr-x.y.z.jar commons-fileupload-x.y.z.jar commons-io-x.y.z.jar commons-lang-x.y.jar commons-logging-x.y.z.jar commons-logging-api-x.y.jar freemarker-x.y.z.jar javassist-.xy.z.GA ognl-x.y.z.jar struts2-core-x.y.z.jar xwork-core.x.y.z.jar Now, let us see how you can do away with the configuration available in the struts.xml file and replace it with annotaions. To explain the concept of Annotation in Struts2, we would have to reconsider our validation example explained in Struts2 Validations chapter. Here, we shall take an example of an Employee whose name, age would be captured using a simple page, and we will put two validations to make sure that ÜSER always enters a name and age should be in between 28 and 65. Let us start with the main JSP page of the example. Create Main Page Let us write main page JSP file index.jsp, which is used to collect Employee related information mentioned above. <%@ 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</title> </head> <body> <s:form action = “empinfo” method = “post”> <s:textfield name = “name” label = “Name” size = “20” /> <s:textfield name = “age” label = “Age” size = “20” /> <s:submit name = “submit” label = “Submit” align=”center” /> </s:form> </body> </html> The index.jsp makes use of Struts tag, which we have not covered yet but we will study them in tags related chapters. But for now, just assume that the s:textfield tag prints a input field, and the s:submit prints a submit button. We have used label property for each tag which creates label for each tag. Create Views We will use JSP file success.jsp which will be invoked in case the 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> Employee Information is captured successfully. </body> </html> Create Action This is the place where annotation is used. Let us re-define action class Employee with annotation, and then add a method called validate () as shown below in Employee.java file. Make sure that your action class extends the ActionSupport class, otherwise your validate method will not be executed. package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.convention.annotation.Results; import com.opensymphony.xwork2.validator.annotations.*; @Results({ @Result(name = “success”, Location = “/success.jsp”), @Result(name = “input”, Location = “/index.jsp”) }) public class Employee extends ActionSupport { private String name; private int age; @Action(value = “/empinfo”) public String execute() { return SUCCESS; } @RequiredFieldValidator( message = “The name is required” ) public String getName() { return name; } public void setName(String name) { this.name = name; } @IntRangeFieldValidator(message = “Age must be in between 28 and 65”, min = “29”, max = “65”) public int getAge() { return age; } public void setAge(int age) { this.age = age; } } We have used few annotations in this example. Let me go through them one by one − First, we have included the Results annotation. A Results annotation is a collection of results. Under the results annotation, we have two result annotations. The result annotations have the name that correspond to the outcome of the execute method. They also contain a location as to which view should be served corresponding to return value from execute() The next annotation is the Action annotation. This is used to decorate the execute() method. The Action method also takes in a value which is the URL on which the action is invoked. Finally, I have used two validation annotations. I have configured the required field validator on name field and the integer range validator on the age field. I have also specified a custom message for the validations. Configuration Files We really do not need struts.xml configuration file, so let us remove this file and let us check 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> <init-param> <param-name>struts.devMode</param-name> <param-value>true</param-value> </init-param> </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 − Now do not enter any required information, just click on Submit button. You will see the following result − Enter the required information but enter a wrong From field, let us say name as “test” and age as 30, and finally click on Submit button. You will see the following result − Struts 2 Annotations Types Struts 2 applications can use Java 5 annotations as an alternative to XML and Java properties configuration. You can check the list of most important annotations related to different categories − Struts 2 Annotations Types. Print Page Previous Next Advertisements ”;

Struts2 – Sending Email

Struts 2 – Sending Email ”; Previous Next This chapter explains how you can send an email using your Struts 2 application. For this exercise, you need to download and install the mail.jar from JavaMail API 1.4.4 and place the mail.jar file in your WEB-INFlib folder and then proceed to follow the standard steps of creating action, view and configuration files. Create Action The next step is to create an Action method that takes care of sending the email. Let us create a new class called Emailer.java with the following contents. package com.tutorialspoint.struts2; import java.util.Properties; import javax.mail.Message; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import com.opensymphony.xwork2.ActionSupport; public class Emailer extends ActionSupport { private String from; private String password; private String to; private String subject; private String body; static Properties properties = new Properties(); static { properties.put(“mail.smtp.host”, “smtp.gmail.com”); properties.put(“mail.smtp.socketFactory.port”, “465”); properties.put(“mail.smtp.socketFactory.class”, “javax.net.ssl.SSLSocketFactory”); properties.put(“mail.smtp.auth”, “true”); properties.put(“mail.smtp.port”, “465”); } public String execute() { String ret = SUCCESS; try { Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } } ); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subject); message.setText(body); Transport.send(message); } catch(Exception e) { ret = ERROR; e.printStackTrace(); } return ret; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public static Properties getProperties() { return properties; } public static void setProperties(Properties properties) { Emailer.properties = properties; } } As seen in the source code above, the Emailer.java has properties that correspond to the form attributes in the email.jsp page given below. These attributes are − From − The email address of the sender. As we are using Google”s SMTP, we need a valid gtalk id Password − The password of the above account To − Who to send the email to? Subject − subject of the email Body − The actual email message We have not considered any validations on the above fields, validations will be added in the next chapter. Let us now look at the execute() method. The execute() method uses the javax Mail library to send an email using the supplied parameters. If the mail is sent successfully, action returns SUCCESS, otherwise it returns ERROR. Create Main Page Let us write main page JSP file index.jsp, which will be used to collect email related information mentioned above − <%@ 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>Email Form</title> </head> <body> <em>The form below uses Google”s SMTP server. So you need to enter a gmail username and password </em> <form action = “emailer” method = “post”> <label for = “from”>From</label><br/> <input type = “text” name = “from”/><br/> <label for = “password”>Password</label><br/> <input type = “password” name = “password”/><br/> <label for = “to”>To</label><br/> <input type = “text” name = “to”/><br/> <label for = “subject”>Subject</label><br/> <input type = “text” name = “subject”/><br/> <label for = “body”>Body</label><br/> <input type = “text” name = “body”/><br/> <input type = “submit” value = “Send Email”/> </form> </body> </html> Create Views We will use JSP file success.jsp 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 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>Email Success</title> </head> <body> Your email to <s:property value = “to”/> was sent successfully. </body> </html> Following will be the view file error.jsp in case of an ERROR is returned from the action. <%@ 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>Email Error</title> </head> <body> There is a problem sending your email to <s:property value = “to”/>. </body> </html> Configuration Files Now 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 = “emailer” class = “com.tutorialspoint.struts2.Emailer” 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 the required information and click Send Email button. If everything goes fine, then you should see the following page. Print Page Previous Next Advertisements ”;

Struts2 – Configuration

Struts 2 – Configuration Files ”; Previous Next This chapter will take you through basic configuration which is required for a Struts 2 application. Here we will see what can be configured with the help of few important configuration files like web.xml, struts.xml, strutsconfig.xml and struts.properties Honestly speaking, you can start working by just using web.xml and struts.xml configuration files (as you have already witnessed in our previous chapter where our example worked using these two files). However, for your knowledge we will explain regarding other files also. The web.xml File The web.xml configuration file is a J2EE configuration file that determines how elements of the HTTP request are processed by the servlet container. It is not strictly a Struts2 configuration file, but it is a file that needs to be configured for Struts2 to work. As discussed earlier, this file provides an entry point for any web application. The entry point of Struts2 application will be a filter defined in deployment descriptor (web.xml). Hence we will define an entry of FilterDispatcher class in web.xml. The web.xml file needs to be created under the folder WebContent/WEB-INF. This is the first configuration file you will need to configure if you are starting without the aid of a template or tool that generates it (such as Eclipse or Maven2). Following is the content of web.xml file which we used in our last example. <?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> Note that we map the Struts 2 filter to /*, and not to /*.action which means that all urls will be parsed by the struts filter. We will cover this when we will go through the Annotations chapter. The Struts.xml File The struts.xml file contains the configuration information that you will be modifying as actions are developed. This file can be used to override default settings for an application, for example struts.devMode = false and other settings which are defined in property file. This file can be created under the folder WEB-INF/classes. Let us have a look at the struts.xml file we created in the Hello World example explained in previous chapter. <?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> <– more actions can be listed here –> </package> <– more packages can be listed here –> </struts> The first thing to note is the DOCTYPE. All struts configuration file needs to have the correct doctype as shown in our little example. <struts> is the root tag element, under which we declare different packages using <package> tags. Here <package> allows separation and modularization of the configuration. This is very useful when you have a large project and project is divided into different modules. For example, if your project has three domains – business_application, customer_application and staff_application, then you could create three packages and store associated actions in the appropriate package. The package tag has the following attributes − Sr.No Attribute & Description 1 name (required) The unique identifier for the package 2 extends Which package does this package extend from? By default, we use struts-default as the base package. 3 abstract If marked true, the package is not available for end user consumption. 4 namespace Unique namespace for the actions The constant tag along with name and value attributes should be used to override any of the following properties defined in default.properties, like we just set struts.devMode property. Setting struts.devMode property allows us to see more debug messages in the log file. We define action tags corresponds to every URL we want to access and we define a class with execute() method which will be accessed whenever we will access corresponding URL. Results determine what gets returned to the browser after an action is executed. The string returned from the action should be the name of a result. Results are configured per-action as above, or as a “global” result, available to every action in a package. Results have optional name and type attributes. The default name value is “success”. Struts.xml file can grow big over time and so breaking it by packages is one way of modularizing it, but Struts offers another way to modularize the struts.xml file. You could split the file into multiple xml files and import them in the following fashion. <?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> <include file=”my-struts1.xml”/> <include file=”my-struts2.xml”/> </struts> The other configuration file that we haven”t covered is the struts-default.xml. This file contains the standard configuration settings for Struts and you would not have to touch these settings for 99.99% of your projects. For this reason, we are not going into too much detail on this file. If you are interested, take a look into the at the default.properties file available in struts2-core-2.2.3.jar file. The Struts-config.xml File The struts-config.xml configuration file is a link between the View and Model components in the Web Client but you would not have to touch these settings for 99.99% of your projects. The configuration file basically contains following main elements − Sr.No Interceptor & Description 1 struts-config This is the root node of the configuration file. 2 form-beans This is where you map your ActionForm subclass to a name. You use this name as an alias for your ActionForm throughout the rest of the strutsconfig.xml file, and even on your JSP pages. 3 global forwards This section maps a page on your webapp to a name. You can use this name to refer to the actual page. This avoids hardcoding URLs on your web pages. 4 action-mappings This

Spring Boot – Runners

Spring Boot – Runners ”; Previous Next Application Runner and Command Line Runner interfaces lets you to execute the code after the Spring Boot application is started. You can use these interfaces to perform any actions immediately after the application has started. This chapter talks about them in detail. Application Runner Application Runner is an interface used to execute the code after the Spring Boot application started. The example given below shows how to implement the Application Runner interface on the main class file. package com.tutorialspoint.demo; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication implements ApplicationRunner { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Override public void run(ApplicationArguments arg0) throws Exception { System.out.println(“Hello World from Application Runner”); } } Now, if you observe the console window below Hello World from Application Runner, the println statement is executed after the Tomcat started. Is the following screenshot relevant? Command Line Runner Command Line Runner is an interface. It is used to execute the code after the Spring Boot application started. The example given below shows how to implement the Command Line Runner interface on the main class file. package com.tutorialspoint.demo; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Override public void run(String… arg0) throws Exception { System.out.println(“Hello world from Command Line Runner”); } } Look at the console window below “Hello world from Command Line Runner” println statement is executed after the Tomcat started. Print Page Previous Next Advertisements ”;

Spring Boot – Exception Handling

Spring Boot – Exception Handling ”; Previous Next Handling exceptions and errors in APIs and sending the proper response to the client is good for enterprise applications. In this chapter, we will learn how to handle exceptions in Spring Boot. Before proceeding with exception handling, let us gain an understanding on the following annotations. Controller Advice The @ControllerAdvice is an annotation, to handle the exceptions globally. Exception Handler The @ExceptionHandler is an annotation used to handle the specific exceptions and sending the custom responses to the client. You can use the following code to create @ControllerAdvice class to handle the exceptions globally − package com.tutorialspoint.demo.exception; import org.springframework.web.bind.annotation.ControllerAdvice; @ControllerAdvice public class ProductExceptionController { } Define a class that extends the RuntimeException class. package com.tutorialspoint.demo.exception; public class ProductNotfoundException extends RuntimeException { private static final long serialVersionUID = 1L; } You can define the @ExceptionHandler method to handle the exceptions as shown. This method should be used for writing the Controller Advice class file. @ExceptionHandler(value = ProductNotfoundException.class) public ResponseEntity<Object> exception(ProductNotfoundException exception) { } Now, use the code given below to throw the exception from the API. @RequestMapping(value = “/products/{id}”, method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct() { throw new ProductNotfoundException(); } The complete code to handle the exception is given below. In this example, we used the PUT API to update the product. Here, while updating the product, if the product is not found, then return the response error message as “Product not found”. Note that the ProductNotFoundException exception class should extend the RuntimeException. package com.tutorialspoint.demo.exception; public class ProductNotfoundException extends RuntimeException { private static final long serialVersionUID = 1L; } The Controller Advice class to handle the exception globally is given below. We can define any Exception Handler methods in this class file. package com.tutorialspoint.demo.exception; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class ProductExceptionController { @ExceptionHandler(value = ProductNotfoundException.class) public ResponseEntity<Object> exception(ProductNotfoundException exception) { return new ResponseEntity<>(“Product not found”, HttpStatus.NOT_FOUND); } } The Product Service API controller file is given below to update the Product. If the Product is not found, then it throws the ProductNotFoundException class. package com.tutorialspoint.demo.controller; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.tutorialspoint.demo.exception.ProductNotfoundException; import com.tutorialspoint.demo.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); static { Product honey = new Product(); honey.setId(“1”); honey.setName(“Honey”); productRepo.put(honey.getId(), honey); Product almond = new Product(); almond.setId(“2”); almond.setName(“Almond”); productRepo.put(almond.getId(), almond); } @RequestMapping(value = “/products/{id}”, method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct(@PathVariable(“id”) String id, @RequestBody Product product) { if(!productRepo.containsKey(id))throw new ProductNotfoundException(); productRepo.remove(id); product.setId(id); productRepo.put(id, product); return new ResponseEntity<>(“Product is updated successfully”, HttpStatus.OK); } } The code for main Spring Boot application class file is given below − package com.tutorialspoint.demo; 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); } } The code for POJO class for Product is given below − package com.tutorialspoint.demo.model; public class Product { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } The code for Maven build – pom.xml is shown below − <?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>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>demo</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath/> </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.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> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> The code for Gradle Build – build.gradle is given below − buildscript { ext { springBootVersion = ”1.5.8.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.springframework.boot:spring-boot-starter-web”) 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 − For Maven, you can use the following command − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the following command − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. You can run the JAR file by using the following command − java –jar <JARFILE> This will start the application on the Tomcat port 8080 as shown below − Now hit the below URL in POSTMAN application and you can see the output as shown below − Update URL: http://localhost:8080/products/3 Print Page Previous Next Advertisements ”;