TestNG – Run JUnit Tests ”; Previous Next Now that you have understood TestNG and its various tests, you must be worried by now as to how to refactor your existing JUnit code. There”s no need to worry, as TestNG provides a way to shift from JUnit to TestNG at your own pace. You can execute your existing JUnit test cases using TestNG. TestNG can automatically recognize and run JUnit tests, so that you can use TestNG as a runner for all your existing tests and write new tests using TestNG. All you have to do is to put JUnit library on the TestNG classpath, so it can find and use JUnit classes, change your test runner from JUnit to TestNG in Ant, and then run TestNG in “mixed” mode. This way, you can have all your tests in the same project, even in the same package, and start using TestNG. This approach also allows you to convert your existing JUnit tests to TestNG incrementally. Let us have an example to demonstrate this amazing ability of TestNG. Create JUnit Test Case Class Create a java class, which is a JUnit test class, TestJunit.java in /work/testng/src. import org.junit.Test; import static org.testng.AssertJUnit.*; public class TestJunit { @Test public void testAdd() { String str = “Junit testing using TestNG”; assertEquals(“Junit testing using TestNG”,str); } } 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 = “Converted JUnit suite” > <test name = “JUnitTests” junit=”true”> <classes> <class name = “TestJunit” /> </classes> </test> </suite> To execute the JUnit test cases, define the property junit=”true” as in the xml above. The JUnit test case class TestJunit is defined in class name. For JUnit 4, TestNG will use the org.junit.runner.JUnitCore runner to run your tests. Compile all java classes using javac. /work/testng/src$ javac TestJunit.java Now, run testng.xml, which will run the JUnit test case as TestNG. /work/testng/src$java -cp “/work/testng/src/junit-4.13.2.jar:/work/testng/src/hamcrest-core-1.3.jar” org.testng.TestNG testng.xml Here, we have placed the dependent JAR files junit-4.13.2.jar and hamcrest-core-1.3.jar under /work/testng/src/. Verify the output. =============================================== Converted JUnit suite Total tests run: 1, Passes: 1, Failures: 0, Skips: 0 =============================================== Print Page Previous Next Advertisements ”;
Category: Java
Spring Boot – Enabling HTTPS
Spring Boot – Enabling HTTPS ”; Previous Next By default, Spring Boot application uses HTTP 8080 port when the application starts up. You need to follow the steps given below to configure the HTTPS and the port 443 in Spring Boot application − Obtain the SSL certificate – Create a self-signed certificate or get one from a Certificate Authority Enable HTTPS and 443 port Self-Signed Certificate To create a self-signed certificate, Java Run Time environment comes bundled with certificate management utility key tool. This utility tool is used to create a Self-Signed certificate. It is shown in the code given here − keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650 Enter keystore password: Re-enter new password: What is your first and last name? [Unknown]: What is the name of your organizational unit? [Unknown]: What is the name of your organization? [Unknown]: What is the name of your City or Locality? [Unknown]: What is the name of your State or Province? [Unknown]: What is the two-letter country code for this unit? [Unknown]: Is CN = Unknown, OU=Unknown, O = Unknown, L = Unknown, ST = Unknown, C = Unknown correct? [no]: yes This code will generate a PKCS12 keystore file named as keystore.p12 and the certificate alias name is tomcat. Configure HTTPS We need to provide the server port as 443, key-store file path, key-store-password, key-store-type and key alias name into the application.properties file. Observe the code given here − server.port: 443 server.ssl.key-store: keystore.p12 server.ssl.key-store-password: springboot server.ssl.keyStoreType: PKCS12 server.ssl.keyAlias: tomcat You can use the following code if you are using YAML properties use below application.yml − server: port: 443 ssl: key-store: keystore.p12 key-store-password: springboot keyStoreType: PKCS12 keyAlias: tomcat You can create an executable JAR file, and run the spring boot application by using the following 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 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 following command − java –jar <JARFILE> Now, the application has started on the Tomcat port 443 with https as shown − Print Page Previous Next Advertisements ”;
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 ”; 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 – Rest Template
Spring Boot – Rest Template ”; Previous Next Rest Template is used to create applications that consume RESTful Web Services. You can use the exchange() method to consume the web services for all HTTP methods. The code given below shows how to create Bean for Rest Template to auto wiring the Rest Template object. package com.tutorialspoint.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } } GET Consuming the GET API by using RestTemplate – exchange() method Assume this URL http://localhost:8080/products returns the following JSON and we are going to consume this API response by using Rest Template using the following code − [ { “id”: “1”, “name”: “Honey” }, { “id”: “2”, “name”: “Almond” } ] You will have to follow the given points to consume the API − Autowired the Rest Template Object. Use HttpHeaders to set the Request Headers. Use HttpEntity to wrap the request object. Provide the URL, HttpMethod, and Return type for Exchange() method. @RestController public class ConsumeWebService { @Autowired RestTemplate restTemplate; @RequestMapping(value = “/template/products”) public String getProductList() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity <String> entity = new HttpEntity<String>(headers); return restTemplate.exchange(” http://localhost:8080/products”, HttpMethod.GET, entity, String.class).getBody(); } } POST Consuming POST API by using RestTemplate – exchange() method Assume this URL http://localhost:8080/products returns the response shown below, we are going to consume this API response by using the Rest Template. The code given below is the Request body − { “id”:”3″, “name”:”Ginger” } The code given below is the Response body − Product is created successfully You will have to follow the points given below to consume the API − Autowired the Rest Template Object. Use the HttpHeaders to set the Request Headers. Use the HttpEntity to wrap the request object. Here, we wrap the Product object to send it to the request body. Provide the URL, HttpMethod, and Return type for exchange() method. @RestController public class ConsumeWebService { @Autowired RestTemplate restTemplate; @RequestMapping(value = “/template/products”, method = RequestMethod.POST) public String createProducts(@RequestBody Product product) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(product,headers); return restTemplate.exchange( “http://localhost:8080/products”, HttpMethod.POST, entity, String.class).getBody(); } } PUT Consuming PUT API by using RestTemplate – exchange() method Assume this URL http://localhost:8080/products/3 returns the below response and we are going to consume this API response by using Rest Template. The code given below is Request body − { “name”:”Indian Ginger” } The code given below is the Response body − Product is updated successfully You will have to follow the points given below to consume the API − Autowired the Rest Template Object. Use HttpHeaders to set the Request Headers. Use HttpEntity to wrap the request object. Here, we wrap the Product object to send it to the request body. Provide the URL, HttpMethod, and Return type for exchange() method. @RestController public class ConsumeWebService { @Autowired RestTemplate restTemplate; @RequestMapping(value = “/template/products/{id}”, method = RequestMethod.PUT) public String updateProduct(@PathVariable(“id”) String id, @RequestBody Product product) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(product,headers); return restTemplate.exchange( “http://localhost:8080/products/”+id, HttpMethod.PUT, entity, String.class).getBody(); } } DELETE Consuming DELETE API by using RestTemplate – exchange() method Assume this URL http://localhost:8080/products/3 returns the response given below and we are going to consume this API response by using Rest Template. This line of code shown below is the Response body − Product is deleted successfully You will have to follow the points shown below to consume the API − Autowired the Rest Template Object. Use HttpHeaders to set the Request Headers. Use HttpEntity to wrap the request object. Provide the URL, HttpMethod, and Return type for exchange() method. @RestController public class ConsumeWebService { @Autowired RestTemplate restTemplate; @RequestMapping(value = “/template/products/{id}”, method = RequestMethod.DELETE) public String deleteProduct(@PathVariable(“id”) String id) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(headers); return restTemplate.exchange( “http://localhost:8080/products/”+id, HttpMethod.DELETE, entity, String.class).getBody(); } } The complete Rest Template Controller class file is given below − package com.tutorialspoint.demo.controller; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; 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 org.springframework.web.client.RestTemplate; import com.tutorialspoint.demo.model.Product; @RestController public class ConsumeWebService { @Autowired RestTemplate restTemplate; @RequestMapping(value = “/template/products”) public String getProductList() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<String> entity = new HttpEntity<String>(headers); return restTemplate.exchange( “http://localhost:8080/products”, HttpMethod.GET, entity, String.class).getBody(); } @RequestMapping(value = “/template/products”, method = RequestMethod.POST) public String createProducts(@RequestBody Product product) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(product,headers); return restTemplate.exchange( “http://localhost:8080/products”, HttpMethod.POST, entity, String.class).getBody(); } @RequestMapping(value = “/template/products/{id}”, method = RequestMethod.PUT) public String updateProduct(@PathVariable(“id”) String id, @RequestBody Product product) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(product,headers); return restTemplate.exchange( “http://localhost:8080/products/”+id, HttpMethod.PUT, entity, String.class).getBody(); } @RequestMapping(value = “/template/products/{id}”, method = RequestMethod.DELETE) public String deleteProduct(@PathVariable(“id”) String id) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); HttpEntity<Product> entity = new HttpEntity<Product>(headers); return restTemplate.exchange( “http://localhost:8080/products/”+id, HttpMethod.DELETE, entity, String.class).getBody(); } } The code for Spring Boot Application Class – DemoApplication.java 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 given 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
Struts2 Questions and Answers ”; Previous Next Struts2 Questions and Answers has been designed with a special intention of helping students and professionals preparing for various Certification Exams and Job Interviews. This section provides a useful collection of sample Interview Questions and Multiple Choice Questions (MCQs) and their answers with appropriate explanations. SN Question/Answers Type 1 Struts2 Interview Questions This section provides a huge collection of Struts2 Interview Questions with their answers hidden in a box to challenge you to have a go at them before discovering the correct answer. 2 Struts2 Online Quiz This section provides a great collection of Struts2 Multiple Choice Questions (MCQs) on a single page along with their correct answers and explanation. If you select the right option, it turns green; else red. 3 Struts2 Online Test If you are preparing to appear for a Java and Struts2 Framework related certification exam, then this section is a must for you. This section simulates a real online test along with a given timer which challenges you to complete the test within a given time-frame. Finally you can check your overall test score and how you fared among millions of other candidates who attended this online test. 4 Struts2 Mock Test This section provides various mock tests that you can download at your local machine and solve offline. Every mock test is supplied with a mock test key to let you verify the final score and grade yourself. Print Page Previous Next Advertisements ”;
Spring Boot – Building RESTful Web Services ”; Previous Next Spring Boot provides a very good support to building RESTful Web Services for enterprise applications. This chapter will explain in detail about building RESTful web services using Spring Boot. Note − For building a RESTful Web Services, we need to add the Spring Boot Starter Web dependency into the build configuration file. If you are a Maven user, use the following code to add the below dependency in your pom.xml file − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> If you are a Gradle user, use the following code to add the below dependency in your build.gradle file. compile(”org.springframework.boot:spring-boot-starter-web”) The code for complete build configuration file Maven build – pom.xml is given 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 complete build configuration file 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”) } Before you proceed to build a RESTful web service, it is suggested that you have knowledge of the following annotations − Rest Controller The @RestController annotation is used to define the RESTful web services. It serves JSON, XML and custom response. Its syntax is shown below − @RestController public class ProductServiceController { } Request Mapping The @RequestMapping annotation is used to define the Request URI to access the REST Endpoints. We can define Request method to consume and produce object. The default request method is GET. @RequestMapping(value = “/products”) public ResponseEntity<Object> getProducts() { } Request Body The @RequestBody annotation is used to define the request body content type. public ResponseEntity<Object> createProduct(@RequestBody Product product) { } Path Variable The @PathVariable annotation is used to define the custom or dynamic request URI. The Path variable in request URI is defined as curly braces {} as shown below − public ResponseEntity<Object> updateProduct(@PathVariable(“id”) String id) { } Request Parameter The @RequestParam annotation is used to read the request parameters from the Request URL. By default, it is a required parameter. We can also set default value for request parameters as shown here − public ResponseEntity<Object> getProduct( @RequestParam(value = “name”, required = false, defaultValue = “honey”) String name) { } GET API The default HTTP request method is GET. This method does not require any Request Body. You can send request parameters and path variables to define the custom or dynamic URL. The sample code to define the HTTP GET request method is shown below. In this example, we used HashMap to store the Product. Note that we used a POJO class as the product to be stored. Here, the request URI is /products and it will return the list of products from HashMap repository. The controller class file is given below that contains GET method REST Endpoint. 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.RequestMapping; import org.springframework.web.bind.annotation.RestController; 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”) public ResponseEntity<Object> getProduct() { return new ResponseEntity<>(productRepo.values(), HttpStatus.OK); } } POST API The HTTP POST request is used to create a resource. This method contains the Request Body. We can send request parameters and path variables to define the custom or dynamic URL. The following example shows the sample code to define the HTTP POST request method. In this example, we used HashMap to store the Product, where the product is a POJO class. Here, the request URI is /products, and it will return the String after storing the product into HashMap repository. 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.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; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); @RequestMapping(value = “/products”, method = RequestMethod.POST) public ResponseEntity<Object> createProduct(@RequestBody Product product) { productRepo.put(product.getId(), product); return new ResponseEntity<>(“Product is created successfully”, HttpStatus.CREATED); } } PUT API The HTTP PUT request is used to update the existing resource. This method contains a Request Body. We can send request parameters and path variables to define the custom or dynamic URL. The example given below shows how to define the HTTP PUT request method. In this example, we used HashMap to update the existing Product, where the product is a POJO class. Here the request URI is /products/{id} which will return the String after a the product into a HashMap repository. Note that we used the Path variable {id} which defines the products ID that needs to be updated. 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.model.Product; @RestController public class ProductServiceController { private static Map<String, Product> productRepo = new HashMap<>(); @RequestMapping(value = “/products/{id}”, method = RequestMethod.PUT) public ResponseEntity<Object> updateProduct(@PathVariable(“id”) String id, @RequestBody Product product) { productRepo.remove(id); product.setId(id); productRepo.put(id, product); return new ResponseEntity<>(“Product is updated successsfully”, HttpStatus.OK); } } DELETE API The HTTP Delete request is used to delete the existing resource. This method does not contain any Request Body. We can send request parameters and path variables to define the custom or dynamic URL. The example given below shows how to define the HTTP DELETE request method. In this example, we used HashMap to remove the existing product, which is a POJO class. The request URI is /products/{id} and it will return the String after deleting the product from HashMap repository. We used the
Struts2 – Validations
Struts 2 – Validations Framework ”; Previous Next In this chapter, we shall look deeper into Struts validation framework. At the Struts core, we have the validation framework that assists the application to run the rules to perform validation before the action method is executed. Client side validation is usually achieved using Javascript. However, one should not rely upon client side validation alone. The best practices suggest that the validation should be introduced at all levels of your application framework. Now let us look at two ways of adding validation to our Struts project. Here, we will take an example of an Employee whose name and age should be captured using a simple page, and we will put these two validations to make sure that the user always enters a name and age which should be in a range 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 will be 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 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 So let us define a small action class Employee, 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; public class Employee extends ActionSupport { private String name; private int age; public String execute() { return SUCCESS; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void validate() { if (name == null || name.trim().equals(“”)) { addFieldError(“name”,”The name is required”); } if (age < 28 || age > 65) { addFieldError(“age”,”Age must be in between 28 and 65″); } } } As shown in the above example, the validation method checks whether the ”Name” field has a value or not. If no value has been supplied, we add a field error for the ”Name” field with a custom error message. Secondly, we check if entered value for ”Age” field is in between 28 and 65 or not, if this condition does not meet we add an error above the validated field. Configuration Files Finally, let us put everything together using the struts.xml configuration file as follows − <?xml version = “1.0” Encoding = “UTF-8”?> <!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” “http://struts.apache.org/dtds/struts-2.0.dtd”> <struts> <constant name = “struts.devMode” value = “true” /> <package name = “helloworld” extends = “struts-default”> <action name = “empinfo” class = “com.tutorialspoint.struts2.Employee” method = “execute”> <result name = “input”>/index.jsp</result> <result name = “success”>/success.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 − 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 − How this Validation Works? When the user presses the submit button, Struts 2 will automatically execute the validate method and if any of the “if” statements listed inside the method are true, Struts 2 will call its addFieldError method. If any errors have been added, then Struts 2 will not proceed to call the execute method. Rather the Struts 2 framework will return input as the result of calling the action. Hence, when validation fails and Struts 2 returns input, the Struts 2 framework will redisplay the index.jsp file. Since, we used Struts 2 form tags, Struts 2 will automatically add the error messages just above the form filed. These error messages are the ones we specified in the addFieldError method call. The addFieldError method takes two arguments. The first, is the form field name to which the error applies and the second, is the error message to display above that form field. addFieldError(“name”,”The name is required”); To handle the return value of input we need to add the following result to our action node in struts.xml. <result name = “input”>/index.jsp</result> XML Based Validation The second method of doing validation is by placing an xml file next to the action class. Struts2 XML based validation provides more
Struts2 – Spring
Struts 2 & Spring Integration ”; Previous Next Spring is a popular web framework that provides easy integration with lots of common web tasks. So the question is, why do we need Spring when we have Struts2? Well, Spring is more than a MVC framework – it offers many other goodies which are not available in Struts. For example: dependency injection that can be useful to any framework. In this chapter, we will go through a simple example to see how to integrate Spring and Struts2 together. First of all, you need to add the following files to the project”s build path from Spring installation. You can download and install latest version of Spring Framework from https://www.springsource.org/download org.springframework.asm-x.y.z.M(a).jar org.springframework.beans-x.y.z.M(a).jar org.springframework.context-x.y.z.M(a).jar org.springframework.core-x.y.z.M(a).jar org.springframework.expression-x.y.z.M(a).jar org.springframework.web-x.y.z.M(a).jar org.springframework.web.servlet-x.y.z.M(a).jar Finally add struts2-spring-plugin-x.y.z.jar in your WEB-INF/lib from your struts lib directory. If you are using Eclipse then you may face an exception java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener. To fix this problem, you should have to go in Marker tab and righ click on the class dependencies one by one and do Quick fix to publish/export all the dependences. Finally make sure there is no dependency conflict available under the marker tab. Now let us setup the web.xml for the Struts-Spring integration as follows − <?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> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <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> The important thing to note here is the listener that we have configured. The ContextLoaderListener is required to load the spring context file. Spring”s configuration file is called applicationContext.xml file and it must be placed at the same level as the web.xml file Let us create a simple action class called User.java with two properties – firstName and lastName. package com.tutorialspoint.struts2; public class User { private String firstName; private String lastName; public String execute() { return “success”; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } } Now let us create the applicationContext.xml spring configuration file and instantiate the User.java class. As mentioned earlier, this file should be under the WEB-INF folder − <?xml version = “1.0” Encoding = “UTF-8”?> <!DOCTYPE beans PUBLIC “-//SPRING//DTD BEAN//EN” “http://www.springframework.org/dtd/spring-beans.dtd”> <beans> <bean id = “userClass” class = “com.tutorialspoint.struts2.User”> <property name = “firstName” value = “Michael” /> <property name = “lastName” value = “Jackson” /> </bean> </beans> As seen above, we have configured the user bean and we have injected the values Michael and Jackson into the bean. We have also given this bean a name “userClass”, so that we can reuse this elsewhere. Next let us create the User.jsp in the WebContent folder − <%@ 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 – Spring integration</h1> <s:form> <s:textfield name = “firstName” label = “First Name”/><br/> <s:textfield name = “lastName” label = “Last Name”/><br/> </s:form> </body> </html> The User.jsp file is pretty straight forward. It serves only one purpose – to display the values of the firstname and lastname of the user object. Finally, let us put all entities together using the struts.xml file. <?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 = “user” class=”userClass” method = “execute”> <result name = “success”>/User.jsp</result> </action> </package> </struts> The important thing to note is that we are using the id userClass to refer to the class. This means that we are using spring to do the dependency injection for the User class. 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/User.jsp. This will produce the following screen − We have now seen how to bring two great frameworks together. This concludes the Struts – Spring integration chapter. Print Page Previous Next Advertisements ”;