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 ”;

Example – Progress Bars

Swing Examples – Progress Bars ”; Previous Next Learn how to play with Progress Bars in Swing UI programming. Here are most commonly used examples − How to show a standard progress bar in Swing? How to show a indeterministic progress bar in Swing? How to use ProgressMonitor in Swing? Print Page Previous Next Advertisements ”;

Spring MVC – Xml View Resolver

Spring MVC – Xml View Resolver Example ”; Previous Next The XmlViewResolver is used to resolve the view names using view beans defined in xml file. The following example shows how to use the XmlViewResolver using Spring Web MVC framework. TestWeb-servlet.xml <bean class = “org.springframework.web.servlet.view.XmlViewResolver”> <property name = “location”> <value>/WEB-INF/views.xml</value> </property> </bean> views.xml <bean id = “hello” class = “org.springframework.web.servlet.view.JstlView”> <property name = “url” value = “/WEB-INF/jsp/hello.jsp” /> </bean> 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 view.xml. 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 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 Download JSTL library jstl.jar. Put it in your CLASSPATH. 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.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.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 = “hello” class = “org.springframework.web.servlet.view.JstlView”> <property name = “url” value = “/WEB-INF/jsp/hello.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> 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 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 SpEL – Annotation Configuration

Spring SpEL – Annotation Based Configuration ”; Previous Next SpEL expression can be used in Annotation based beans configuration Syntax Following is an example of using an expression in annotation based configuration. @Value(“#{ T(java.lang.Math).random() * 100.0 }”) private int id; Here we are using @Value annotation and we”ve specified a SpEL expression on a property. Similarly we can specify SpEL expression on setter methods, on constructors and during autowiring as well. @Value(“#{ systemProperties[”user.country”] }”) public void setCountry(String country) { this.country = country; } Following example shows the various use cases. Example Let”s update the project created in Spring SpEL – Create Project chapter. We”re adding/updating following files − Employee.java − An employee class. AppConfig.java − A configuration class. MainApp.java − Main application to run and test. Here is the content of Employee.java file − package com.tutorialspoint; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class Employee { @Value(“#{ T(java.lang.Math).random() * 100.0 }”) private int id; private String name; private String country; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } @Value(“Mahesh”) public void setName(String name) { this.name = name; } public String getCountry() { return country; } @Value(“#{ systemProperties[”user.country”] }”) public void setCountry(String country) { this.country = country; } @Override public String toString() { return “[” + id + “, ” + name + “, ” + country + “]”; } } Here is the content of AppConfig.java file − package com.tutorialspoint; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan(basePackages = “com.tutorialspoint”) public class AppConfig { } Here is the content of MainApp.java file − package com.tutorialspoint; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class MainApp { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(AppConfig.class); context.refresh(); Employee emp = context.getBean(Employee.class); System.out.println(emp); } } Output [84, Mahesh, IN] Print Page Previous Next Advertisements ”;

Spring MVC – Errors

Spring MVC – Error Handling Example ”; Previous Next The following example shows how to use Error Handling and Validators in forms 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 HelloWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create Java classes Student, StudentController and StudentValidator under the com.tutorialspoint package. 3 Create view files addStudent.jsp, result.jsp under the jsp sub-folder. 4 The final step is to create the content of the source and configuration files and export the application as explained below. Student.java package com.tutorialspoint; public class Student { private Integer age; private String name; private Integer id; public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } } StudentValidator.java package com.tutorialspoint; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; public class StudentValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Student.class.isAssignableFrom(clazz); } @Override public void validate(Object target, Errors errors) { ValidationUtils.rejectIfEmptyOrWhitespace(errors, “name”, “required.name”,”Field name is required.”); } } StudentController.java package com.tutorialspoint; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.Validator; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class StudentController { @Autowired @Qualifier(“studentValidator”) private Validator validator; @InitBinder private void initBinder(WebDataBinder binder) { binder.setValidator(validator); } @RequestMapping(value = “/addStudent”, method = RequestMethod.GET) public ModelAndView student() { return new ModelAndView(“addStudent”, “command”, new Student()); } @ModelAttribute(“student”) public Student createStudentModel() { return new Student(); } @RequestMapping(value = “/addStudent”, method = RequestMethod.POST) public String addStudent(@ModelAttribute(“student”) @Validated Student student, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { return “addStudent”; } model.addAttribute(“name”, student.getName()); model.addAttribute(“age”, student.getAge()); model.addAttribute(“id”, student.getId()); return “result”; } } HelloWeb-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.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> <bean id = “studentValidator” class = “com.tutorialspoint.StudentValidator” /> </beans> Here, for the first service method student(), we have passed a blank Studentobject in the ModelAndView object with name “command”, because the spring framework expects an object with name “command”, if you are using <form:form> tags in your JSP file. So, when student() method is called, it returns addStudent.jsp view. The second service method addStudent() will be called against a POST method on the HelloWeb/addStudent URL. You will prepare your model object based on the submitted information. Finally, a “result” view will be returned from the service method, which will result in rendering the result.jsp. In case there are errors generated using validator then same view “addStudent” is returned, Spring automatically injects error messages from BindingResult in view. addStudent.jsp <%@taglib uri = “http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring MVC Form Handling</title> </head> <style> .error { color: #ff0000; } .errorblock { color: #000; background-color: #ffEEEE; border: 3px solid #ff0000; padding: 8px; margin: 16px; } </style> <body> <h2>Student Information</h2> <form:form method = “POST” action = “/HelloWeb/addStudent” commandName = “student”> <form:errors path = “*” cssClass = “errorblock” element = “div” /> <table> <tr> <td><form:label path = “name”>Name</form:label></td> <td><form:input path = “name” /></td> <td><form:errors path = “name” cssClass = “error” /></td> </tr> <tr> <td><form:label path = “age”>Age</form:label></td> <td><form:input path = “age” /></td> </tr> <tr> <td><form:label path = “id”>id</form:label></td> <td><form:input path = “id” /></td> </tr> <tr> <td colspan = “2”> <input type = “submit” value = “Submit”/> </td> </tr> </table> </form:form> </body> </html> Here we are using <form:errors /> tag with path=”*” to render error messages. For example <form:errors path = “*” cssClass = “errorblock” element = “div” /> It will render the error messages for all input validations. We are using <form:errors /> tag with path=”name” to render error message for name field. For example <form:errors path = “name” cssClass = “error” /> It will render error messages for the name field validations. result.jsp <%@taglib uri = “http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring MVC Form Handling</title> </head> <body> <h2>Submitted Student Information</h2> <table> <tr> <td>Name</td> <td>${name}</td> </tr> <tr> <td>Age</td> <td>${age}</td> </tr> <tr> <td>ID</td> <td>${id}</td> </tr> </table> </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 the HelloWeb.war file in Tomcat”s webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL − http://localhost:8080/HelloWeb/addStudent and we will see the following screen, if everything is fine with the Spring Web Application. After submitting the required information, click on the submit button to submit the form. You should see the following screen, if everything is fine with the Spring Web Application. Print Page Previous Next Advertisements ”;

Spring MVC – Radiobuttons

Spring MVC – RadioButtons Example ”; Previous Next The following example explains how to use RadioButtons in forms using the Spring Web MVC framework. To begin with, let us have a working Eclipse IDE in place and follow the subsequent steps to develop a Dynamic Form based Web Application using the Spring Web Framework. Step Description 1 Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create Java classes User, UserController under the com.tutorialspointpackage. 3 Create view files user.jsp, users.jsp under the jsp sub-folder. 4 The final step is to create the content of the source and configuration files and export the application as explained below. User.java package com.tutorialspoint; public class User { private String username; private String password; private String address; private boolean receivePaper; private String [] favoriteFrameworks; private String gender; private String favoriteNumber; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public boolean isReceivePaper() { return receivePaper; } public void setReceivePaper(boolean receivePaper) { this.receivePaper = receivePaper; } public String[] getFavoriteFrameworks() { return favoriteFrameworks; } public void setFavoriteFrameworks(String[] favoriteFrameworks) { this.favoriteFrameworks = favoriteFrameworks; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getFavoriteNumber() { return favoriteNumber; } public void setFavoriteNumber(String favoriteNumber) { this.favoriteNumber = favoriteNumber; } } UserController.java package com.tutorialspoint; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.ui.ModelMap; @Controller public class UserController { @RequestMapping(value = “/user”, method = RequestMethod.GET) public ModelAndView user() { User user = new User(); user.setFavoriteFrameworks((new String []{“Spring MVC”,”Struts 2″})); user.setGender(“M”); ModelAndView modelAndView = new ModelAndView(“user”, “command”, user); return modelAndView; } @RequestMapping(value = “/addUser”, method = RequestMethod.POST) public String addUser(@ModelAttribute(“SpringWeb”)User user, ModelMap model) { model.addAttribute(“username”, user.getUsername()); model.addAttribute(“password”, user.getPassword()); model.addAttribute(“address”, user.getAddress()); model.addAttribute(“receivePaper”, user.isReceivePaper()); model.addAttribute(“favoriteFrameworks”, user.getFavoriteFrameworks()); model.addAttribute(“gender”, user.getGender()); model.addAttribute(“favoriteNumber”, user.getFavoriteNumber()); return “users”; } @ModelAttribute(“webFrameworkList”) public List<String> getWebFrameworkList() { List<String> webFrameworkList = new ArrayList<String>(); webFrameworkList.add(“Spring MVC”); webFrameworkList.add(“Struts 1”); webFrameworkList.add(“Struts 2”); webFrameworkList.add(“Apache Wicket”); return webFrameworkList; } @ModelAttribute(“numbersList”) public List<String> getNumbersList() { List<String> numbersList = new ArrayList<String>(); numbersList.add(“1”); numbersList.add(“2”); numbersList.add(“3”); numbersList.add(“4″); return numbersList; } } Here, for the first service method user(), we have passed a blank User object in the ModelAndView object with name “command”, because the spring framework expects an object with name “command”, if you are using <form:form> tags in your JSP file. So, when user() method is called, it returns the user.jsp view. The second service method addUser() will be called against a POST method on the HelloWeb/addUser URL. You will prepare your model object based on the submitted information. Finally, the “users” view will be returned from the service method, which will result in rendering the users.jsp. user.jsp <%@taglib uri = “http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring MVC Form Handling</title> </head> <body> <h2>User Information</h2> <form:form method = “POST” action = “/HelloWeb/addUser”> <table> <tr> <td><form:label path = “username”>User Name</form:label></td> <td><form:input path = “username” /></td> </tr> <tr> <td><form:label path = “password”>Age</form:label></td> <td><form:password path = “password” /></td> </tr> <tr> <td><form:label path = “address”>Address</form:label></td> <td><form:textarea path = “address” rows = “5” cols = “30” /></td> </tr> <tr> <td><form:label path = “receivePaper”>Subscribe Newsletter</form:label></td> <td><form:checkbox path = “receivePaper” /></td> </tr> <tr> <td><form:label path = “favoriteFrameworks”>Favorite Web Frameworks</form:label></td> <td><form:checkboxes items = “${webFrameworkList}” path = “favoriteFrameworks” /></td> </tr> <tr> <td><form:label path = “gender”>Gender</form:label></td> <td> <form:radiobutton path = “gender” value = “M” label = “Male” /> <form:radiobutton path = “gender” value = “F” label = “Female” /> </td> </tr> <tr> <td><form:label path = “favoriteNumber”>Favorite Number</form:label></td> <td> <form:radiobuttons path = “favoriteNumber” items = “${numbersList}” /> </td> </tr> <tr> <td colspan = “2”> <input type = “submit” value = “Submit”/> </td> </tr> </table> </form:form> </body> </html> Here, we are using <form:radiobuttons />tag to render the HTML radiobuttons. For example − <form:radiobuttons path = “favoriteNumber” items=”${numbersList}” /> It will render the following HTML content. <span> <input id = “favoriteNumber1” name = “favoriteNumber” type = “radio” value = “1”/> <label for = “favoriteNumber1”>1</label> </span> <span> <input id = “favoriteNumber2” name = “favoriteNumber” type = “radio” value = “2”/> <label for = “favoriteNumber2”>2</label> </span> <span> <input id = “favoriteNumber3” name = “favoriteNumber” type = “radio” value = “3”/> <label for = “favoriteNumber3”>3</label> </span> <span> <input id = “favoriteNumber4” name = “favoriteNumber” type = “radio” value = “4”/> <label for = “favoriteNumber4”>4</label> </span> users.jsp <%@taglib uri = “http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring MVC Form Handling</title> </head> <body> <h2>Submitted User Information</h2> <table> <tr> <td>Username</td> <td>${username}</td> </tr> <tr> <td>Password</td> <td>${password}</td> </tr> <tr> <td>Address</td> <td>${address}</td> </tr> <tr> <td>Subscribed to Newsletter</td> <td>${receivePaper}</td> </tr> <tr> <td>Favorite Web Frameworks</td> <td> <% String[] favoriteFrameworks = (String[])request.getAttribute(“favoriteFrameworks”); for(String framework: favoriteFrameworks) { out.println(framework); } %></td> </tr> <tr> <td>Gender</td> <td>${(gender==”M”? “Male” : “Female”)}</td> </tr> <tr> <td>Favourite Number</td> <td>${favoriteNumber}</td> </tr> </table> </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 the HelloWeb.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 the following URL – http://localhost:8080/HelloWeb/user and we will see the following screen, if everything is fine with the Spring Web Application. After submitting the required information, click on the submit button to submit the form. We will see the following screen, if everything is fine with your Spring Web Application. Print Page Previous Next Advertisements ”;

Parameter Method Name Resolver

Spring MVC – Parameter Method Name Resolver Example ”; Previous Next The following example shows how to use the Parameter Method Name Resolver of a Multi Action Controller using the Spring Web MVC framework. The MultiActionController class helps to map multiple URLs with their methods in a single controller respectively. package com.tutorialspoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; public class UserController extends MultiActionController{ public ModelAndView home(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Home”); return model; } public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Add”); return model; } public ModelAndView remove(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Remove”); return model; } } <bean class = “com.tutorialspoint.UserController”> <property name = “methodNameResolver”> <bean class = “org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver”> <property name = “paramName” value = “action”/> </bean> </property> </bean> For example, using the above configuration, if URI − /user/*.htm?action=home is requested, DispatcherServlet will forward the request to the UserController home() method. /user/*.htm?action=add is requested, DispatcherServlet will forward the request to the UserController add() method. /user/*.htm?action=remove is requested, DispatcherServlet will forward the request to the UserController remove() method. 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 a Java class UserController under the com.tutorialspoint package. 3 Create a view file user.jsp under the jsp sub-folder. 4 The final step is to create the content of the source and configuration files and export the application as explained below. UserController.java package com.tutorialspoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; public class UserController extends MultiActionController{ public ModelAndView home(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Home”); return model; } public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Add”); return model; } public ModelAndView remove(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Remove”); return model; } } 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”> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/”/> <property name = “suffix” value = “.jsp”/> </bean> <bean class = “org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping”> <property name = “caseSensitive” value = “true” /> </bean> <bean class = “com.tutorialspoint.UserController”> <property name = “methodNameResolver”> <bean class = “org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver”> <property name = “paramName” value = “action”/> </bean> </property> </bean> </beans> user.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 the TestWeb.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. Now, try a URL − http://localhost:8080/TestWeb/user/test.htm?action=home and we will see the following screen, if everything is fine with the Spring Web Application. Print Page Previous Next Advertisements ”;

Properties Method Name Resolver

Spring MVC – Properties Method Name Resolver Example ”; Previous Next The following example shows how to use the Properties Method Name Resolver method of a Multi Action Controller using Spring Web MVC framework. The MultiActionController class helps to map multiple URLs with their methods in a single controller respectively. package com.tutorialspoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; public class UserController extends MultiActionController{ public ModelAndView home(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Home”); return model; } public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Add”); return model; } public ModelAndView remove(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Remove”); return model; } } <bean class = “com.tutorialspoint.UserController”> <property name = “methodNameResolver”> <bean class = “org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver”> <property name = “mappings”> <props> <prop key = “/user/home.htm”>home</prop> <prop key = “/user/add.htm”>add</prop> <prop key = “/user/remove.htm”>update</prop> </props> </property> </bean> </property> </bean> For example, using the above configuration, if URI − /user/home.htm is requested, DispatcherServlet will forward the request to the UserController home() method. /user/add.htm is requested, DispatcherServlet will forward the request to the UserController add() method. /user/remove.htm is requested, DispatcherServlet will forward the request to the UserController remove() method. To start with it, 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 Java class UserController under the com.tutorialspoint package. 3 Create a view file user.jsp under the jsp sub-folder. 4 The final step is to create the content of the source and configuration files and export the application as explained below. UserController.java package com.tutorialspoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; public class UserController extends MultiActionController{ public ModelAndView home(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Home”); return model; } public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Add”); return model; } public ModelAndView remove(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“user”); model.addObject(“message”, “Remove”); return model; } } 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”> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/”/> <property name = “suffix” value = “.jsp”/> </bean> <bean class = “org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping”> <property name = “caseSensitive” value = “true” /> </bean> <bean class = “com.tutorialspoint.UserController”> <property name = “methodNameResolver”> <bean class = “org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver”> <property name = “mappings”> <props> <prop key = “/user/home.htm”>home</prop> <prop key = “/user/add.htm”>add</prop> <prop key = “/user/remove.htm”>update</prop> </props> </property> </bean> </property> </bean> </beans> user.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 the TestWeb.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. Now, try a URL − http://localhost:8080/TestWeb/user/add.htm and we will see the following screen, if everything is fine with the Spring Web Application. Print Page Previous Next Advertisements ”;

Spring DI – Map Ref Setter

Spring DI – Map Ref Setter ”; Previous Next You have seen how to configure primitive data type using value attribute and object references using ref attribute of the <property> tag in your Bean configuration file. Both the cases deal with passing singular value to a bean. Now what if you want to pass Map. In this example, we”re showcasing passing direct values of the Map using setter injection. Example The following example shows a class JavaCollection that is using collections as dependency injected using setter method. Let”s update the project created in Spring DI – Create Project chapter. We”re adding following files − Address.java − A class to be used as dependency. JavaCollection.java − A class containing a collections of dependencies. MainApp.java − Main application to run and test. Here is the content of Address.java file − package com.tutorialspoint; public class Address { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return name; } } Here is the content of JavaCollection.java file − package com.tutorialspoint; import java.util.*; public class JavaCollection { Map<String, Address> addressMap; public JavaCollection() {} public JavaCollection(Map<String, Address> addressMap) { this.addressMap = addressMap; } // a setter method to set Map public void setAddressMap(Map<String, Address> addressMap) { this.addressMap = addressMap; } // prints and returns all the elements of the Map. public Map<String, Address> getAddressMap() { System.out.println(“Map Elements :” + addressMap); return addressMap; } } Following is the content of the MainApp.java file − package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“applicationcontext.xml”); JavaCollection jc=(JavaCollection)context.getBean(“javaCollection”); jc.getAddressMap(); } } Following is the configuration file applicationcontext.xml which has configuration for all the type of collections − <?xml version = “1.0” encoding = “UTF-8”?> <beans xmlns = “http://www.springframework.org/schema/beans” 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”> <bean id = “address1” class = “com.tutorialspoint.Address”> <property name=”name” value=”INDIA”></property> </bean> <bean id = “address2” class = “com.tutorialspoint.Address”> <property name=”name” value=”JAPAN”></property> </bean> <bean id = “address3” class = “com.tutorialspoint.Address”> <property name=”name” value=”USA”></property> </bean> <bean id = “address4” class = “com.tutorialspoint.Address”> <property name=”name” value=”UK”></property> </bean> <bean id = “javaCollection” class = “com.tutorialspoint.JavaCollection”> <property name = “addressMap”> <map> <entry key = “1” value-ref = “address1″/> <entry key = “2” value-ref = “address2″/> <entry key = “3” value-ref = “address3″/> <entry key = “4” value-ref = “address4″/> </map> </property> </bean> </beans> Output Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message − Map Elements :{1=INDIA, 2=JAPAN, 3=USA, 4=UK} Print Page Previous Next Advertisements ”;

Struts2 – Value Stack/OGNL

Struts 2 – Value Stack/OGNL ”; Previous Next The Value Stack The value stack is a set of several objects which keeps the following objects in the provided order − Sr.No Objects & Description 1 Temporary Objects There are various temporary objects which are created during execution of a page. For example the current iteration value for a collection being looped over in a JSP tag. 2 The Model Object If you are using model objects in your struts application, the current model object is placed before the action on the value stack. 3 The Action Object This will be the current action object which is being executed. 4 Named Objects These objects include #application, #session, #request, #attr and #parameters and refer to the corresponding servlet scopes. The value stack can be accessed via the tags provided for JSP, Velocity or Freemarker. There are various tags which we will study in separate chapters, are used to get and set struts 2.0 value stack. You can get valueStack object inside your action as follows − ActionContext.getContext().getValueStack() Once you have a ValueStack object, you can use the following methods to manipulate that object − Sr.No ValueStack Methods & Description 1 Object findValue(String expr) Find a value by evaluating the given expression against the stack in the default search order. 2 CompoundRoot getRoot() Get the CompoundRoot which holds the objects pushed onto the stack. 3 Object peek() Get the object on the top of the stack without changing the stack. 4 Object pop() Get the object on the top of the stack and remove it from the stack. 5 void push(Object o) Put this object onto the top of the stack. 6 void set(String key, Object o) Sets an object on the stack with the given key so it is retrievable by findValue(key,…) 7 void setDefaultType(Class defaultType) Sets the default type to convert to if no type is provided when getting a value. 8 void setValue(String expr, Object value) Attempts to set a property on a bean in the stack with the given expression using the default search order. 9 int size() Get the number of objects in the stack. The OGNL The Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and manipulate data on the ValueStack. OGNL also helps in data transfer and type conversion. The OGNL is very similar to the JSP Expression Language. OGNL is based on the idea of having a root or default object within the context. The properties of the default or root object can be referenced using the markup notation, which is the pound symbol. As mentioned earlier, OGNL is based on a context and Struts builds an ActionContext map for use with OGNL. The ActionContext map consists of the following − Application − Application scoped variables Session − Session scoped variables Root / value stack − All your action variables are stored here Request − Request scoped variables Parameters − Request parameters Atributes − The attributes stored in page, request, session and application scope It is important to understand that the Action object is always available in the value stack. So, therefore if your Action object has properties “x” and “y” there are readily available for you to use. Objects in the ActionContext are referred using the pound symbol, however, the objects in the value stack can be directly referenced. For example, if employee is a property of an action class, then it can be referenced as follows − <s:property value = “name”/> instead of <s:property value = “#name”/> If you have an attribute in session called “login” you can retrieve it as follows − <s:property value = “#session.login”/> OGNL also supports dealing with collections – namely Map, List and Set. For example to display a dropdown list of colors, you could do − <s:select name = “color” list = “{”red”,”yellow”,”green”}” /> The OGNL expression is clever to interpret the “red”,”yellow”,”green” as colours and build a list based on that. The OGNL expressions will be used extensively in the next chapters when we will study different tags. So rather than looking at them in isolation, let us look at it using some examples in the Form Tags / Control Tags / Data Tags and Ajax Tags section. ValueStack/OGNL Example Create Action Let us consider the following action class where we are accessing valueStack and then setting few keys which we will access using OGNL in our view, i.e., JSP page. package com.tutorialspoint.struts2; import java.util.*; import com.opensymphony.xwork2.util.ValueStack; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class HelloWorldAction extends ActionSupport { private String name; public String execute() throws Exception { ValueStack stack = ActionContext.getContext().getValueStack(); Map<String, Object> context = new HashMap<String, Object>(); context.put(“key1”, new String(“This is key1”)); context.put(“key2”, new String(“This is key2”)); stack.push(context); System.out.println(“Size of the valueStack: ” + stack.size()); return “success”; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Actually, Struts 2 adds your action to the top of the valueStack when executed. So, the usual way to put stuff on the Value Stack is to add getters/setters for the values to your Action class and then use <s:property> tag to access the values. But I”m showing you how exactly ActionContext and ValueStack work in struts. Create Views Let us create the below jsp file HelloWorld.jsp in the WebContent folder in your eclipse project. This view will be displayed in case action returns success − <%@ page contentType = “text/html; charset = UTF-8” %> <%@ taglib prefix = “s” uri = “/struts-tags” %> <html> <head> <title>Hello World</title> </head> <body> Entered value : <s:property value = “name”/><br/> Value of key 1 : <s:property value = “key1” /><br/> Value of key 2 : <s:property value = “key2” /> <br/> </body> </html> We also need to create index.jsp in the WebContent folder whose content is as follows − <%@ page language = “java” contentType = “text/html; charset = ISO-8859-1” pageEncoding = “ISO-8859-1″%> <%@ taglib prefix = “s” uri = “/struts-tags”%> <!DOCTYPE html PUBLIC