Struts Example


Let’s see, how to develop a simple web application using Struts. Prior to this, want to learn about Struts basics go through these blogs Struts Basics & Struts Dispatch Action.
Before starting the application, download Tomcat-6.0.29.zip & Struts-1.3.10.zip

Follow the basic steps to configure struts in tomcat.

  • Unzip the tomcat zip file, you can get the folder apache-tomcat-6.0.29
  • Unzip the struts zip file, from that copy all jars from struts-1.3.10\lib directory to apache-tomcat-6.0.29\lib directory.
  • Copy the struts-1.3.10\src\taglib\src\main\resources\META-INF\tld\struts-html.tld file and place it under apache-tomcat-6.0.29\webapps\examples\WEB-INF directory.

Tomcat zip has the sample examples of jsp/servlet, which has been present under webapps/examples directory. We can use the same for developing our simple struts web application(Books Store).

In this app you are able to view the complete details of available books by accessing the url http://localhost:8080/examples/showbooks.do. From this page, you can do the basic operations like Add/Edit/Delete book.

Following steps are tell you how to implement this web app, what are the settings required to configure and where to place the action classes & jsp files.

web.xml or Deployment Descriptor.
We have to configure about ActionServlet in web application. This can be done by adding the following servlet definition to the apache-tomcat-6.0.29\webapps\examples\WEB-INF\web.xml file.

 <servlet>
 <servlet-name>action</servlet-name>
 <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
 <init-param>
 <param-name>config</param-name>
 <param-value>/WEB-INF/struts-config.xml</param-value>
 </init-param>
 <init-param>
 <param-name>validate</param-name>
 <param-value>true</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>
 

Servlet Mappings tells when the action should be executed.

 <servlet-mapping>
 <servlet-name>action</servlet-name>
 <url-pattern>*.do</url-pattern>
 </servlet-mapping>
 

To use HTML tag lib, you must add the following tag library entries into web.xml file.

 <taglib>
 <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
 <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
 </taglib>
 

struts-config.xml
This file is used to configure the struts framework details of a web application contains form-bean, action-mappings definitions.Add this file under apache-tomcat-6.0.29\webapps\examples\WEB-INF directory.

 <?xml version="1.0" encoding="ISO-8859-1" ?>
 <!DOCTYPE struts-config PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
 "http://struts.apache.org/dtds/struts-config_1_3.dtd" >

 <struts-config>
 <!-- Form Bean Definitions -->
 <form-beans>
 <form-bean name="BookForm" type="com.books.BookForm"/>
 </form-beans>

 <!--  Action Mapping Definitions  -->
 <action-mappings>
 <action path="/showbooks"
 type="com.books.ShowBooks"
 validate="false"
 scope="session">
 <forward name="success" path="/jsp/books/books.jsp"/>
 </action>

 <!-- Example of Struts Dispatch Action : has the extra attribute parameter-->
 <action path="/bookaction"
 type="com.books.BookActions"
 parameter="actionMethod"
 name="BookForm"
 validate="false"
 scope="session">
 <forward name="addBook" path="/jsp/books/addbook.jsp"/>
 <forward name="editBook" path="/jsp/books/editbook.jsp"/>
 <forward name="deleteBook" path="/jsp/books/deletebook.jsp"/>
 </action>
 </action-mappings>
 </struts-config>
 

ShowBooks.java
Action class used to show the book details page. In this example, I used class objects to store the book details you can use database to store the content of your app. This class been invoked when you access this url http://localhost:8080/examples/showbooks.do from the web browser.

 package com.books;

 import org.apache.struts.action.ActionForm;
 import org.apache.struts.action.ActionMapping;
 import org.apache.struts.action.ActionForward;
 import org.apache.struts.action.Action;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;

 public class ShowBooks extends Action
 {
 public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Show Books List");
 Books b = Books.getInstance();
 request.setAttribute("booksList", b.getBookList());
 return mapping.findForward("success");
 }
 }
 

Books.java
Class used to store the book details i.e., app data is persisted in jvm memory, this will get lost once you restarted the tomcat server. So you can use databases to store your application data.

 package com.books;

 import java.util.Map;
 import java.util.HashMap;
 import java.util.List;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.Set;

 class Books {

 int bookIdCount = 1000;
 Map<Integer, StoreBook> bookMap = new HashMap<Integer, StoreBook>();
 private static Books books = null;

 private Books() {
 }

 public static Books getInstance() {
 if (books == null) {
 books = new Books();
 }
 return books;
 }

 public void storeBook(String bookName, String authorName, int bookCost) {
 StoreBook sb = new StoreBook();
 bookIdCount++;
 sb.addBook(bookIdCount, bookName, authorName, bookCost);
 bookMap.put(bookIdCount, sb);
 }

 public void updateBook(int bookId, String bookName, String authorName, int bookCost) {
 StoreBook sb = bookMap.get(bookId);
 sb.updateBook(bookName, authorName, bookCost);
 }

 public Map searchBook(int bookId) {
 return bookMap.get(bookId).getBooks();
 }

 public void deleteBook(int bookId) {
 bookMap.remove(bookId);
 }
 // Inner Class used to persist the app data ie) book details.
 class StoreBook {

 private String bookName;
 private String authorName;
 private int bookCost;
 private int bookId;

 StoreBook() {
 }

 public void addBook(int bookId, String bookName, String authorName, int bookCost) {
 this.bookId = bookId;
 this.bookName = bookName;
 this.authorName = authorName;
 this.bookCost = bookCost;
 }

 public void updateBook(String bookName, String authorName, int bookCost) {
 this.bookName = bookName;
 this.authorName = authorName;
 this.bookCost = bookCost;
 }

 public Map getBooks() {
 Map books = new HashMap();
 books.put("BookId", this.bookId);
 books.put("BookName", this.bookName);
 books.put("AuthorName", this.authorName);
 books.put("BookCost", this.bookCost);
 return books;
 }
 }

 public List getBookList() {
 List booksList = new ArrayList();
 Set s = bookMap.keySet();
 Iterator itr = s.iterator();
 while (itr.hasNext()) {
 booksList.add(bookMap.get((Integer)itr.next()).getBooks());
 }
 return booksList;
 }
 }
 


BookForm.java

Form bean class has the getter & setter methods of corresponding form input elements. With this, you can get and set the value of form elements in the Action class.

 package com.books;

 import org.apache.struts.action.ActionForm;

 public class BookForm extends ActionForm {

 private String bookName;
 private String authorName;
 private int bookCost;
 private int bookId;

 public BookForm() {
 super();
 }

 public String getBookName() {
 return bookName;
 }
 public void setBookName(String bookName) {
 this.bookName = bookName;
 }

 public String getAuthorName() {
 return authorName;
 }
 public void setAuthorName(String authorName) {
 this.authorName = authorName;
 }

 public int getBookCost() {
 return bookCost;
 }
 public void setBookCost(int bookCost) {
 this.bookCost = bookCost;
 }

 public int getBookId() {
 return bookId;
 }
 public void setBookId(int bookId) {
 this.bookId = bookId;
 }
 }
 

BookActions.java
It’s an example of struts DispatchAction class, each and every action/function of book has equivalent methods to process it. This class been invoked when you access these url’s from the web browser.
Add Book : http://localhost:8080/examples/bookaction.do?actionMethod=AddBook
Edit Book : http://localhost:8080/examples/bookaction.do?actionMethod=EditBook&bookId=1008
Delete Book : http://localhost:8080/examples/bookaction.do?actionMethod=DeleteBook

 package com.books;

 import org.apache.struts.action.ActionForm;
 import org.apache.struts.action.ActionMapping;
 import org.apache.struts.action.ActionForward;
 import org.apache.struts.actions.DispatchAction;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;

 import java.util.Map;

 public class BookActions extends DispatchAction
 {
 public ActionForward AddBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Add Book Page");
 return mapping.findForward("addBook");
 }

 public ActionForward EditBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Edit Book Page");
 int bookId = Integer.parseInt(request.getParameter("bookId"));

 Books b = Books.getInstance();
 Map bookDet = b.searchBook(bookId);

 //Used form bean class methods to fill the form input elements with selected book values.
 BookForm bf = (BookForm)form;
 bf.setBookName(bookDet.get("BookName").toString());
 bf.setAuthorName(bookDet.get("AuthorName").toString());
 bf.setBookCost((Integer)bookDet.get("BookCost"));
 bf.setBookId((Integer)bookDet.get("BookId"));
 return mapping.findForward("editBook");
 }

 public ActionForward SaveBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Save Book");
 //Used form bean class methods to get the value of form input elements.
 BookForm bf = (BookForm)form;
 String bookName = bf.getBookName();
 String authorName = bf.getAuthorName();
 int bookCost = bf.getBookCost();

 Books b = Books.getInstance();
 b.storeBook(bookName, authorName, bookCost);
 return new ActionForward("/showbooks.do", true);
 }

 public ActionForward UpdateBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Update Book");
 BookForm bf = (BookForm)form;
 String bookName = bf.getBookName();
 String authorName = bf.getAuthorName();
 int bookCost = bf.getBookCost();
 int bookId = bf.getBookId();

 Books b = Books.getInstance();
 b.updateBook(bookId, bookName, authorName, bookCost);
 return new ActionForward("/showbooks.do", true);
 }

 public ActionForward DeleteBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Delete Book");
 int bookId = Integer.parseInt(request.getParameter("bookId"));
 Books b = Books.getInstance();
 b.deleteBook(bookId);
 return new ActionForward("/showbooks.do", true);
 }
 }
 

books.jsp
File used to show the available books in the app store. This page is being forwarded from the ShowBooks action class.

 <%@ page import="java.util.HashMap"%>
 <%@ page import="java.util.Map"%>
 <%@ page import="java.util.List"%>
 <%@ page import="java.util.ArrayList"%>
 <%@ page import="java.util.Iterator"%>
 <html>
 <body>
 <p><b>Struts Example - Simple Book Store App</b></p>
 <b>Available Books</b>
 <form name="bookform" action="/examples/bookaction.do">
 <table style="background-color:#82CAFA;">
 <tr style="color:yellow;"><th>&nbsp;</th><th>Book Name</th><th>Author Name</th><th>Book Cost</th></tr>
 <%List bookList = (ArrayList)request.getAttribute("booksList");
 Iterator itr = bookList.iterator();
 while(itr.hasNext()){
 Map map = (HashMap)itr.next();
 %>
 <tr><td><input type="radio" name="bookId" value='<%=map.get("BookId")%>' onclick="javascript:enableEditDelete();"></td>
 <td><%=map.get("BookName")%></td><td><%=map.get("AuthorName")%></td><td><%=map.get("BookCost")%></td>
 </tr>
 <%}%>
 </table>
 </p>
 <p>
 <table><tr>
 <td><input type="submit" name="actionMethod" value="AddBook" /></td>
 <td><input type="submit" name="actionMethod" id="editbutton" value="EditBook" disabled="true" /></td>
 <td><input type="submit" name="actionMethod" id="deletebutton" value="DeleteBook" disabled="true" onclick="return checkDelete();" /></td>
 </tr></table>
 </form>
 </p>
 <script>
 function checkDelete(){
 return confirm("Are u sure to delete this book..?");
 }
 function enableEditDelete(){
 document.getElementById('editbutton').disabled=false;
 document.getElementById('deletebutton').disabled=false;
 }
 </script>
 </body>
 </html>
 

addbook.jsp
Web page used to add a new book to the app store.

 <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
 <html>
 <body>
 <p><b>Struts Example - Simple Book Store App</b></p>
 <b>Add Book</b>
 <html:form>
 <table style="background-color:#82CAFA;">
 <tr><td>Book Name</td><td><html:text property="bookName" value=""/></td></tr>
 <tr><td>Author Name</td><td><html:text property="authorName" value=""/></td></tr>
 <tr><td>Book Cost</td><td><html:text property="bookCost" value=""/></td></tr>
 </table>
 </p>
 <p>
 <table><tr>
 <td><input type="submit" name="actionMethod" value="SaveBook" /></td>
 </tr></table>
 </html:form>
 </p>
 </body>
 </html>
 


editbook.jsp

In this page, used HTML tag lib, form bean class(BookForm) will take care of filling the form input elements.

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
 <html>
 <body>
 <p><b>Struts Example - Simple Book Store App</b></p>
 <b>Edit Book</b>
 <html:form>
 <table style="background-color:#82CAFA;">
 <tr><td>Book Id</td><td><html:text property="bookId" disabled="true"/></td></tr>
 <tr><td>Book Name</td><td><html:text property="bookName"/></td></tr>
 <tr><td>Author Name</td><td><html:text property="authorName"/></td></tr>
 <tr><td>Book Cost</td><td><html:text property="bookCost"/></td></tr>
 </table>
 </p>
 <p>
 <table><tr>
 <td><input type="submit" name="actionMethod" value="UpdateBook" /></td>
 </tr></table>
 </html:form>
 </p>
 </body>
 </html>
 

Note:

  • All the jsp files should present under directory apache-tomcat-6.0.29\webapps\examples\jsp\books.
  • Compile all the java files, and place the created class files to apache-tomcat-6.0.29\webapps\examples\WEB-INF\classes

All the codes specified in this blog will compile & work perfectly without any issues. Just download and try it. It’s very easy to learn and build applications in Struts.

Sample Output of Book Store Apps.

Available Books in Store

Add Book Web Page

Add Book

Edit Book Web Page

Edit Book


Tags: , , , , , , , , , , , , ,

3 Responses to “Struts Example”

  1. Dinesh Says:

    Hi Mani,

    Nice initiative. Good example.
    Go ahead.


    Dinesh

  2. Anand Says:

    An Article explaining the MVC Architecture that is used in this struts example can be found. Click Here

  3. vijay Says:

    Good example

Leave a comment