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
Category: Java
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 ”;
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 MVC – Overview
Spring – MVC Framework Overview ”; Previous Next The Spring Web MVC framework provides a model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The Model encapsulates the application data and in general, they will consist of POJO. The View is responsible for rendering the model data and in general, it generates HTML output that the client”s browser can interpret. The Controller is responsible for processing User Requests and Building Appropriate Model and passes it to the view for rendering. The DispatcherServlet The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is shown in the following illustration. Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet − After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller. The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet. The DispatcherServlet will take help from ViewResolver to pick up the defined view for the request. Once view is finalized, The DispatcherServlet passes the model data to the view, which is finally rendered, on the browsers. All the above-mentioned components, i.e. HandlerMapping, Controller and ViewResolver are parts of WebApplicationContext, which is an extension of the plain ApplicationContext with some extra features necessary for web applications. Required Configuration We need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the web.xml file. The following is an example to show declaration and mapping for HelloWeb DispatcherServlet − <web-app id = “WebApp_ID” version = “2.4” xmlns = “http://java.sun.com/xml/ns/j2ee” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”> <display-name>Spring MVC Application</display-name> <servlet> <servlet-name>HelloWeb</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloWeb</servlet-name> <url-pattern>*.jsp</url-pattern> </servlet-mapping> </web-app> The web.xml file will be kept in the WebContent/WEB-INF directory of your web application. Upon initialization of the HelloWeb DispatcherServlet, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the application”s WebContent/WEB-INF directory. In this case, our file will be HelloWeb-servlet.xml. Next, the <servlet-mapping> tag indicates which URLs will be handled by which DispatcherServlet. Here, all the HTTP requests ending with .jsp will be handled by the HelloWeb DispatcherServlet. If you do not want to go with the default filename as [servlet-name]-servlet.xml and default location as WebContent/WEB-INF, you can customize this file name and location by adding the servlet listener ContextLoaderListener in your web.xml file as follows − <web-app…> <!——– DispatcherServlet definition goes here—–> …. <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/HelloWeb-servlet.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> </web-app> Now, let us check the required configuration for HelloWeb-servlet.xml file, placed in your web application”s WebContent/WEB-INF directory. <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:context = “http://www.springframework.org/schema/context” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = ” http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> </beans> Following are some important points about HelloWeb-servlet.xml file − The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope. The <context:component-scan…> tag will be used to activate the Spring MVC annotation scanning capability, which allows to make use of annotations like @Controller and @RequestMapping, etc. The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above-defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp. Let us now understand how to create the actual components i.e., Controller, Model and View. Defining a Controller The DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controller annotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method. @Controller @RequestMapping(“/hello”) public class HelloController{ @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } The @Controller annotation defines the class as a Spring MVC controller. Here, the first usage of @RequestMapping indicates that all handling methods on this controller are relative to the /hello path. The next annotation @RequestMapping (method = RequestMethod.GET) is used to declare the printHello() method as the controller”s default service method to handle HTTP GET request. We can define another method to handle any POST request at the same URL. We can also write the above controller in another form, where we can add additional attributes in the @RequestMapping as follows − @Controller public class HelloController{ @RequestMapping(value = “/hello”, method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } The value attribute indicates the URL to which the handler method is mapped and the method attribute defines the service method to handle the HTTP GET request. Following are some important points to be noted regarding the controller defined above − You will define the required business logic inside a service method. You can call another method inside this method as per the requirement. Based on the business logic defined, you will create a model within this method. You can set different model attributes and these attributes will be accessed by the view to present the result. This example creates a model with its attribute “message”. A defined service method can return a String, which contains the name of the view to be used to render the model. This example returns “hello” as the logical view name. Creating JSP Views Spring MVC supports many types of views for different presentation technologies. These include – JSPs, HTML,
Spring Security – Discussion
Discuss Spring Security ”; Previous Next In this tutorial, we will learn about Spring Security Frameworks. We will start with the basics and go through the configuration of various frameworks to work with Spring Security. We will also do some handson coding to perform CRUD operation using Spring Security Frameworks. Print Page Previous Next Advertisements ”;
TestNG – Parameterized Test
TestNG – Parameterized Test ”; Previous Next Another interesting feature available in TestNG is parametric testing. In most cases, you”ll come across a scenario where the business logic requires a hugely varying number of tests. Parameterized tests allow developers to run the same test over and over again using different values. TestNG lets you pass parameters directly to your test methods in two different ways − With testng.xml With Data Providers Passing Parameters with testng.xml With this technique, you define the simple parameters in the testng.xml file and then reference those parameters in the source files. Let us have an example to demonstrate how to use this technique to pass parameters. Create Test Case Class Create a java test class, say, ParameterizedTest1.java. Add test method parameterTest() to your test class. This method takes a string as input parameter. Add the annotation @Parameters(“myName”) to this method. The parameter would be passed a value from testng.xml, which we will see in the next step. Create a java class file named ParameterizedTest1.java in /work/testng/src. import org.testng.annotations.Parameters; import org.testng.annotations.Test; public class ParameterizedTest1 { @Test @Parameters(“myName”) public void parameterTest(String myName) { System.out.println(“Parameterized value is : ” + myName); } } Create testng.xml Create testng.xml in /work/testng/src to execute test case(s). <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” > <suite name = “Suite1”> <test name = “test1”> <parameter name = “myName” value=”manisha”/> <classes> <class name = “ParameterizedTest1″ /> </classes> </test> </suite> We can also define the parameters at the <suite> level. Suppose we have defined myName at both <suite> and <test> levels. In such cases, regular scoping rules apply. It means that any class inside <test> tag will see the value of parameter defined in <test>, while the classes in the rest of the testng.xml file will see the value defined in <suite>. Compile the test case class using javac. /work/testng/src$ javac ParameterizedTest1.java Now, run testng.xml, which will run the parameterTest method. TestNG will try to find a parameter named myName first in the <test> tag, and then, if it can’t find it, it searches in the <suit> tag that encloses it. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. Parameterized value is : manisha =============================================== Suite1 Total tests run: 1, Failures: 0, Skips: 0 =============================================== TestNG will automatically try to convert the value specified in testng.xml to the type of your parameter. Here are the types supported − String int/Integer boolean/Boolean byte/Byte char/Character double/Double float/Float long/Long short/Short Passing Parameters with Dataproviders When you need to pass complex parameters or parameters that need to be created from Java (complex objects, objects read from a property file or a database, etc.), parameters can be passed using Dataproviders. A Data Provider is a method annotated with @DataProvider. This annotation has only one string attribute: its name. If the name is not supplied, the data provider’s name automatically defaults to the method’s name. A data provider returns an array of objects. The following examples demonstrate how to use data providers. The first example is about @DataProvider using Vector, String, or Integer as parameter, and the second example is about @DataProvider using object as parameter. Example 1 Here, the @DataProvider passes Integer and Boolean as parameter. Create Java class Create a java class called PrimeNumberChecker.java. This class checks if the number is prime. Create this class in /work/testng/src. public class PrimeNumberChecker { public Boolean validate(final Integer primeNumber) { for (int i = 2; i < (primeNumber / 2); i++) { if (primeNumber % i == 0) { return false; } } return true; } } Create Test Case Class Create a java test class, say, ParamTestWithDataProvider1.java in /work/testng/src. Define the method primeNumbers(), which is defined as a Data provider using the annotation. This method returns an array of objects. Add the test method testPrimeNumberChecker() to your test class. This method takes an Integer and Boolean as input parameters. This method validates if the parameter passed is a prime number. Add the annotation @Test(dataProvider = “test1”) to this method. The attribute dataProvider is mapped to “test1”. Following are the contents of ParamTestWithDataProvider1.java. import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class ParamTestWithDataProvider1 { private PrimeNumberChecker primeNumberChecker; @BeforeMethod public void initialize() { primeNumberChecker = new PrimeNumberChecker(); } @DataProvider(name = “test1”) public static Object[][] primeNumbers() { return new Object[][] {{2, true}, {6, false}, {19, true}, {22, false}, {23, true}}; } // This test will run 4 times since we have 5 parameters defined @Test(dataProvider = “test1″) public void testPrimeNumberChecker(Integer inputNumber, Boolean expectedResult) { System.out.println(inputNumber + ” ” + expectedResult); Assert.assertEquals(expectedResult, primeNumberChecker.validate(inputNumber)); } } Create testng.xml Create a testng.xml /work/testng/src to execute Test case(s). <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” > <suite name = “Suite1”> <test name = “test1”> <classes> <class name = “ParamTestWithDataProvider1″ /> </classes> </test> </suite> Compile the Test case class using javac. /work/testng/src$ javac ParamTestWithDataProvider1.java PrimeNumberChecker.java Now, run testng.xml. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. 2 true 6 false 19 true 22 false 23 true =============================================== Suite1 Total tests run: 5, Failures: 0, Skips: 0 =============================================== Example 2 Here, the @DataProvider passes Object as parameter. Create Java class Create a java class Bean.java, which is a simple object with get/set methods, in /work/testng/src. public class Bean { private String val; private int i; public Bean(String val, int i) { this.val = val; this.i = i; } public String getVal() { return val; } public void setVal(String val) { this.val = val; } public int getI() { return i; } public void setI(int i) { this.i = i; } } Create Test Case Class Create a java test class, say, ParamTestWithDataProvider2.java. Define the method primeNumbers(), which is defined as a data provider using annotation. This method returns an array of object. Add the test method testMethod() to your test class. This method takes an object bean as parameter. Add the annotation @Test(dataProvider = “test1”) to this method. The attribute dataProvider is mapped to “test1”. Create a java class file named ParamTestWithDataProvider2.java in /work/testng/src. import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public
Example – Toolbars
Swing Examples – Toolbars ”; Previous Next Learn how to play with Toolbars in Swing UI programming. Here are most commonly used examples − How to create a toolbar with buttons in Swing? How to create an immovaable toolbar in Swing? Print Page Previous Next Advertisements ”;