TestNG – Executing Tests

TestNG – Executing Tests ”; Previous Next The test cases are executed using TestNG class. This class is the main entry point for running tests in the TestNG framework. Users can create their own TestNG object and invoke it in many different ways such as − On an existing testng.xml. On a synthetic testng.xml, created entirely from Java. By directly setting the test classes. You can also define which groups to include or exclude, assign parameters, etc. The command line parameters are − -d outputdir: specify the output directory. -testclass class_name: specifies one or several class names. -testjar jar_name: specifies the jar containing the tests. -sourcedir src1;src2: ; separated list of source directories (used only when javadoc annotations are used). -target -groups -testrunfactory -listener We will create the TestNG object an existing testng.xml in our example below. 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; } } Create Test Case Class Create a java test class, say, SampleTest.java. Add a test method testPrintMessage() to your test class. Add an Annotation @Test to method testPrintMessage(). Implement the test condition and check the condition using assertEquals API of TestNG. Create a java class file called SampleTest.java in /work/testng/src. import org.testng.Assert; import org.testng.annotations.Test; public class SampleTest { String message = “Hello World”; MessageUtil messageUtil = new MessageUtil(message); @Test public void testPrintMessage() { Assert.assertEquals(message, messageUtil.printMessage()); } } Create testng.xml Next, let”s create testng.xml file in /work/testng/src, to execute test case(s). This file captures your entire testing in XML. This file makes it easy to describe all your test suites and their parameters in one file, which you can check in your code repository or e-mail to coworkers. It also makes it easy to extract subsets of your tests or split several runtime configurations (e.g., testngdatabase.xml would run only tests that exercise your database). <?xml version = “1.0” encoding = “UTF-8”?> <suite name = “Sample test Suite”> <test name = “Sample test”> <classes> <class name = “SampleTest” /> </classes> </test> </suite> Compile the test case using javac. /work/testng/src$ javac MessageUtil.java SampleTest.java Now, run the testng.xml, which will run the test case defined in <test> tag. /work/testng/src$ java org.testng.TestNG testng.xml Verify the output. Hello World =============================================== Sample test Suite Total tests run: 1, Failures: 0, Skips: 0 =============================================== Print Page Previous Next Advertisements ”;

Spring MVC – Generate JSON

Spring MVC – Generate JSON Example ”; Previous Next The following example shows how to generate JSON using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework − Step Description 1 Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create a Java classes User, UserController under the com.tutorialspoint package. 3 Download Jackson libraries Jackson Core, Jackson Databind and Jackson Annotations from maven repository page. Put them in your CLASSPATH. 4 The final step is to create the content of all the source and configuration files and export the application as explained below. User.java package com.tutorialspoint; public class User { private String name; private int id; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } } UserController.java package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping(“/user”) public class UserController { @RequestMapping(value=”{name}”, method = RequestMethod.GET) public @ResponseBody User getUser(@PathVariable String name) { User user = new User(); user.setName(name); user.setId(1); return user; } } TestWeb-servlet.xml <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” xmlns:mvc = http://www.springframework.org/schema/mvc” 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd”> <context:component-scan base-package = com.tutorialspoint” /> <mvc:annotation-driven /> </beans> Here, we have created a Simple POJO User and in UserController we have returned the User. Spring automatically handles the JSON conversion based on RequestMapping and Jackson jar present in the classpath. Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your TestWeb.war file in Tomcat”s webapps folder. Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL – http://localhost:8080/TestWeb/mahesh and we will see the following screen. Print Page Previous Next Advertisements ”;

Spring MVC – Generate PDF

Spring MVC – Generate PDF Example ”; Previous Next The following example shows how to generate a PDF using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and adhere to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework. Step Description 1 Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create Java classes UserPDFView and PDFController under the com.tutorialspoint package. 3 Download the iText library − iText from the maven repository page. Put it in your CLASSPATH. 4 The final step is to create the content of the source and configuration files and export the application as explained below. PDFController.java package com.tutorialspoint; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class PDFController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { //user data Map<String,String> userData = new HashMap<String,String>(); userData.put(“1”, “Mahesh”); userData.put(“2”, “Suresh”); userData.put(“3”, “Ramesh”); userData.put(“4”, “Naresh”); return new ModelAndView(“UserSummary”,”userData”,userData); } } UserExcelView.java package com.tutorialspoint; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.view.document.AbstractPdfView; import com.lowagie.text.Document; import com.lowagie.text.Table; import com.lowagie.text.pdf.PdfWriter; public class UserPDFView extends AbstractPdfView { protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter pdfWriter, HttpServletRequest request, HttpServletResponse response) throws Exception { Map<String,String> userData = (Map<String,String>) model.get(“userData”); Table table = new Table(2); table.addCell(“Roll No”); table.addCell(“Name”); for (Map.Entry<String, String> entry : userData.entrySet()) { table.addCell(entry.getKey()); table.addCell(entry.getValue()); } document.add(table); } } TestWeb-servlet.xml <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” xmlns:mvc = “http://www.springframework.org/schema/mvc” 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd”> <bean class = “org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping” /> <bean class = “com.tutorialspoint.PDFController” /> <bean class = “org.springframework.web.servlet.view.XmlViewResolver”> <property name = “location”> <value>/WEB-INF/views.xml</value> </property> </bean> </beans> views.xml <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”> <bean id = “UserSummary” class = “com.tutorialspoint.UserPDFView”></bean> </beans> Here, we have created a PDFController and UserPDFView. iText library deals with the PDF file formats and will convert the data to a PDF document. Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the TestWeb.war file in Tomcat”s webapps folder. Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. We can also try the following URL − http://localhost:8080/TestWeb/pdf and if all goes as planned, we will see the following screen. Print Page Previous Next Advertisements ”;

Resource Bundle View Resolver

Spring MVC – Resource Bundle View Resolver Example ”; Previous Next The ResourceBundleViewResolver is used to resolve the view names using view beans defined in the properties file. The following example shows how to use the ResourceBundleViewResolver using the Spring Web MVC Framework. TestWeb-servlet.xml <bean class = “org.springframework.web.servlet.view.ResourceBundleViewResolver”> <property name = “basename” value = “views” /> </bean> Here, the basename refers to name of the resource bundle, which carries the views. The default name of the resource bundle is views.properties, which can be overridden using the basename property. views.properties hello.(class) = org.springframework.web.servlet.view.JstlView hello.url = /WEB-INF/jsp/hello.jsp For example, using the above configuration, if URI − /hello is requested, DispatcherServlet will forward the request to the hello.jsp defined by bean hello in the views.properties. Here, “hello” is the view name to be matched. Whereas, class refers to the view type and URL is the view”s location. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using Spring Web Framework. Step Description 1 Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create a Java class HelloController under the com.tutorialspointpackage. 3 Create a view file hello.jsp under the jsp sub-folder. 4 Create a properties file views.properties under the src folder. 5 Download JSTL library jstl.jar. Put it in your CLASSPATH. 6 The final step is to create the content of the source and configuration files and export the application as explained below. HelloController.java package com.tutorialspoint; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.ui.ModelMap; @Controller @RequestMapping(“/hello”) public class HelloController{ @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { model.addAttribute(“message”, “Hello Spring MVC Framework!”); return “hello”; } } TestWeb-servlet.xml <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.ResourceBundleViewResolver”> <property name = “basename” value = “views” /> </bean> </beans> views.properties hello.(class) = org.springframework.web.servlet.view.JstlView hello.url = /WEB-INF/jsp/hello.jsp hello.jsp <%@ page contentType=”text/html; charset=UTF-8″ %> <html> <head> <title>Hello World</title> </head> <body> <h2>${message}</h2> </body> </html> Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat”s webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try to access the URL − http://localhost:8080/HelloWeb/hello and if everything is fine with the Spring Web Application, we will see the following screen. Print Page Previous Next Advertisements ”;

Spring DI – Useful Resources

Spring DI – Useful Resources ”; Previous Next The following resources contain additional information on Spring DI. Please use them to get more in-depth knowledge on this topic. Useful Links on Spring DI Spring Source − Find latest news about Spring Framework, download section and all about Spring. Oracle”s Site on JDBC − Sun Developer Network giving link on JDBC material. MySQL Connector/J − MySQL Connector/J is the official JDBC driver for MySQL. The JavaTM Tutorials − The Java Tutorials are practical guides for programmers who want to use the Java programming language to create applications. JavaTM 2 SDK, Standard Edition − Official site for JavaTM 2 SDK, Standard Edition Free Java Download − Download Java for your desktop computer now! Java Technology Reference − Sun Microsystem”s official website listing down all the API documentation, latest Java Technologies, Books and other resource. To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

Spring MVC – Using log4j

Spring MVC – Integrate LOG4J Example ”; Previous Next The following example shows how to integrate LOG4J using the Spring Web MVC Framework. To start with, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework. Step Description 1 Create a project with the name TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create a Java class HelloController under the com.tutorialspointpackage. 3 Download the log4j library LOG4J from the maven repository page. Put it in your CLASSPATH. 4 Create a log4j.properties under the SRC folder. 5 The final step is to create the content of the source and configuration files and export the application as explained below. HelloController.java package com.tutorialspoint; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.ui.ModelMap; @Controller @RequestMapping(“/hello”) public class HelloController{ private static final Logger LOGGER = Logger.getLogger(HelloController.class); @RequestMapping(method = RequestMethod.GET) public String printHello(ModelMap model) { LOGGER.info(“printHello started.”); //logs debug message if(LOGGER.isDebugEnabled()){ LOGGER.debug(“Inside: printHello”); } //logs exception LOGGER.error(“Logging a sample exception”, new Exception(“Testing”)); model.addAttribute(“message”, “Hello Spring MVC Framework!”); LOGGER.info(“printHello ended.”); return “hello”; } } log4j.properties # Root logger option log4j.rootLogger = DEBUG, stdout, file # Redirect log messages to console log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L – %m%n # Redirect log messages to a log file log4j.appender.file = org.apache.log4j.RollingFileAppender #outputs to Tomcat home log4j.appender.file.File = ${catalina.home}/logs/myapp.log log4j.appender.file.MaxFileSize = 5MB log4j.appender.file.MaxBackupIndex = 10 log4j.appender.file.layout = org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L – %m%n TestWeb-servlet.xml <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” xmlns:mvc = “http://www.springframework.org/schema/mvc” 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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> hello.jsp <%@ page contentType = “text/html; charset = UTF-8″ %> <html> <head> <title>Hello World</title> </head> <body> <h2>${message}</h2> </body> </html> Here, we have configured the LOG4J to log details on the Tomcat console and in the file present in &t; tomcat home → logs as myapp.log. Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your TestWeb.war file in Tomcat”s webapps folder. Now, start the Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL −http://localhost:8080/TestWeb/hello and we will see the following screen on Tomcat”s log. Print Page Previous Next Advertisements ”;

Struts2 – Type Conversion

Struts 2 – Type Conversion ”; Previous Next Everything on a HTTP request is treated as a String by the protocol. This includes numbers, booleans, integers, dates, decimals and everything else. However, in the Struts class, you could have properties of any data types. How does Struts autowire the properties for you? Struts uses a variety of type converters under the covers to do the heavy lifting. For example, if you have an integer attribute in your Action class, Struts automatically converts the request parameter to the integer attribute without you doing anything. By default, Struts comes with a number of type converters If you are using any of the below listed converters, then you have nothing to worry about − Integer, Float, Double, Decimal Date and Datetime Arrays and Collections Enumerations Boolean BigDecimal At times when you are using your own data type, it is necessary to add your own converters to make Struts aware how to convert those values before displaying. Consider the following POJO class Environment.java. package com.tutorialspoint.struts2; public class Environment { private String name; public Environment(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } This is a very simple class that has an attribute called name, so nothing special about this class. Let us create another class that contains information about the system –SystemDetails.java. For the purpose of this exercise, I have hardcoded the Environment to “Development” and the Operating System to “Windows XP SP3”. In a real-time project, you would get this information from the system configuration. Let us have the following action class − package com.tutorialspoint.struts2; import com.opensymphony.xwork2.ActionSupport; public class SystemDetails extends ActionSupport { private Environment environment = new Environment(“Development”); private String operatingSystem = “Windows XP SP3”; public String execute() { return SUCCESS; } public Environment getEnvironment() { return environment; } public void setEnvironment(Environment environment) { this.environment = environment; } public String getOperatingSystem() { return operatingSystem; } public void setOperatingSystem(String operatingSystem) { this.operatingSystem = operatingSystem; } } Next, let us create a simple JSP file System.jsp to display the Environment and the Operating System information. <%@ 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>System Details</title> </head> <body> Environment: <s:property value = “environment”/><br/> Operating System:<s:property value = “operatingSystem”/> </body> </html> Let us wire the system.jsp and the SystemDetails.java class together using struts.xml. The SystemDetails class has a simple execute () method that returns the string “SUCCESS“. <?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 = “system” class = “com.tutorialspoint.struts2.SystemDetails” method = “execute”> <result name = “success”>/System.jsp</result> </action> </package> </struts> 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/system.action. This will produce the following screen − What is wrong with the above output? Struts knows how to display and convert the string “Windows XP SP3” and other built-in data types, but it does not know what to do with the property of Environment type. It is simply called toString() method on the class To resolve this problem, let us now create and register a simple TypeConverter for the Environment class. Create a class called EnvironmentConverter.java with the following. package com.tutorialspoint.struts2; import java.util.Map; import org.apache.struts2.util.StrutsTypeConverter; public class EnvironmentConverter extends StrutsTypeConverter { @Override public Object convertFromString(Map context, String[] values, Class clazz) { Environment env = new Environment(values[0]); return env; } @Override public String convertToString(Map context, Object value) { Environment env = (Environment) value; return env == null ? null : env.getName(); } } The EnvironmentConverter extends the StrutsTypeConverter class and tells Struts how to convert Environment to a String and vice versa by overriding two methods which are convertFromString() and convertToString(). Let us now register this converter before we use it in our application. There are two ways to register a converter. If the converter will be used only in a particular action, then you would have to create a property file which needs to be named as ”[action-class]”converstion.properties. In our case, we create a file called SystemDetails-converstion.properties with the following registration entry − environment = com.tutorialspoint.struts2.EnvironmentConverter In the above example, “environment” is the name of the property in the SystemDetails.java class and we are telling Struts to use the EnvironmentConverter for converting to and from this property. However, we are not going to do this, Instead we are going to register this converter globally, so that it can be used throughout the application. To do this, create a property file called xwork-conversion.properties in the WEBINF/classes folder with the following line com.tutorialspoint.struts2.Environment = com.tutorialspoint.struts2.EnvironmentConverter This simply registers the converter globally, so that Struts can automatically do the conversion every time when it encounters an object of the type Environment. Now, if you re-compiling and re-running the program, then you will get a better output as follows − Obviously, now the result will be better which means our Struts convertor is working fine. This is how you can create multiple convertors and register them to use as per your requirements. Print Page Previous Next Advertisements ”;

Struts2 – Control Tags

Struts 2 – Control Tags ”; Previous Next The Struts 2 tags has a set of tags that makes it easy to control the flow of page execution. Following is the list of important Struts 2 Control Tags − The If and Else Tags These tags perform basic condition flow found in every language. ”If” tag is used by itself or with ”Else If” Tag and/or single/multiple ”Else” Tag as shown below − <s:if test = “%{false}”> <div>Will Not Be Executed</div> </s:if> <s:elseif test = “%{true}”> <div>Will Be Executed</div> </s:elseif> <s:else> <div>Will Not Be Executed</div> </s:else> Check Detailed Example The Iterator Tags This iterator will iterate over a value. An iterable value can be either itherjava.util.Collection or java.util.Iterator file. While iterating over an iterator, you can use Sort tag to sort the result or SubSet tag to get a sub set of the list or array. The following example retrieves the value of the getDays() method of the current object on the value stack and uses it to iterate over. The <s:property/> tag prints out the current value of the iterator. <s:iterator value = “days”> <p>day is: <s:property/></p> </s:iterator> Check Detailed Example The Merge Tag These merge tag takes two or more lists as parameters and merge them all together as shown below − <s:merge var = “myMergedIterator”> <s:param value = “%{myList1}” /> <s:param value = “%{myList2}” /> <s:param value = “%{myList3}” /> </s:merge> <s:iterator value = “%{#myMergedIterator}”> <s:property /> </s:iterator> Check Detailed Example The Append Tag These append tag take two or more lists as parameters and append them all together as shown below − <s:append var = “myAppendIterator”> <s:param value = “%{myList1}” /> <s:param value = “%{myList2}” /> <s:param value = “%{myList3}” /> </s:append> <s:iterator value = “%{#myAppendIterator}”> <s:property /> </s:iterator> Check Detailed Example The Generator Tag These generator tag generates an iterator based on the val attribute supplied. The following generator tag generates an iterator and prints it out using the iterator tag. <s:generator val = “%{”aaa,bbb,ccc,ddd,eee”}”> <s:iterator> <s:property /><br/> </s:iterator> </s:generator> Check Detailed Example Print Page Previous Next Advertisements ”;

Struts2 – Interceptors

Struts 2 – Interceptors ”; Previous Next Interceptors are conceptually the same as servlet filters or the JDKs Proxy class. Interceptors allow for crosscutting functionality to be implemented separately from the action as well as the framework. You can achieve the following using interceptors − Providing preprocessing logic before the action is called. Providing postprocessing logic after the action is called. Catching exceptions so that alternate processing can be performed. Many of the features provided in the Struts2 framework are implemented using interceptors; Examples include exception handling, file uploading, lifecycle callbacks, etc. In fact, as Struts2 emphasizes much of its functionality on interceptors, it is not likely to have 7 or 8 interceptors assigned per action. Struts2 Framework Interceptors Struts 2 framework provides a good list of out-of-the-box interceptors that come preconfigured and ready to use. Few of the important interceptors are listed below − Sr.No Interceptor & Description 1 alias Allows parameters to have different name aliases across requests. 2 checkbox Assists in managing check boxes by adding a parameter value of false for check boxes that are not checked. 3 conversionError Places error information from converting strings to parameter types into the action”s field errors. 4 createSession Automatically creates an HTTP session if one does not already exist. 5 debugging Provides several different debugging screens to the developer. 6 execAndWait Sends the user to an intermediary waiting page while the action executes in the background. 7 exception Maps exceptions that are thrown from an action to a result, allowing automatic exception handling via redirection. 8 fileUpload Facilitates easy file uploading. 9 i18n Keeps track of the selected locale during a user”s session. 10 logger Provides simple logging by outputting the name of the action being executed. 11 params Sets the request parameters on the action. 12 prepare This is typically used to do pre-processing work, such as setup database connections. 13 profile Allows simple profiling information to be logged for actions. 14 scope Stores and retrieves the action”s state in the session or application scope. 15 ServletConfig Provides the action with access to various servlet-based information. 16 timer Provides simple profiling information in the form of how long the action takes to execute. 17 token Checks the action for a valid token to prevent duplicate formsubmission. 18 validation Provides validation support for actions Please look into Struts 2 documentation for complete detail on the abovementioned interceptors. But I will show you how to use an interceptor in general in your Struts application. How to Use Interceptors? Let us see how to use an already existing interceptor to our “Hello World” program. We will use the timer interceptor whose purpose is to measure how long it took to execute an action method. At the same time, I”m using params interceptor whose purpose is to send the request parameters to the action. You can try your example without using this interceptor and you will find that name property is not being set because parameter is not able to reach to the action. We will keep HelloWorldAction.java, web.xml, HelloWorld.jsp and index.jsp files as they have been created in Examples chapter but let us modify the struts.xml file to add an interceptor 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”> <interceptor-ref name = “params”/> <interceptor-ref name = “timer” /> <result name = “success”>/HelloWorld.jsp</result> </action> </package> </struts> 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 enter any word in the given text box and click Say Hello button to execute the defined action. Now if you will check the log generated, you will find the following text − INFO: Server startup in 3539 ms 27/08/2011 8:40:53 PM com.opensymphony.xwork2.util.logging.commons.CommonsLogger info INFO: Executed action [//hello!execute] took 109 ms. Here bottom line is being generated because of timer interceptor which is telling that action took total 109ms to be executed. Create Custom Interceptors Using custom interceptors in your application is an elegant way to provide crosscutting application features. Creating a custom interceptor is easy; the interface that needs to be extended is the following Interceptor interface − public interface Interceptor extends Serializable { void destroy(); void init(); String intercept(ActionInvocation invocation) throws Exception; } As the names suggest, the init() method provides a way to initialize the interceptor, and the destroy() method provides a facility for interceptor cleanup. Unlike actions, interceptors are reused across requests and need to be threadsafe, especially the intercept() method. The ActionInvocation object provides access to the runtime environment. It allows access to the action itself and methods to invoke the action and determine whether the action has already been invoked. If you have no need for initialization or cleanup code, the AbstractInterceptor class can be extended. This provides a default nooperation implementation of the init() and destroy() methods. Create Interceptor Class Let us create the following MyInterceptor.java in Java Resources > src folder − package com.tutorialspoint.struts2; import java.util.*; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class MyInterceptor extends AbstractInterceptor { public String intercept(ActionInvocation invocation)throws Exception { /* let us do some pre-processing */ String output = “Pre-Processing”; System.out.println(output); /* let us call action or next interceptor */ String result = invocation.invoke(); /* let us do some post-processing */ output = “Post-Processing”; System.out.println(output); return result; } } As you notice, actual action will be executed using the interceptor by invocation.invoke()call. So you can do some pre-processing and some postprocessing based on your requirement. The framework itself starts the process by making the first call to the ActionInvocation object”s invoke(). Each time invoke() is called, ActionInvocation consults its state and executes whichever interceptor comes next. When all of

Spring Security – Logout

Spring Security – Logout ”; Previous Next Logout is an important function, so that a user is required to login to access any secured resource once user has logged out or signed out or its current session is invalidated for any reason. Spring security provides a default logout functionality as we”ve seen in Spring Security – Form Login chapter. A logout functionality performs following important functions. Invalidates the Http session, and unbinds objects bound to the session. It clears the remember-me cookie. Removes the authentication from Spring’s Security context. A logout can be explicitly configured as given below − protected void configure(HttpSecurity http) throws Exception { http // … .logout(config -> config .logoutUrl(“/logout”) .logoutSuccessUrl(“/login”)) .build(); } Important Methods Following are important methods that we can configure in logout() method. logoutUrl (“/logout”) − This will be used to logout from our application. It has default value as logout and can be changed to any other custom value. logoutSuccessUrl (“/login”) − This will be used to load login page once user is successfully logged out. invalidateHttpSession (“true”) − This is used to invalidate the session. By default, it is true so that when user it logged out, its session is invalidated. We can mark it false to keep the session alive even after logout. deleteCookies (“JSESSIONID”) − This is used to clear remember-me cookie. logoutSuccessHandler(logoutSuccessHandler()); − This method is used when we need to perform some action at the time user logs out from the application. Let us start actual programming with Spring Security. 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 Tool Suite IDE. Now let us proceed to write a Spring MVC based Application managed by Maven, which will ask user to login, authenticate user and then provide option to logout using Spring Security Form Login Feature. Create Project using Spring Initializr Spring Initializr is great way to start with Spring Boot project. It provides a easy to use User Interface to create a project, add dependencies, select java runtime etc. It generates a skeleton project structure which once downloaded can be imported in spring tool suite and we can proceed with our readymade project structure. We”re choosing a maven project, naming the project as formlogin, with java version as 21. Following dependencies are added: Spring Web Spring Security Thymeleaf Spring Boot DevTools Thymeleaf is a templating engine for Java. It allows us to quickly develop static or dynamic web pages for rendering in the browser. It is extremely extensible and allows us to define and customize the processing of our templates in fine detail. In addition to this, we can learn more about Thymeleaf by clicking this link. Let”s move on to generate our project and download it. We then extract it to a folder of our choice and use any IDE to open it. I shall be using Spring Tools Suite 4. It is available for free downloading from the https://spring.io/tools website and is optimized for spring applications. pom.xml with all relevant dependencies Let”s take a look at our pom.xml file. It should look something similar to this − pom.xml <?xml version=”1.0″ encoding=”UTF-8″?> <project xmlns=”http://maven.apache.org/POM/4.0.0″ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.3.1</version> <relativePath/> <!– lookup parent from repository –> </parent> <groupId>com.tutorialspoint.security</groupId> <artifactId>formlogin</artifactId> <version>0.0.1-SNAPSHOT</version> <name>formlogin</name> <description>Demo project for Spring Boot</description> <url/> <licenses> <license/> </licenses> <developers> <developer/> </developers> <scm> <connection/> <developerConnection/> <tag/> <url/> </scm> <properties> <java.version>21</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity6</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-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> Spring Security Configuration Class Inside of our config package, we have created the WebSecurityConfig class. We shall be using this class for our security configurations, so let”s annotate it with an @Configuration annotation and @EnableWebSecurity. As a result, Spring Security knows to treat this class a configuration class. As we can see, configuring applications have been made very easy by Spring. WebSecurityConfig package com.tutorialspoint.security.formlogin.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class WebSecurityConfig { @Bean protected UserDetailsService userDetailsService() { UserDetails user = User.builder() .username(“user”) .password(passwordEncoder().encode(“user123”)) .roles(“USER”) .build(); UserDetails admin = User.builder() .username(“admin”) .password(passwordEncoder().encode(“admin123”)) .roles(“USER”, “ADMIN”) .build(); return new InMemoryUserDetailsManager(user, admin); } @Bean protected PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests( request -> request.requestMatchers(“/login”).permitAll() .requestMatchers(“/**”).authenticated() ) .formLogin(form -> form.loginPage(“/login”) .defaultSuccessUrl(“/”) .failureUrl(“/login?error=true”) .permitAll()) .logout(config -> config .logoutUrl(“/logout”) .logoutSuccessUrl(“/login”) .invalidateHttpSession(true) .deleteCookies(“JSESSIONID”)) .build(); } } Here we”ve mentioned the logout url to be used logout which is a default url provided by spring security. We are not required to create a special logout page for it. Similarly once user is logged out, user will be shown the login page which is standard practice. Controller Class In this class, we”ve created a mapping for “/” endpoint and for “/login” for the index page and login page of this application. AuthController.java package com.tutorialspoint.security.formlogin.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class AuthController { @GetMapping(“/”) public String home() { return “index”; } @GetMapping(“/login”) public String login() { return “login”; } } Views Let”s create index.html in /src/main/resources/templates folder with following content to act as a home page and to display logged in user name. index.html <!DOCTYPE html> <html xmlns=”http://www.w3.org/1999/xhtml” xmlns:th=”https://www.thymeleaf.org” xmlns:sec=”https://www.thymeleaf.org/thymeleaf-extras-springsecurity3″> <head> <title> Hello World! </title> </head> <body> <h1 th:inline=”text”>Hello <span sec:authentication=”name”></span>!</h1> <form th:action=”@{/logout}” method=”post”> <input type=”submit” value=”Sign Out”/> </form> </body> <html> Here we”ve used a form with a submit button to logout the user. <form th:action=”@{/logout}” method=”post”> <input type=”submit” value=”Sign Out”/> </form> We can use a link as well as well as shown below: <a href=”/logout” alt=”logout”>Sign Out</a> login.html Let”s create the