You are on page 1of 30

Struts 2 Demo Application:

Struts 2 Demo Application: About Application: Application is a book store shopping cart and has following features, 1. First choose category from dropdown, then choose book name by selecting checkboxes, then click Add to Cart. It will show all book list which you are interested to purchase. Now click Purchase button, then select mode i.e. Cash or Card and then it will finally show total amount which you have to pay. 2. Registration page (using struts2 action form i.e. textbox, radio button, checkbox), Also using dojo calendar as we are using struts 2 dojo plugin jar. 3. Login and Logout 4. Session 5. Database operation 6. Locale setting, uncomment code //Locale.setDefault(Locale.CHINA); at login.jsp to see Chinese Locale demo, ApplicationResources.properties (default property file) ApplicationResources_zh_CN.properties (Chinese property file) 7. dao i.e. data access object 8. interceptor filter uses for validation(at login page just click login button to see required field validation check.) 9. Action classes 10. POJO classes i.e. Book, Category and User classes. Requirement: Please install following softwares to run below example, JDK 1.6 MySQL 5.0 and above database Eclipse Tomcat 6.0 server configured in Eclipse. Download below jars from Struts website, commons-fileupload-1.2.1.jar commons-io-1.3.2.jar freemarker-2.3.16.jar javassist-3.7.ga.jar ognl-3.0.jar struts2-core-2.2.1.jar struts2-dojo-plugin-2.1.2.jar xwork-core-2.2.1.jar Step 1: Create MySQL database struts2_training and execute below SQL in query browser to create tables and minimal data, /* MySQL - 5.1.34-community : Database - struts2_training MySQL/Oracle Connection String: try { //Class.forName("oracle.jdbc.driver.OracleDriver"); Class.forName("com.mysql.jdbc.Driver"); //con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","scott","tiger"); con=DriverManager.getConnection("jdbc:mysql://localhost/struts2_training", "root", "root");

} */ CREATE DATABASE /*!32312 IF NOT EXISTS*/`struts2_training` /*!40100 DEFAULT CHARACTER SET latin1 */; USE `struts2_training`; /*Table structure for table `aj_book` */ DROP TABLE IF EXISTS `aj_book`; CREATE TABLE `aj_book` ( `bookid` decimal(5,0) DEFAULT NULL, `bookname` varchar(100) DEFAULT NULL, `categoryid` decimal(5,0) DEFAULT NULL, `bookprice` float DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*Data for the table `aj_book` */ insert into `aj_book`(`bookid`,`bookname`,`categoryid`,`bookprice`) values ('1','Java Book 1','1',11),('2','Dotnet Book 2','2',22),('3','Java Book 2','1',33),('4','Dotnet Book 2','2',44); /*Table structure for table `aj_category` */ DROP TABLE IF EXISTS `aj_category`; CREATE TABLE `aj_category` ( `categoryid` decimal(5,0) DEFAULT NULL, `categoryname` varchar(50) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*Data for the table `aj_category` */ insert into `aj_category`(`categoryid`,`categoryname`) values ('1','JAVA'),('2','DotNet'); /*Table structure for table `aj_user` */ DROP TABLE IF EXISTS `aj_user`; CREATE TABLE `aj_user` ( `firstname` varchar(100) DEFAULT NULL, `lastname` varchar(100) DEFAULT NULL, `username` varchar(100) DEFAULT NULL, `password` varchar(100) DEFAULT NULL, `hobbies` varchar(100) DEFAULT NULL, `gender` varchar(7) DEFAULT NULL, `birthdate` date DEFAULT NULL, `emailid` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*Data for the table `aj_user` */

insert into `aj_user`(`firstname`,`lastname`,`username`,`password`,`hobbies`,`gender`,`birthdate`,`emailid `) values ('ajit','singh','user1','user1','music','M','0000-00-00','ajit_singh@example.com');

Step 2: Create a empty Dynamic web project and give ts name Struts2Application Step 3: Create a new package com.example.struts2.shopcart.dao, then create a new Java class ShopCartDAO and paste below code in this class. package com.example.struts2.shopcart.dao; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import com.example.struts2.shopcart.model.domain.Book; import com.example.struts2.shopcart.model.domain.Category; import com.example.struts2.shopcart.model.domain.User; public class ShopCartDAO { private Connection con; private PreparedStatement st; private ResultSet rs; public ShopCartDAO() { try { //Class.forName("oracle.jdbc.driver.OracleDriver"); Class.forName("com.mysql.jdbc.Driver"); //con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","scott","tige r"); con=DriverManager.getConnection("jdbc:mysql://localhost/struts2_training", "root", ""); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public boolean addUser(User user){ boolean added=false; try { st=con.prepareStatement("insert into aj_user values(?,?,?,?,?,?,?,?)"); st.clearParameters(); st.setString(1,user.getFirstName()); st.setString(2,user.getLastName()); st.setString(3,user.getUserName()); st.setString(4,user.getPassword());

st.setString(5,Arrays.toString(user.getHobbies())); st.setString(6,user.getGender()); st.setDate(7,new Date(user.getBirthDate().getTime())); st.setString(8,user.getEmailId()); int count=st.executeUpdate(); if(count==1){ added=true; System.out.println("+++++++++++++ Record Added+++++++"); } } catch (SQLException e) { e.printStackTrace(); } return added; } public void close(){ if(con!=null){ try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } public boolean isValid(User user){ boolean valid=false; try { st=con.prepareStatement("select * from aj_user where username " + "like ? and password like ?"); st.clearParameters(); st.setString(1,user.getUserName()); st.setString(2,user.getPassword()); rs=st.executeQuery(); if(rs.next()){ valid=true; } } catch (SQLException e) { e.printStackTrace(); } return valid; } public ArrayList<Category>getCategories(){ ArrayList<Category>categoryList=new ArrayList<Category>(); try { st=con.prepareStatement("select * from aj_category"); rs=st.executeQuery(); while(rs.next()){ categoryList.add(new Category(rs.getInt(1),rs.getString(2))); } } catch (SQLException e) { e.printStackTrace(); } for(Category c : categoryList){

System.out.println(c.getCategoryName()); } return categoryList; } public ArrayList<Book>getBooks(int categoryId){ ArrayList<Book>bookList=new ArrayList<Book>(); try { st=con.prepareStatement("select * from aj_book where categoryId=?"); st.clearParameters(); st.setInt(1,categoryId); rs=st.executeQuery(); while(rs.next()){ bookList.add(new Book(rs.getInt(1),rs.getString(2),rs.getInt(3),rs.getDouble(4))); } for(Book b : bookList){ System.out.println(b.getBookName()); } } catch (SQLException e) { e.printStackTrace(); } return bookList; } } Step 4: Create a new package com.example.struts2.shopcart.interceptors, then create a new Java class ShopcartSessionTracker and paste below code in this class. package com.example.struts2.shopcart.interceptors; import java.util.Collections; import java.util.Map; import java.util.Set; import javax.xml.crypto.dsig.spec.ExcC14NParameterSpec; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.Interceptor; import com.opensymphony.xwork2.util.TextParseUtil; public class ShopcartSessionTracker implements Interceptor{ Map<String, Object>session; private Set<String> excludeMethods=Collections.EMPTY_SET; private Set<String> includeMethods=Collections.EMPTY_SET; public void setExcludeMethods(String excludeMethods) { this.excludeMethods = TextParseUtil.commaDelimitedStringToSet(excludeMethods); System.out.println("+++++++++++ EX +++++++"+excludeMethods); } public void setIncludeMethods(String includeMethods) { this.includeMethods = TextParseUtil.commaDelimitedStringToSet(includeMethods);

System.out.println("++++++++++++In ++++"+includeMethods); } @Override public void destroy() { System.out.println("++++++++++ destroy ++++++++++++"); } @Override public void init() { System.out.println("+++++++++++ init++++++++++++++"); } @Override public String intercept(ActionInvocation invocation) throws Exception { String result=""; String className=invocation.getAction().getClass().getName(); String method=invocation.getProxy().getMethod(); System.out.println("Pre Process for "+className+" "+method); session=ActionContext.getContext().getSession(); String trackerId=(String)session.get("trackerId"); if(excludeMethods.contains(method)){ result=invocation.invoke(); }else if(includeMethods.contains(method)){ if(trackerId==null){ result="nosession"; }else{ result=invocation.invoke(); System.out.println("Post Process for "+className+" "+method); } } return result; } } Step 5: Create a new package com.example.struts2.shopcart.model.actions Step 6: Create a new Java class BookAction in com.example.struts2.shopcart.model.actions and paste below code in this class. package com.example.struts2.shopcart.model.actions; import com.example.struts2.shopcart.model.domain.Book; import com.opensymphony.xwork2.ActionSupport; public class BookAction extends ActionSupport { private String message; private Book book; public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public String add(){ message="Inside Add method Book Details : [ "+book.getBookId()+" "+ book.getBookName()+" ].";

System.out.println(message); return "success"; } public String update(){ message="Inside Update method Book Details : [ "+book.getBookId()+" "+ book.getBookName()+" ]."; System.out.println(message); return "success"; } public String delete(){ message="Inside Delete method Book Details : [ "+book.getBookId()+" "+ book.getBookName()+" ]."; System.out.println(message); return "success"; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } Step 7: Create a new Java class LoginAction in com.example.struts2.shopcart.model.actions and paste below code in this class. package com.example.struts2.shopcart.model.actions; import java.util.ArrayList; import java.util.Map; import com.example.struts2.shopcart.dao.ShopCartDAO; import com.example.struts2.shopcart.model.domain.Category; import com.example.struts2.shopcart.model.domain.User; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.util.ValueStack; public class LoginAction extends ActionSupport { private String userName; private String password; private User user; private ArrayList<Category>categoryList; private ShopCartDAO dao; private Map<String, Object>session; public ArrayList<Category> getCategoryList() { return categoryList; } public void setCategoryList(ArrayList<Category> categoryList) { this.categoryList = categoryList; } public ShopCartDAO getDao() { return dao; }

public void setDao(ShopCartDAO dao) { this.dao = dao; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } 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; } @Override public String execute() throws Exception { String result="failed"; session=ActionContext.getContext().getSession(); System.out.println(userName+" : "+password); dao=new ShopCartDAO(); user=new User(); user.setUserName(getUserName()); user.setPassword(getPassword()); setUser(user); if(dao.isValid(user)){ setCategoryList(dao.getCategories()); session.put("user",user); session.put("categoryList", getCategoryList()); session.put("trackerId", "1111"); result="success"; }else{ addActionError("Invalid Username or Password"); return ERROR; } dao.close(); /* ValueStack stack=ActionContext.getContext().getValueStack(); System.out.println(stack); System.out.println(stack.size()); */ return result; } @Override public void validate() { if(getUserName().length()==0){ addFieldError("userName","USERNAME is Required");

} if(getPassword().length()==0){ addFieldError("password", "PASSWORD is Required"); }else if(getPassword().length()<5){ addFieldError("password","PASSWORD must be MINIMUM 5 characters"); } } } Step 8: Create a new Java class PaymentAction in com.example.struts2.shopcart.model.actions and paste below code in this class. package com.example.struts2.shopcart.model.actions; import java.util.Map; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class PaymentAction extends ActionSupport { private String mode; private Map<String, Object>session; public String getMode() { return mode; } public void setMode(String mode) { this.mode = mode; } @Override public String execute() throws Exception { System.out.println(mode); session=ActionContext.getContext().getSession(); session.put("mode",mode); return mode; } } Step 9: Create a new Java class PaymentMade in com.example.struts2.shopcart.model.actions and paste below code in this class. package com.example.struts2.shopcart.model.actions; import com.opensymphony.xwork2.ActionSupport; public class PaymentMade extends ActionSupport { private String amount; private String cardNo; public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public String getCardNo() { return cardNo;

} public void setCardNo(String cardNo) { this.cardNo = cardNo; } @Override public String execute() throws Exception { System.out.println(amount+"========"+cardNo); /* * THE Business Logic may be placed here */ return "success"; } } Step 10: Create a new Java class RegisterAction in com.example.struts2.shopcart.model.actions and paste below code in this class. package com.example.struts2.shopcart.model.actions; import com.example.struts2.shopcart.dao.ShopCartDAO; import com.example.struts2.shopcart.model.domain.User; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.Preparable; public class RegisterAction extends ActionSupport implements ModelDriven<User>, Preparable { private User user; private ShopCartDAO dao; //if preparable is not implemented then create user obj in constr of Action @Override public void prepare() throws Exception { user=new User(); } @Override public User getModel() { return user; } @Override public String execute() throws Exception { dao=new ShopCartDAO(); boolean isAdded=dao.addUser(user); dao.close(); if(isAdded){ return "success"; }else{ return "failed"; } } } Step 11: Create a new Java class ShowBooksAction in com.example.struts2.shopcart.model.actions and paste below code in this class.

package com.example.struts2.shopcart.model.actions; import java.util.ArrayList; import java.util.Map; import org.apache.struts2.interceptor.SessionAware; import com.example.struts2.shopcart.dao.ShopCartDAO; import com.example.struts2.shopcart.model.domain.Book; import com.example.struts2.shopcart.model.domain.User; import com.opensymphony.xwork2.ActionSupport; public class ShowBooksAction extends ActionSupport implements SessionAware{ private static final long serialVersionUID = 1L; private Map<String, Object>session; private int category; private ShopCartDAO dao; private ArrayList<Book>bookList; @Override public void setSession(Map<String, Object> session) { this.session=session; } public int getCategory() { return category; } public void setCategory(int category) { this.category = category; } public ArrayList<Book> getBookList() { return bookList; } public void setBookList(ArrayList<Book> bookList) { this.bookList = bookList; } @Override public String execute() throws Exception { dao=new ShopCartDAO(); User user=(User)session.get("user"); System.out.println("---------"+user.getUserName()); session.put("amount", new Double(1234.5)); setBookList(dao.getBooks(category)); dao.close(); return "success"; } } Step 12: Create a new Java class StoreBooksAction in com.example.struts2.shopcart.model.actions and paste below code in this class. package com.example.struts2.shopcart.model.actions; import java.util.ArrayList; import java.util.Map; import org.apache.struts2.interceptor.SessionAware;

import com.example.struts2.shopcart.model.domain.Book; import com.opensymphony.xwork2.ActionSupport; public class StoreBooksAction extends ActionSupport implements SessionAware{ private static final long serialVersionUID = 1L; private Map<String, Object>session; private ArrayList<Book> currSelected; private ArrayList<Book>allBooks; private String[] selectedBooks; public String[] getSelectedBooks() { return selectedBooks; } public void setSelectedBooks(String[] selectedBooks) { this.selectedBooks = selectedBooks; } @Override public void setSession(Map<String, Object> session) { this.session=session; } @Override public String execute() throws Exception { currSelected=(ArrayList<Book>)session.get("currSelected"); allBooks=(ArrayList<Book>)session.get("allBooks"); Double bill=(Double)session.get("bill"); if(currSelected==null){ currSelected=new ArrayList<Book>(); } if(bill==null){ bill=0.0; } for(String id : selectedBooks){ for(Book b : allBooks){ if(b.getBookId()==Integer.parseInt(id)){ currSelected.add(b); bill+=b.getBookPrice(); break; } } } session.put("currSelected", currSelected); session.put("bill",bill); for(Book bk : currSelected){ System.out.println(bk.getBookName()); } System.out.println("BILL :: "+bill); return "success"; } } Step 13: Create a new property file LoginApplicationResources.properties in src\com\example\struts2\shopcart\model\actions and paste below code in this class. label.userName=USERNAME label.password=PASSWORD

Step 13: Create a new xml file RegisterAction-validation.xml in src\com\example\struts2\shopcart\model\actions and paste below code in this class. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> <validators> <field name="firstName"> <field-validator type="requiredstring"> <message key="First name is required"/> </field-validator> </field> <field name="lastName"> <field-validator type="requiredstring"> <message key="Last name is required"/> </field-validator> </field> <field name="userName"> <field-validator type="required"> <message key="Please provide Your BirthDate"/> </field-validator> <field-validator type="requiredstring"> <message key="Username is required"/> </field-validator> </field> <field name="password"> <field-validator type="requiredstring"> <message key="Password is required"/> </field-validator> <field-validator type="expression"> <param name="expression">userName!=password</param> <message key="USERNAME and PASSWORD cannot be same"/> </field-validator> </field> <field name="emailId"> <field-validator type="requiredstring"> <message key="Email-Id is required"/> </field-validator> <field-validator type="email"> <message key="enter a valid Email-Id "/> </field-validator> </field> <field name="gender"> <field-validator type="requiredstring">

<message key="Please select the gender"/> </field-validator> </field> <field name="hobbies"> <field-validator type="expression"> <param name="expression">hobbies.length !=0 </param> <message key="Please select the hobby"/> </field-validator> </field> <field name="birthDate"> <field-validator type="required"> <message key="Please Provide a BirthDate"/> </field-validator> <field-validator type="date"> <!-- The format here is mm-dd-yy --> <param name="min">1/1/70</param> <param name="max">12/31/05</param> <message key="Please enter a valid date"/> </field-validator> </field> <!-<field name="postalcode"> <field-validator type="requiredstring"> <message key="requiredstring"/> </field-validator> <field-validator type="regex"> <param name="expression"><![CDATA[^\d*$]]></param> <message key="requiredinteger"/> </field-validator> </field> --> </validators>

Step 14: Create a new package com.example.struts2.shopcart.model.domain, then create a new Java class Book and paste below code in this class. package com.example.struts2.shopcart.model.domain; public class Book { private int bookId; private String bookName; private int categoryId; private double bookPrice; public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public String getBookName() {

return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public int getCategoryId() { return categoryId; } public void setCategoryId(int categoryId) { this.categoryId = categoryId; } public double getBookPrice() { return bookPrice; } public void setBookPrice(double bookPrice) { this.bookPrice = bookPrice; } public Book(int bookId, String bookName, int categoryId, double bookPrice) { super(); this.bookId = bookId; this.bookName = bookName; this.categoryId = categoryId; this.bookPrice = bookPrice; } public Book() {} } Step 15: Create a new Java class Category in package com.example.struts2.shopcart.model.domain and paste below code in this class. package com.example.struts2.shopcart.model.domain; public class Category { private int categoryId; private String categoryName; public Category() {} public Category(int categoryId,String categoryName){ this.categoryId=categoryId; this.categoryName=categoryName; } public int getCategoryId() { return categoryId; } public void setCategoryId(int categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } }

Step 16: Create a new Java class User in package com.example.struts2.shopcart.model.domain and paste below code in this class. package com.example.struts2.shopcart.model.domain; import java.util.Date; public class User { private String firstName; private String lastName; private String userName; private String password; private String[] hobbies; private String gender; private Date birthDate; private String emailId; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } 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[] getHobbies() { return hobbies; } public void setHobbies(String[] hobbies) { this.hobbies = hobbies; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthDate() { return birthDate; }

public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } } Step 17: Create i18n property file ApplicationResources.properties in src folder and paste below code, label.userName=UserName label.password=Password label.login.submit=Login Step 18: Create i18n property file ApplicationResources_zh_CN.properties (for Chinese character) in src folder and paste below code, label.userName=\u7528\u6237\u540D label.password=\u5BC6\u7801 label.login.submit=\u63D0\u4EA4 Step 19: Create struts-2.1.7.dtd in src folder and paste below code, <?xml version="1.0" encoding="UTF-8"?> <!-/* * $Id: struts-2.0.dtd 651946 2008-04-27 13:41:38Z apetrelli $ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ --> <!-- START SNIPPET: strutsDtd -->

<!-Struts configuration DTD. Use the following DOCTYPE <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"> --> <!ELEMENT struts ((package|include|bean|constant)*, unknown-handler-stack?)> <!ATTLIST struts order CDATA #IMPLIED > <!ELEMENT package (result-types?, interceptors?, default-interceptor-ref?, default-action-ref?, default-class-ref?, global-results?, global-exception-mappings?, action*)> <!ATTLIST package name CDATA #REQUIRED extends CDATA #IMPLIED namespace CDATA #IMPLIED abstract CDATA #IMPLIED externalReferenceResolver NMTOKEN #IMPLIED > <!ELEMENT result-types (result-type+)> <!ELEMENT result-type (param*)> <!ATTLIST result-type name CDATA #REQUIRED class CDATA #REQUIRED default (true|false) "false" > <!ELEMENT interceptors (interceptor|interceptor-stack)+> <!ELEMENT interceptor (param*)> <!ATTLIST interceptor name CDATA #REQUIRED class CDATA #REQUIRED > <!ELEMENT interceptor-stack (interceptor-ref*)> <!ATTLIST interceptor-stack name CDATA #REQUIRED > <!ELEMENT interceptor-ref (param*)> <!ATTLIST interceptor-ref name CDATA #REQUIRED > <!ELEMENT default-interceptor-ref (#PCDATA)> <!ATTLIST default-interceptor-ref

name CDATA #REQUIRED > <!ELEMENT default-action-ref (#PCDATA)> <!ATTLIST default-action-ref name CDATA #REQUIRED > <!ELEMENT default-class-ref (#PCDATA)> <!ATTLIST default-class-ref class CDATA #REQUIRED > <!ELEMENT global-results (result+)> <!ELEMENT global-exception-mappings (exception-mapping+)> <!ELEMENT action (param|result|interceptor-ref|exception-mapping)*> <!ATTLIST action name CDATA #REQUIRED class CDATA #IMPLIED method CDATA #IMPLIED converter CDATA #IMPLIED > <!ELEMENT param (#PCDATA)> <!ATTLIST param name CDATA #REQUIRED > <!ELEMENT result (#PCDATA|param)*> <!ATTLIST result name CDATA #IMPLIED type CDATA #IMPLIED > <!ELEMENT exception-mapping (#PCDATA|param)*> <!ATTLIST exception-mapping name CDATA #IMPLIED exception CDATA #REQUIRED result CDATA #REQUIRED > <!ELEMENT include (#PCDATA)> <!ATTLIST include file CDATA #REQUIRED > <!ELEMENT bean (#PCDATA)> <!ATTLIST bean type CDATA #IMPLIED name CDATA #IMPLIED class CDATA #REQUIRED

scope CDATA #IMPLIED static CDATA #IMPLIED optional CDATA #IMPLIED > <!ELEMENT constant (#PCDATA)> <!ATTLIST constant name CDATA #REQUIRED value CDATA #REQUIRED > <!ELEMENT unknown-handler-stack (unknown-handler-ref*)> <!ELEMENT unknown-handler-ref (#PCDATA)> <!ATTLIST unknown-handler-ref name CDATA #REQUIRED > <!-- END SNIPPET: strutsDtd --> Step 20: Create struts.xml in src folder and paste below code, <?xml version="1.0" encoding="UTF-8"?> <!-<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"> --> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "struts-2.1.7.dtd"> <struts> <constant name="struts.devMode" value="true"/> <constant name="struts.custom.i18n.resources" value="ApplicationResources"/> <package name="login" extends="struts-default"> <interceptors> <interceptor name="SessionInterceptor" class="com.example.struts2.shopcart.interceptors.ShopcartSessionTracker"/> <interceptor-stack name="SessionStack"> <interceptor-ref name="SessionInterceptor"> <param name="includeMethods">execute,update</param> <param name="excludeMethods">add,delete</param> </interceptor-ref> <interceptor-ref name="defaultStack"/> </interceptor-stack> </interceptors> <global-results> <result name="nosession">/jsps/invalidsession.jsp</result> </global-results> <action name="logout"> <result>/jsps/logout.jsp</result> </action> <action name="gotologin"> <result>/jsps/login.jsp</result> </action>

<action name="gotoregister"> <result>/jsps/register.jsp</result> </action> <action name="purchase"> <result>/jsps/payment.jsp</result> </action> <!-- The action name (log) given here is set as attribute to submit button on login.jsp page --> <action name="log" class="com.example.struts2.shopcart.model.actions.LoginAction"> <result name="success">/jsps/category.jsp</result> <result name="failed">/jsps/failed.jsp</result> <result name="input">/jsps/login.jsp</result> <result name="error">/jsps/login.jsp</result> </action> <action name="register" class="com.example.struts2.shopcart.model.actions.RegisterAction"> <result name="success">/jsps/registersuccess.jsp</result> <result name="failed">/jsps/failed.jsp</result> <result name="input">/jsps/register.jsp</result> </action> <action name="showbooks" class="com.example.struts2.shopcart.model.actions.ShowBooksAction"> <interceptor-ref name="SessionStack"/> <interceptor-ref name="execAndWait"> <param name="delaySleepInterval">100</param> </interceptor-ref> <result name="wait">/jsps/wait.jsp</result> <result name="success" >/jsps/showbooks.jsp</result> <result name="input">/jsps/category.jsp</result> </action> <action name="selectedbooks" class="com.example.struts2.shopcart.model.actions.StoreBooksAction"> <interceptor-ref name="SessionStack"/> <result name="success" >/jsps/showselected.jsp</result> <result name="input">/jsps/showbooks.jsp</result> </action> <action name="makepayment" class="com.example.struts2.shopcart.model.actions.PaymentAction"> <interceptor-ref name="SessionStack"/> <result name="Cash" >/jsps/billdetails.jsp</result> <result name="Card" >/jsps/billdetails.jsp</result> <result name="input">/jsps/payment.jsp</result> </action> <action name="thankyou" class="com.example.struts2.shopcart.model.actions.PaymentMade" method="execute"> <interceptor-ref name="SessionStack"/> <result>/jsps/thankyou.jsp</result> <result name="input">/jsps/billdetails.jsp</result> </action> <action name="*Book" method="{1}"

class="com.example.struts2.shopcart.model.actions.BookAction"> <interceptor-ref name="SessionStack"/> <result>/jsps/success.jsp</result> </action> </package> </struts>

Step 21: Paste below jar files in WebContent\WEB-INF\lib folder, commons-fileupload-1.2.1.jar commons-io-1.3.2.jar freemarker-2.3.16.jar javassist-3.7.ga.jar ognl-3.0.jar struts2-core-2.2.1.jar struts2-dojo-plugin-2.1.2.jar xwork-core-2.2.1.jar Step 22: Paste below content in WebContent\WEB-INF\web.xml, <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/webapp_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>Struts2TrainingProj</display-name> <welcome-file-list> <welcome-file>/jsps/index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filterclass> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>

Step 23: Create a new folder jsps in WebContent folder. Step 24: Create billdetails.jsp in jsps folder and paste below code in this file, <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html>

<head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Bill Details</title> </head> Welcome <s:property value="#session.user.userName"/> <a href='<s:url action="logout"/>'>LogOut</a> <body> <s:form action="thankyou"> <s:if test="#session.mode.equals('Cash')"> <s:text name=" Make Cash Payment"/> <s:textfield label="Amount : " name="amount" value="%{#session['bill']}" readonly="true"/> </s:if> <s:else> <s:text name="Make Card Payment"/> <s:textfield label="Amount : " name="amount" value="%{#session['bill']}" readonly="true"/> <s:textfield label="Card No. : " name="cardNo"/> </s:else> <s:submit value="Pay"/> </s:form> </body> </html> Step 25: Create bookutil.jsp in jsps folder and paste below code in this file, <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@taglib uri="/struts-tags" prefix="s" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <s:form action="book"> <s:textfield name="book.bookId" label="Book ID"/> <s:textfield name="book.bookName" label="Book Name"/> <s:textfield name="book.categoryId" label="Category ID"/> <s:textfield name="book.bookPrice" label="Book Price"/> <s:submit value="add" action="addBook"/> <s:submit value="update" action="updateBook"/> <s:submit value="delete" action="deleteBook"/> </s:form> </body> </html> Step 26: Create category.jsp in jsps folder and paste below code in this file, <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

<%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Category Page</title> </head> <body> Welcome <s:property value="#session.user.userName"/> <a href='<s:url action="logout"/>'>LogOut</a> <%-Welcome <s:property value="user.userName"/> <a href='<s:url action="logout"/>'>LogOut</a> --%> <center> <table border="2"> <thead>Select Category</thead> <s:form action="showbooks"> <tr><td> <s:select name="category" list="#session['categoryList']" listValue="categoryName" listKey="categoryId"/> </td></tr> <s:submit value="Select"/> </s:form> </table> </center> </body> </html> Step 27: Create failed.jsp in jsps folder and paste below code in this file, <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login Failed Page</title> </head> <body> <h2>Invalid USERNAME OR PASSWORD</h2> <a href='<s:url action="gotologin"/>'>Re-Login</a> </body> </html> Step 28: Create index.jsp in jsps folder and paste below code in this file, <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Index Page</title> </head> <body> <center> <table border="2"> <tr><td><a href='<s:url action="gotologin"/>'>Login</a></td></tr> <tr><td><a href='<s:url action="gotoregister"/>'>Register Here</a></td></tr> </table> </center> </body> </html> Step 29: Create invalidsession.jsp in jsps folder and paste below code in this file, <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Invalid Session</title> </head> <body> <center> <h2>Sorry !!!</h2> <A href="login.jsp">Please Login</A> </center> </body> </html> Step 30: Create login.jsp in jsps folder and paste below code in this file, <%@page import="java.util.Locale"%> <%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login Page</title> </head> <body> <center> <% //Locale.setDefault(Locale.CHINA); String locale=Locale.getDefault().toString(); out.println(" Current Locale :: "+locale);

%> <s:actionerror/> <s:form action="login"> <%-<s:i18n name="com.example.struts2.shopcart.model.actions.LoginApplicationResources"> --%> <s:textfield name="userName" key="label.userName"/> <s:password name="password" key="label.password"/> <%-</s:i18n> --%> <%--This action attrib must be set as name in struts.xml for corresponding action --%> <s:submit name="login" key="label.login.submit" action="log"/> </s:form> </center> </body> </html> Step 31: Create logout.jsp in jsps folder and paste below code in this file, <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Log Out Page</title> </head> <body> <h2>Logged Out Successfully</h2> <% session.invalidate(); %> </body> </html> Step 32: Create payment.jsp in jsps folder and paste below code in this file, <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Payment Page</title> </head> Welcome <s:property value="#session.user.userName"/> <a href='<s:url action="logout"/>'>LogOut</a> <body>

<center> <s:form action="makepayment"> <s:text name="Your Total Bill is : "/><s:text name="#session['bill']"/> <%-<s:radio label= "Payment Mode " name= "mode" list="#{'1':'Cash','2':'Card'}" value="2"/> --%> <s:radio label= "Payment Mode " name= "mode" list="{'Cash','Card'}"/> <s:submit value="Select Mode"/> </s:form> </center> </body> </html> Step 33: Create register.jsp in jsps folder and paste below code in this file, <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags" %> <%@ taglib prefix="sd" uri="/struts-dojo-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <%--Must be done in order for dojo tags to work --%> <sd:head parseContent="true"/> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Register Page</title> </head> <body> <center> <s:actionerror/> <s:form action="register"> <s:textfield name="firstName" label="First Name "/> <s:textfield name="lastName" label="Last Name "/> <s:textfield name="userName" label="User Name" /> <s:password name="password" label="Password" /> <s:radio name="gender" label="Gender" list="{'Male','Female'}" /> <s:checkboxlist list="{'Sports','Travel','Reading'}" name="hobbies" label="Hobbies" /> <s:fielderror fieldName="hobbies"/> <%--Shows datepicker from 1970 to 2005 --%> <sd:datetimepicker name="birthDate" label="BirthDate : " displayFormat="dd/MM/yy"/> <s:textfield name="emailId" label="Email-Id"/> <s:submit value="Register"/> </s:form> </center> </body> </html> Step 34: Create showbooks.jsp in jsps folder and paste below code in this file, <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

<%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Books Page</title> </head> Welcome <s:property value="#session.user.userName"/> <a href='<s:url action="logout"/>'>LogOut</a> <h3>Amount : <s:property value="#session['amount']"/> </h3> <body> <s:form action="selectedbooks" theme="simple"> <center> <table border=2><tr><td>Book Name</td><td>Book Price</td></tr> <s:set var="allBooks" value="bookList" scope="session"/> <s:iterator value="bookList"> <tr><td><s:checkbox name="selectedBooks" fieldValue="%{bookId}"/> <s:property value="bookName"/></td> <td><s:property value="bookPrice"/></td></tr> </s:iterator> <tr><td><s:submit value="Add To Cart"/></td></tr> </table> </center> </s:form> </body> </html> Step 35: Create showselected.jsp in jsps folder and paste below code in this file, <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Selected Books</title> </head> Welcome <s:property value="#session.user.userName"/> <a href='<s:url action="logout"/>'>LogOut</a> <body> <s:form action="purchase" theme="simple"> <center> <table border=2> <tr><td>Book Name</td><td>Book Price</td></tr> <s:iterator value="#session['currSelected']"> <tr><td><s:property value="bookName"/></td> <td><s:property value="bookPrice"/></td></tr> </s:iterator> <tr><td><s:text name="Current Bill : "/></td> <td><s:text name="#session['bill']"/> </td></tr>

<tr><td><s:submit value="Purchase"/> </td> <td><a href="jsps/category.jsp">More Books</a></td></tr> </table> </center> </s:form> </body> </html> Step 36: Create success.jsp in jsps folder and paste below code in this file, <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <H2>${message }</H2> </body> </html> Step 37: Create thankyou.jsp in jsps folder and paste below code in this file, <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Bill Payed</title> </head> Welcome <s:property value="#session.user.userName"/> <a href='<s:url action="logout"/>'>LogOut</a> <body> <center> <h2>Thank You for BILL Do visit again</h2> <h2><s:text name=" Recieved The Amount of Rs. "/><s:text name="#session.bill"/> </h2> </center> </body> </html> Step 38: Create wait.jsp in jsps folder and paste below code in this file, <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="/struts-tags" prefix="s"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="refresh" content="5;url=<s:url includeParams="all" />"/> <title>Insert title here</title> </head> <body> <H2>Please Wait the process is going on........</H2> </body> </html>

You might also like