CRUD는 작성, 읽기, 업데이트 및 삭제의 약어이며 일반 응용 프로그램의 소우주입니다. 프레임 워크의 CRUD 쓰기를 마스터하는 경우 프레임 워크를 사용하여 일반 응용 프로그램을 만들 수 있습니다. 따라서 새로운 프레임 워크를 사용하여 OLTP (온라인 트랜잭션 처리) 응용 프로그램을 개발할 때 먼저 CRUD 작성 방법을 연구합니다. 이것은 새로운 프로그래밍 언어를 배울 때 사람들이 "Hello World"를 작성하는 방식과 유사합니다.
이 기사는 Struts 2에서 CRUD의 개발을 설명하기위한 것이므로 단순성과 이해의 용이성을 위해 데이터베이스 작업에 시간을 보내지 않을 것입니다. 대신 데이터베이스를 시뮬레이션하는 해시 테이블 (해시 맵).
특정 구현
먼저 "가짜"DAO (데이터 액세스 오브젝트, 데이터 액세스 오브젝트)를 살펴 보겠습니다. 코드는 다음과 같습니다.
PACKED 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 {private static final concurrentmap <string, book / data; bookdao (); data = new ConcurrenThashmap <문자열, book> (); data.put ( "978-0735619678", 새 책 ( "978-0735619678", "코드 완료, 두 번째 에디션", 32.99); data.put ( "978-0596007867", New Book ( "978-0596007867", "프로젝트 관리 기술", 35.96)); data.put ( "978-0201633610", 새 책 ( "978-0201633610", "디자인 패턴 : 재사용 가능한 객체 정리 소프트웨어", 43.19); new.put ( "97896527) Book ( "978-0596527341", "월드 와이드 웹을위한 정보 아키텍처 : 대규모 웹 사이트 설계", 25.19); data.put ( "978-0735605350", 새 책 ( "978-0735605350", "소프트웨어 예술 : 25.19);) {} public static bookdao getInstance () {return incast;} public collection <book> getbooks () {return data.values ();} public book getbook (string isbn) {return data.get (isbn);} public void storebook (book book) {book.put ());} public void remelbook (string book);} {data.remove (isbn);} public void removebooks (string [] isbn) {for (string isbn : isbn) {data.remove (isbn);}}}목록 1 SRC/Tutorial/DAO/BookDao.java
위의 코드에는 설명이 필요하지 않다고 생각합니다. ConcurrentMap 데이터 구조를 사용하여 Book Objects를 저장하는데, 이는 주로 책 객체의 검색 및 저장을 용이하게합니다. 또한 응용 프로그램의 데이터베이스를 시뮬레이션하기 위해 데이터 변수를 정적으로 고유하게 설정했습니다.
다음은 데이터 모델 북 클래스이며 코드는 다음과 같습니다.
패키지 자습서; 공개 클래스 북 {private string isbn; private String 제목; 개인 이중 가격; public book () {} public book (String isbn, String Title, double price) {this.isbn = isbn; this.title = title; this.price;} public string getisbn () {return isbn;} public void setisbn (string isbn) it. isbn;} public double getPrice () {반환 가격;} public void setPrice (double price) {this.price = price;} public string getTitle () {return title;} public void settitle (문자열 제목) {this.title = title;}}2 SRC/Tutorial/Model/Book.java를 나열합니다
이 책 수업에는 세 가지 속성이 있습니다 : ISBN, 제목 및 가격은 각각 책의 숫자, 이름 및 가격을 나타냅니다. 이 번호는 책을 고유하게 식별하는 데 사용됩니다 (데이터베이스의 기본 키에 해당).
그런 다음 액션 클래스의 코드를 살펴 보겠습니다.
패키지 튜토리얼; import java.util.collection; import tutorial.dao.bookdao; import tutorial.model.book; import com.opensymphony.xwork2.actionSupport; public class bookactions 확장 actionSupport {private static long serialversionuid = 872316812305356L; private string;]; 컬렉션 <book> books; private bookdao dao = bookdao.getInstance (); public book getbook () {return book;} public void setbook (} public void setbook (book book) {this.book = book;} public string getisbn () {return isbn;} public void setisbn (string isbn) {thisbn = isbn; isbn;} public void setisbnns (string [] isbnns) {this.isbns = isbnns;} 공개 컬렉션 <book> getbooks () {return books;} public void setbooks (collection <book> books) {this.books = books;} public string load () {public string (return); dao.getbooks (); 반환 성공;} public string store () {dao.storebook (book); return success;} public string remove () {if (null! = isbn) {dao.removebook (isbn);} else {dao.removebooks (isbns);}}}}}}}}3 SRC/Tutorial/Action/BookAction.java를 나열합니다
BookAction 클래스에서 ISBN 속성은 편집 또는 삭제 될 책의 수를 나타내는 데 사용되며 ISBN 속성은 삭제할 책의 숫자 배열을 나타내는 데 사용되며 속성 책은 현재 책을 나타내며 속성 책은 현재 책 목록을 나타냅니다. BookAction에는 4 가지 작업 방법,로드, 목록, 저장 및 제거가 있습니다. 즉, CRUD는 모두 BookAction에서 구현됩니다.
다음은 조치 구성 코드입니다.
<? xml version = "1.0"encoding = "utf-8"?> <! doctype struts public "-// apache 소프트웨어 재단 // dtd struts configuration 2.0 // en" "http://struts.apache.org/dtds/struts-2.0.dtd"> extends = "struts-default"namespace = "/book"> <action name = "list"method = "list"> ridge "list> jsp </action> <action name ="edit "method"> <eccent> edit.jsp </action> <action "method ="store "> </action"> rishect "> result> <restect"> 이름 = "제거"메소드 = "제거"> <결과 유형 = "리디렉션"> list.action.action </resent> </action> </package> </struts>
4 src/struts.xml 목록
위 구성에서는 네 가지 작업 정의를 사용했습니다. 그것들은 모두 "/book"네임 스페이스 내에 있습니다. 이러한 방식으로 "http : // localhost : 8080/struts2_crud/book/list", "http : // localhost : 8080/struts2_crud/book/edit.action", "http : // localhost : 8080/struts2_crud/book/book/book/book/book/book/book/book/book/strud" "http : // localhost : 8080/struts2_crud/book/remove.action". 물론 이것은 개인적인 취향 일뿐입니다. 행동 만 정의 할 수 있습니다 (이름이 "책"이라고 가정 한 다음 "http : // localhost : 8080/struts2_crud/book! list.action"을 통해 액세스 할 수 있습니다. 자세한 내용은 "Struts 2.0 액션 설명"을 참조하십시오. 또한 편집 또는 삭제를 마친 후 목록 페이지로 돌아가려면 유형 리디렉션 (리디렉션)의 결과를 사용합니다.
다음은 목록 페이지의 코드입니다.
< %@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8" %> < %@ taglib prefix = "s"uri = "/struts-tags" %> <! doctype html public "-// dtd xhtml 1.0 transitional // et. "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> html xmlns ="http://www.w3.org/1999/xhtml "> <head> <title> book list </title> <stryst in store type"> csss " Black; Border-Collapse : Collapse;} 테이블 Thead tr {테두리 : 1px solid black; 패딩 : 3px; 배경 색; #cccccc;} 테이블 tbody td {border : 1px solid black; padding : 3px;} </style> </head> <hod> <h2> 도서 목록 </h2> <s : form action = "remove" "remove </stleing> </head> <hod> <h2> 도서 목록 : 3px; CellPacing = "0"> <thead> <tr> <th> 선택 </th> <th> isbn </th> <th> title </th> <th> 가격 </th> <th> 운영 </th> </tr> </thead> <s : iterator value = "books"> <td> <입력 유형 = "checkbox"arebn "isbn"isbn "isbn" " value = "isbn" /> ' /> < /td> <td> <s : 속성 값 = "isbn" /> /> < /td> <td> $ <s : 속성 값 = "price" /> < /td> <td> <a href ='<s : url action = "edit"> <s : param name = "isbn"isbn " /> </s : url> '> edit </a> <a href ='<s : url action = "remove"> <s : param name = "isbn"value = "isbn"/> </s : url> '> delete </a> </td> </td> </s : iterator> </tables> <s : 제출 "/> <a href = "edit.jsp"> 책 추가 </a> </s : form> </body> </html>Listing 5 WebContent/Book/List.jsp
위의 코드에서 <s : form> tag에서 테마 속성을 "Simple"으로 설정하여 기본 테이블 레이아웃을 취소 할 수 있음을 주목할 가치가 있습니다. 이전에 일부 친구들은 "제출 버튼을 오른쪽에 놓고 싶지 않다면 어떻게해야합니까?" 위의 땀은 답 중 하나입니다. 물론 테마를 사용자 정의하고 기본적으로 전체 사이트에 적용하여 통합 사이트 스타일을 얻을 수 있습니다. 나는 이것을 향후 기사에서 자세히 설명하겠습니다.
책을 편집하거나 추가하기위한 페이지 코드는 다음과 같습니다.
< %@ page language = "java"contmenttype = "text/html; charset = utf-8"pageencoding = "utf-8" %> < %@ taglib prefix = "s"uri = "/struts-tags" %> <! doctype html public "-// dtd xhtml 1.0 transitional // et. "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> html xmlns ="http://www.w3.org/1999/xhtml "> "책 추가 < /s : if> <s : else> 편집 서적 < /s : else> < /h2> <s : form action ="store "> <s : textfield name ="book.isbn "label ="isbn " /> <s : textfield name ="book.title "label ="itt /> </s : form> </body> </html>
6 WebContent/book/edit.jsp
책이 null 인 경우 페이지가 책을 추가하는 데 사용되며 그 반대는 편집 페이지입니다.
모든 사람이 예제를 실행하도록 촉진하기 위해 다음과 같이 web.xml 코드도 게시했습니다.
<? 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 : schemalocation ="http://java.sun.sun.sun.sun.sun.sun.sun.sun.sun.sun. http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">display-name>strut 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> </welcle-file-list> </web-app>
목록 7 WebContent/Web-Inf/Web.xml
작업이 완료되고 다음은 응용 프로그램을 실행하도록 게시됩니다. 유형 : http : // localhost : 8080/struts2_crud/book/list.action 아래 그림에 표시된 페이지에 표시됩니다.
목록 8 목록 페이지
"책 추가"를 클릭하면 아래 그림에 표시된 페이지가 나타납니다.
목록 9 책 페이지 추가
목록 페이지로 돌아가서 "편집"을 클릭하면 아래 그림에 표시된 페이지가 나타납니다.
목록 10 편집 책 페이지
요약
이 기사는 Struts 2의 CRUD 구현 방법을 간단히 소개하므로 국제화 및 데이터 검증과 같은 많은 기능이 구현되지 않습니다. 위의 예를 기반으로 개선 할 수 있으며 연습하는 것이 좋습니다. 이해하지 못하면 메시지를 남겨주세요. 편집자는 제 시간에 모든 사람에게 답장을합니다. Wulin Network 웹 사이트를 지원해 주셔서 대단히 감사합니다!