Struts2 Implement CRUD (add-check) function Instance code _java

Source: Internet
Author: User

CRUD is the abbreviation for Create (create), read (read), update (update), and delete (delete), which is the epitome of a common application. If you have the crud writing for a framework, it means you can use the framework to create a generic application, so when you develop an OLTP (Online Transaction Processing) application using the new framework, you'll first look at how to write crud. It's like writing "Hello World" when you're learning a new programming language.

This article is intended to describe the crud development on Struts 2, so for the sake of simplicity, I will not spend time on database operations. Instead, a hash Map of a mock database.

Concrete implementation

First, let's take a look at the "fake" DAO (data Access Object), the following code:

Package Tutorial.dao;
Import java.util.Collection;
Import Java.util.concurrent.ConcurrentHashMap;
Import Java.util.concurrent.ConcurrentMap;
Import Tutorial.model.Book; 
public class Bookdao {private static final Bookdao instance; private static final concurrentmap<string, book> data; static {instance = new Bookdao (); data = new concurrenthashmap<string, book> (); Data.put ("978-0735619678", New Boo
K ("978-0735619678", "Code Complete, Second Edition", 32.99));
Data.put ("978-0596007867", New book ("978-0596007867", "Art of Project Management", 35.96)); Data.put ("978-0201633610", New book ("978-0201633610", "Design patterns:elements of reusable object-oriented",
43.19)); Data.put ("978-0596527341", New book ("978-0596527341", "information architecture to the world Wide web:designing
Cale Web Sites ", 25.19));
Data.put ("978-0735605350", New book ("978-0735605350", "Software estimation:demystifying-Black Art", 25.19)); Private Bookdao () {} public static BOokdao getinstance () {return instance.} public collection<book> Getbooks () {return data.values ():} Public book G  Etbook (String ISBN) {return Data.get (ISBN);} public void Storebook (book book) {Data.put (BOOK.GETISBN (), book);
void Removebook (String ISBN) {data.remove (ISBN);} public void Removebooks (string[] ISBNs) {for (string Isbn:isbns) {
Data.remove (ISBN); }
}
}

Listing 1 Src/tutorial/dao/bookdao.java

The above code is not to be explained. As you know, I use the CONCURRENTMAP data structure to store the book object, primarily to facilitate the retrieval and preservation of the object, and I also set the data variable to be the only static one to simulate the application's database.

Next is the data model book class, the code is as follows:

Package Tutorial.model;
public class Book {
Private String ISBN;
Private String title;
private double price;
Public book () { 
} public book
(string ISBN, string title, double price) {
this.isbn = ISBN;
this.title = title;
This.price = Price;
}
Public String GETISBN () {return
ISBN;
}
public void Setisbn (String ISBN) {
this.isbn = ISBN;
}
Public double GetPrice () {return price
;
}
public void Setprice (double price) {
This.price = Price;
}
Public String GetTitle () {return
title;
}
public void Settitle (String title) {
this.title = title;
} 
}

Listing 2 Src/tutorial/model/book.java

The book class has three properties ISBN, and title and price represent the number of books, names, and prices, where the number is used to uniquely identify the book (the primary key in a comparable database).

Then we'll look at the code for the Action class:

Package tutorial.action;
Import java.util.Collection;
Import Tutorial.dao.BookDao;
Import Tutorial.model.Book;
Import Com.opensymphony.xwork2.ActionSupport; public class Bookaction extends Actionsupport {private static final long serialversionuid = 872316812305356L; private Str
ING ISBN;
Private string[] ISBNs;
Private book book;
Private collection<book> Books;
Private Bookdao DAO = Bookdao.getinstance (); Public book GetBook () {return book.} public void Setbook [book book] {this.book = book;} public String getisbn () {Retu
RN ISBN; public void Setisbn (String ISBN) {this.isbn = ISBN;} public string[] Getisbns () {return ISBNs;} public void Setisbns (string[] ISBNs)
{This.isbns = ISBNs;}  Public collection<book> Getbooks () {return books;} public void Setbooks (Collection<book> books) {This.books
= books;  public string Load () {book = Dao.getbook (ISBN), return SUCCESS} public string list () {books = Dao.getbooks ();
SUCCESS;
Public String Store () {Dao.storebook (book);
return SUCCESS;  Public String Remove () {if (Null!= ISBN) {dao.removebook (ISBN);} else {dao.removebooks (ISBNs);} return SUCCESS;}}

Listing 3 Src/tutorial/action/bookaction.java

Bookaction Property ISBN is used to represent the number of books to be edited or deleted, property ISBNs is used to represent an array of numbers for a number of books to be deleted, the property book represents the current books, and the properties book represents the current list of books. Bookaction has four action methods, namely, load, list, store, and remove, and that is, CRUD is centrally implemented in Bookaction.

And then down is the action's configuration code:

<?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>
<package name=" Struts2_crud_demo "extends=" Struts-default "namespace="/book ">
<action name=" "List" class= "tutorial.action.BookAction" method= "list" >
<result>List.jsp</result>
</action>
<action name= "Edit" class= " Tutorial.action.BookAction "method=" "Load" >
<result>Edit.jsp</result>
</action>
<action name= "store" class= "tutorial.action.BookAction" method= "store" >
<result type= "redirect" ">List.action</result>
</action>
<action name=" Remove "class=" Tutorial.action.BookAction "method=" Remove ">
<result type=" redirect ">List.action</result>
</action>
</package>
</struts>

Listing 4 Src/struts.xml

In the above configuration, I have used four action definitions. They are all in the "/book" Name value space. So I can go through the "http://localhost:8080/Struts2_CRUD/Book/List.action", "http://localhost:8080/Struts2_CRUD/Book/", respectively. Edit.action "," Http://localhost:8080/Struts2_CRUD/Book/Store.action "and" http://localhost:8080/Struts2_CRUD/Book/ Remove.action "To invoke the four action methods of bookaction for CRUD operations. Of course, it's just a hobby, you can simply define an action (assuming its name is "book"), and then access it by means of "http://localhost:8080/Struts2_CRUD/Book!list.action". For more information, refer to the Action tutorial on Struts 2.0. Also, because I want to go back to the list page after I finish editing or deleting, I use result with type Redirect (redirect).

The following is the code for the list page:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" Utf-8 "%> <%@ taglib prefix=" s "uri="/struts-tags "%> <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">  

Listing 5 webcontent/book/list.jsp

The above code, notably in the <s:form> tab, I set the theme property to "simple" so that it can cancel its default table layout. Before, some friends asked me "What if you don't want the submit button on the right?" "The above perspiration is one of the answers. Of course, a better way to customize a theme and set it to the default application to the entire site, so that you can get a unified site style. I will give a detailed description of this in future articles.

Edit or add the page code for the book as follows:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" Utf-8 "%>
<%@ taglib prefix=" s "uri="/struts-tags "%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
 
 

Listing 6 webcontent/book/edit.jsp

If the book is null, the page is used to add books, whereas the page is edited.

To facilitate the running of the example, I posted the Web.xml code as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <web-app id= "Webapp_9" version= "2.4" xmlns= "http://"
Java.sun.com/xml/ns/j2ee "
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "
xsi:schemalocation=" HTTP://JAVA.SUN.COM/XML/NS/J2EE http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd ">
<display-name> Struts 2 fileupload</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
< url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
< welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

Listing 7 Webcontent/web-inf/web.xml

Done, the following release runs the application, in the browser type: Http://localhost:8080/Struts2_CRUD/Book/List.action, the following image shows the page:

Listing 8 List Page

Click "ADD Book" to see the following image:

Listing 9 Add a book page

Back to the list page, click "Edit", and the following image shows the page:

Listing 10 Edit a book page

Summarize

This article is just a cursory introduction to the CRUD implementation of struts 2, so there are many features that are not implemented, such as internationalization and data validation. You can make it perfect on the basis of the example above, as well as practice. There is no understanding of the place welcome to my message, small series will promptly reply to everyone, here also thank you for your support cloud Habitat community site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.