Struts 2 – Quick Guide ”; Previous Next Basic MVC Architecture Model View Controller or MVC as it is popularly called, is a software design pattern for developing web applications. A Model View Controller pattern is made up of the following three parts − Model − The lowest level of the pattern which is responsible for maintaining data. View − This is responsible for displaying all or a portion of the data to the user. Controller − Software Code that controls the interactions between the Model and View. MVC is popular as it isolates the application logic from the user interface layer and supports separation of concerns. Here the Controller receives all requests for the application and then works with the Model to prepare any data needed by the View. The View then uses the data prepared by the Controller to generate a final presentable response. The MVC abstraction can be graphically represented as follows. The Model The model is responsible for managing the data of the application. It responds to the request from the view and it also responds to instructions from the controller to update itself. The View It means presentation of data in a particular format, triggered by a controller”s decision to present the data. They are script-based templating systems like JSP, ASP, PHP and very easy to integrate with AJAX technology. The Controller The controller is responsible for responding to the user input and perform interactions on the data model objects. The controller receives the input, it validates the input and then performs the business operation that modifies the state of the data model. Struts2 is a MVC based framework. In the coming chapters, let us see how we can use the MVC methodology within Struts2. Struts 2 – Overview Struts2 is a popular and mature web application framework based on the MVC design pattern. Struts2 is not just a new version of Struts 1, but it is a complete rewrite of the Struts architecture. The Webwork framework initially started with Struts framework as the basis and its goal was to offer an enhanced and improved framework built on Struts to make web development easier for the developers. After a while, the Webwork framework and the Struts community joined hands to create the famous Struts2 framework. Struts 2 Framework Features Here are some of the great features that may force you to consider Struts2 − POJO Forms and POJO Actions − Struts2 has done away with the Action Forms that were an integral part of the Struts framework. With Struts2, you can use any POJO to receive the form input. Similarly, you can now see any POJO as an Action class. Tag Support − Struts2 has improved the form tags and the new tags which allow the developers to write less code. AJAX Support − Struts2 has recognized the take over by Web2.0 technologies, and has integrated AJAX support into the product by creating AJAX tags, this function is very similar to the standard Struts2 tags. Easy Integration − Integration with other frameworks like Spring, Tiles and SiteMesh is now easier with a variety of integration available with Struts2. Template Support − Support for generating views using templates. Plugin Support − The core Struts2 behavior can be enhanced and augmented by the use of plugins. A number of plugins are available for Struts2. Profiling − Struts2 offers integrated profiling to debug and profile the application. In addition to this, Struts also offers integrated debugging with the help of built in debugging tools. Easy to Modify Tags − Tag markups in Struts2 can be tweaked using Freemarker templates. This does not require JSP or java knowledge. Basic HTML, XML and CSS knowledge is enough to modify the tags. Promote Less configuration − Struts2 promotes less configuration with the help of using default values for various settings. You don”t have to configure something unless it deviates from the default settings set by Struts2. View Technologies − Struts2 has a great support for multiple view options (JSP, Freemarker, Velocity and XSLT) Listed above are the Top 10 features of Struts 2 which makes it as an Enterprise ready framework. Struts 2 Disadvantages Though Struts 2 comes with a list of great features, there are some limitations of the current version – Struts 2 which needs further improvement. Listed are some of the main points − Bigger Learning Curve − To use MVC with Struts, you have to be comfortable with the standard JSP, Servlet APIs and a large & elaborate framework. Poor Documentation − Compared to the standard servlet and JSP APIs, Struts has fewer online resources, and many first-time users find the online Apache documentation confusing and poorly organized. Less Transparent − With Struts applications, there is a lot more going on behind the scenes than with normal Java-based Web applications which makes it difficult to understand the framework. Final note, a good framework should provide generic behavior that many different types of applications can make use of it. Struts 2 is one of the best web frameworks and being highly used for the development of Rich Internet Applications (RIA). Struts 2 – Environment Setup Our first task is to get a minimal Struts 2 application running. This chapter will guide you on how to prepare a development environment to start your work with Struts 2. I assume that you already have JDK (5+), Tomcat and Eclipse installed on your machine. If you do not have these components installed, then follow the given steps on fast track − Step 1 – Setup Java Development Kit (JDK) You can download the latest version of SDK from Oracle”s Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally, set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and installed the SDK in
Category: Java
Spring ORM – Discussion
Discuss Spring ORM ”; Previous Next The Spring Framework integrates well with ORM frameworks like Hibernate, Java Persistence API (JPA), Java Data Objects (JDO) and iBATIS SQL Maps. Spring provides resource management, data access object (DAO) implementations, and transaction strategies. Print Page Previous Next Advertisements ”;
Spring ORM – Overview
Spring ORM – Overview ”; Previous Next The Spring Framework integrates well with ORM frameworks like Hibernate, Java Persistence API (JPA), Java Data Objects (JDO) and iBATIS SQL Maps. Spring provides resource management, data access object (DAO) implementations, and transaction strategies. Spring allows to configure ORM library features through dependency management. Spring maintains a uniform DAO Exception hiearchies and a generic transaction management for all the ORM libraries it supports. Spring IoC container facilitates ORM configurations and easy deployment. Following are the key benefits of using Spring framework to create ORM DAO. Easy to Test − Using spring IoC, an ORM implementation can be easily configured. Each piece of persistence unit can be tested in isolation. Common Data Access Exception − Spring wraps ORM Tools exceptions to a common runtime exception as DataAccessException. This approach helps to handle most persistence exception (non-recoverable) in appropriate layers. No need to handle ORM specific boilerplate catch/throws/exception declarations. General Resource Management − Spring application contexts manages persistence objects, their configurations easily. For example, Hibernate SessionFactory instances, JPA EntityManagerFactory instances, JDBC DataSource instances, iBatis SQL Maps configuration objects and other related objects. Spring handles the local as well JTA transaction management by itself. Integrated transaction management − Spring AOP can be used to wrap an ORM code with a declarative AOP styled interceptor either using @Transaction annotation or by specifying transaction AOP advice in XML configuration file. Spring handles transaction semantics, exception handling, rollback and so on. Spring allows to swap transaction managers without affecting the ORM code. Print Page Previous Next Advertisements ”;
Example – Frames
Swing Examples – Frames ”; Previous Next How to create a standard window in Swing? How to change the look and feel of a swing window? How to set the look and feel of a swing window as current system? How to change the default icon of a swing window? How to respond to windows event of a swing window? Print Page Previous Next Advertisements ”;
Example – Scroll Panes
Swing Examples – ScrollPanes ”; Previous Next Learn how to play with ScrollPanes in Swing UI programming. Here are most commonly used examples − How to create and use a scroll pane in java swing application? How to add a vertical scrollbar in Java Swing application? How to add a horizontal scrollbar in Java Swing application? Print Page Previous Next Advertisements ”;
Example – Layouts
Swing Examples – Layouts ”; Previous Next Learn how to play with Layouts in Swing UI programming. Here are most commonly used examples − Example of BoxLayout in swing? Example of GridLayout in swing? Example of FlowLayout in swing? Example of BorderLayout in swing? Example of GridBagLayout in swing? Example of CardLayout in swing? Example of GroupLayout in swing? Example of SpringLayout in swing? Example of Split Pane with horizontal split in swing? Example of Split Pane with vertical split in swing? Example of Tabbed Pane in Swing? How to show a tabbed window with icon tabs in Swing? Print Page Previous Next Advertisements ”;
Example – Tree
Swing Examples – Trees ”; Previous Next Learn how to play with Trees in Swing UI programming. Here are most commonly used examples − How to create a tree in Swing? Print Page Previous Next Advertisements ”;
TestNG – Parallel Execution
TestNG – Parallel Execution ”; Previous Next TestNG allows to run tests parallelly or in separate threads in following ways: Parallel suites: If you are running several suite files (e.g. testng1.xml testng2.xml”), and you want each of these suites to be run in a separate thread. Use the following command line flag to specify the size of a thread pool: java org.testng.TestNG -suitethreadpoolsize 3 testng1.xml testng2.xml testng3.xml Parallel tests, classes and methods: Use parallel attribute on the <suite> tag respectively (for methods,test,classes, instances). <suite name=”My suite” parallel=”methods” thread-count=”5″> <suite name=”My suite” parallel=”tests” thread-count=”5″> <suite name=”My suite” parallel=”classes” thread-count=”5″> <suite name=”My suite” parallel=”instances” thread-count=”5″> Parallel testing is used heavily with Selenium because of the importance of cross-browser testing. With so many browsers in market today with a different version, create a browser matrix and run the tests parallelly. This will save us lot of time and other resources. Advantages and Disadvantages Following are some of the advantages of parallel testing using TestNG: It reduces time Allows multi-threaded tests Following are some of the disadvantages of parallel testing using TestNG Fails on dependent modules – Most of the times the tests are inter-dependent, hence failing chances are more. Program flow sequence – The tester should be well aware of the program flow to create parallel testing modules. Create Test Case Class Let us see an example to run test methods parallelly. Create a java class, say, TestParallel.java in /work/testng/src. import org.testng.annotations.Test; public class TestParallel { @Test public void method1() { System.out.println(“Inside method1()”); //Assert.assertEquals(message, messageUtil.printMessage()); } @Test public void method2() { System.out.println(“Inside method2()”); //Assert.assertEquals(message, messageUtil.printMessage()); } } The preceding test class contains two test methods which will run in separate threads. 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 = “Parallel Testing Suite”> <test name = “Parallel Tests” parallel = “methods”> <classes> <class name = “TestParallel” /> </classes> </test> </suite> Compile the TestParallel class using javac. /work/testng/src$ javac TestParallel.java Now, run testng.xml. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. Inside method1() Inside method2() =============================================== Parallel Testing Suite Total tests run: 2, Passes: 2, Failures: 0, Skips: 0 =============================================== Print Page Previous Next Advertisements ”;
TestNG – Group Test
TestNG – Group Test ”; Previous Next Group test is a new innovative feature in TestNG, which doesn’t exist in JUnit framework. It permits you to dispatch methods into proper portions and perform sophisticated groupings of test methods. Not only can you declare those methods that belong to groups, but you can also specify groups that contain other groups. Then, TestNG can be invoked and asked to include a certain set of groups (or regular expressions), while excluding another set. Group tests provide maximum flexibility in how you partition your tests, and doesn”t require you to recompile anything if you want to run two different sets of tests back to back. Groups are specified in your testng.xml file using the <groups> tag. It can be found either under the <test> or <suite> tag. Groups specified in the <suite> tag apply to all the <test> tags underneath. Now, let”s take an example to see how group test works. 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 “tutorialspoint” to the message public String salutationMessage() { message = “tutorialspoint” + message; System.out.println(message); return message; } // add “www.” to the message public String exitMessage() { message = “www.” + message; System.out.println(message); return message; } } Create Test Case Class Create a java test class, say, GroupTestExample.java in /work/testng/src. Add test methods, testPrintMessage() and testSalutationMessage(), to your test class. Group the test method in two categories − Check-in tests (checkintest) − These tests should be run before you submit new code. They should typically be fast and just make sure no basic functionality is broken. Functional tests (functest) − These tests should cover all the functionalities of your software and be run at least once a day, although ideally you would want to run them continuously. Following are the contents of GroupTestExample.java. import org.testng.Assert; import org.testng.annotations.Test; public class GroupTestExample { String message = “.com”; MessageUtil messageUtil = new MessageUtil(message); @Test(groups = { “functest”, “checkintest” }) public void testPrintMessage() { System.out.println(“Inside testPrintMessage()”); message = “.com”; Assert.assertEquals(message, messageUtil.printMessage()); } @Test(groups = { “checkintest” }) public void testSalutationMessage() { System.out.println(“Inside testSalutationMessage()”); message = “tutorialspoint” + “.com”; Assert.assertEquals(message, messageUtil.salutationMessage()); } @Test(groups = { “functest” }) public void testingExitMessage() { System.out.println(“Inside testExitMessage()”); message = “www.” + “tutorialspoint”+”.com”; Assert.assertEquals(message, messageUtil.exitMessage()); } } Create testng.xml Create testng.xml in /work/testng/src, to execute test case(s). Here, we would be executing only those tests, that belong to the group functest. <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” > <suite name = “Suite1”> <test name = “test1”> <groups> <run> <include name = “functest” /> </run> </groups> <classes> <class name = “GroupTestExample” /> </classes> </test> </suite> Compile the MessageUtil, Test case classes using javac. /work/testng/src$ javac MessageUtil.java GroupTestExample.java Now, run the testng.xml, which will run only the method testPrintMessage(), as it belongs to the group functest. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. Only the method testPrintMessage() is executed. Inside testPrintMessage() .com Inside testExitMessage() www..com =============================================== Suite1 Total tests run: 2, Failures: 1, Skips: 0 =============================================== Group of Groups Groups can also include other groups. These groups are called MetaGroups. For example, you might want to define a group all that includes checkintest and functest. Let”s modify our testng.xml file as follows − <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” > <suite name = “Suite1”> <test name = “test1”> <groups> <define name = “all”> <include name = “functest”/> <include name = “checkintest”/> </define> <run> <include name = “all”/> </run> </groups> <classes> <class name = “GroupTestExample” /> </classes> </test> </suite> Executing the above testng.xml will execute all the three tests and will give you the following result − Inside testPrintMessage() .com Inside testSalutationMessage() tutorialspoint.com Inside testExitMessage() www.tutorialspoint.com =============================================== Suite1 Total tests run: 3, Failures: 0, Skips: 0 =============================================== Exclusion Groups You can ignore a group by using the <exclude> tag as shown below − <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” > <suite name = “Suite1”> <test name = “test1”> <groups> <define name = “all”> <exclude name = “functest”/> <include name = “checkintest”/> </define> <run> <include name = “all”/> </run> </groups> <classes> <class name = “GroupTestExample” /> </classes> </test> </suite> Print Page Previous Next Advertisements ”;
Struts2 – Result Types
Struts 2 – Results & Result Types ”; Previous Next As mentioned previously, the <results> tag plays the role of a view in the Struts2 MVC framework. The action is responsible for executing the business logic. The next step after executing the business logic is to display the view using the <results> tag. Often there is some navigation rules attached with the results. For example, if the action method is to authenticate a user, there are three possible outcomes. Successful Login Unsuccessful Login – Incorrect username or password Account Locked In this scenario, the action method will be configured with three possible outcome strings and three different views to render the outcome. We have already seen this in the previous examples. But, Struts2 does not tie you up with using JSP as the view technology. Afterall the whole purpose of the MVC paradigm is to keep the layers separate and highly configurable. For example, for a Web2.0 client, you may want to return XML or JSON as the output. In this case, you could create a new result type for XML or JSON and achieve this. Struts comes with a number of predefined result types and whatever we”ve already seen that was the default result type dispatcher, which is used to dispatch to JSP pages. Struts allow you to use other markup languages for the view technology to present the results and popular choices include Velocity, Freemaker, XSLT and Tiles. The Dispatcher Result Type The dispatcher result type is the default type, and is used if no other result type is specified. It”s used to forward to a servlet, JSP, HTML page, and so on, on the server. It uses the RequestDispatcher.forward() method. We saw the “shorthand” version in our earlier examples, where we provided a JSP path as the body of the result tag. <result name = “success”> /HelloWorld.jsp </result> We can also specify the JSP file using a <param name = “location”> tag within the <result…> element as follows − <result name = “success” type = “dispatcher”> <param name = “location”> /HelloWorld.jsp </param > </result> We can also supply a parse parameter, which is true by default. The parse parameter determines whether or not the location parameter will be parsed for OGNL expressions. The FreeMaker Result Type In this example, we are going to see how we can use FreeMaker as the view technology. Freemaker is a popular templating engine that is used to generate output using predefined templates. Let us now create a Freemaker template file called hello.fm with the following contents − Hello World ${name} The above file is a template where name is a parameter which will be passed from outside using the defined action. You will keep this file in your CLASSPATH. Next, let us modify the struts.xml to specify the result as follows − <?xml version = “1.0” Encoding = “UTF-8”?> <!DOCTYPE struts PUBLIC “-//Apache Software Foundation//DTD Struts Configuration 2.0//EN” “http://struts.apache.org/dtds/struts-2.0.dtd”> <struts> <constant name = “struts.devMode” value = “true” /> <package name = “helloworld” extends = “struts-default”> <action name = “hello” class = “com.tutorialspoint.struts2.HelloWorldAction” method = “execute”> <result name = “success” type = “freemarker”> <param name = “location”>/hello.fm</param> </result> </action> </package> </struts> Let us keep our HelloWorldAction.java, HelloWorldAction.jsp and index.jsp files as we have created them in examples chapter. Now Right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat”s webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen . Enter a value “Struts2” and submit the page. You should see the next page. As you can see, this is exactly same as the JSP view except that we are not tied to using JSP as the view technology. We have used Freemaker in this example. The Redirect Result Type The redirect result type calls the standard response.sendRedirect() method, causing the browser to create a new request to the given location. We can provide the location either in the body of the <result…> element or as a <param name = “location”> element. Redirect also supports the parse parameter. Here”s an example configured using XML − <action name = “hello” class = “com.tutorialspoint.struts2.HelloWorldAction” method = “execute”> <result name = “success” type = “redirect”> <param name = “location”> /NewWorld.jsp </param > </result> </action> So just modify your struts.xml file to define redirect type as mentioned above and create a new file NewWorld.jpg where you will be redirected whenever hello action will return success. You can check Struts 2 Redirect Action example for better understanding. Print Page Previous Next Advertisements ”;