New JBuilder2005 Struts Depth experience

Source: Internet
Author: User
Tags add empty exception handling final sql string version dreamweaver
   Add a Struts configuration file

Considering that the library module is a relatively self-contained module, in order to avoid a team project overlay or conflict due to resource contention on the Struts profile, we provide a separate new struts profile for this module, using this configuration file to configure the Library module with all of the struts-related information.

We add a configuration file named Book-struts-config.xml to the Webmodule module in the following manner.

First to the project directory >/webmodule/ Web-inf Copy an original Struts-config.xml file, renamed to Book-struts-config.xml placed in the same directory struts-config.xml, delete the contents of the original configuration, adjust it to:

! DOCTYPE struts-config Public "-//apache Software foundation//dtd struts Configuration 1.1//en" "http:// Jakarta.apache.org/struts/dtds/struts-config_1_1.dtd ">


Then, in the resource tree of the Engineering pane, navigate to the Webmodule->deployment descriptors-><struts 1.1> node, right-click the <struts 1.1> node, and select Properties from the pop-up menu ... POPs up the properties for ' <struts 1.1> ' dialog box, as shown in Figure 16:


Figure Struts Configuration File Maintenance dialog box
Click Add ... button, select Book-struts-config.xml profile in the pop-up Choose Struts Config file dialog box, press OK this new struts profile will be added to the Struts config files in Web.xml in the list.

After the new profile succeeds, you will find this newly added Struts configuration file under the <struts 1.1> node of the Engineering pane resource tree, as shown in the following illustration:


Figure 172 Struts configuration files
This way, when you create a new Formbean or action, you can choose which configuration file to use to save struts configuration information.

   Book Action Form

Let's start by creating a bookactionform to receive the form data for the new book page, using Book-struts-config.xml to save Bookactionform configuration information. Bookactionform requires data validation self-test, that is, let Bookactionform implement the Validate () method.

Creating Bookactionform is similar to creating useractionform, but in step 1th of the wizard you need to specify Book-struts-config.xml record Bookactionform configuration information, as shown in Figure 18:


Figure 18 Selecting a different configuration file
We added a configuration file to the Web module in the previous section and listed all of the Web module's configuration files in the Struts config dropdown box, where we chose Web-inf/book-struts-config.xml.

In step 2nd of the wizard, we define the following 5 properties for Bookactionform:

String bookid;//the book ID, corresponding to the book_id of the T_book table, is the primary key.
String ISBN;//ISBN
String createdate;//Date Created
String bookname;//Title
String author;//Author


In step 2nd of the wizard, create the Bookactionform directly by pressing finish. Since the BookID property is a primary key, it cannot be duplicated with the records already in the T_book, which can be done through the Bookactionform data self-test mechanism, which is implemented by defining the Validate () method. The wizard has generated the Validate () method framework for Bookactionform, and we just need to write the BookID checksum code in the Validate () method, Bookactionform's final code is shown in Listing 10:

Code List Ten Bookactionform.java

1. Package bookstore;
2.
3. Import Javax.servlet.http.HttpServletRequest;
4. Import org.apache.struts.action.*;
5. Import java.sql.*;
6.
7. public class Bookactionform
8. Extends Actionform {
9...
Public actionerrors Validate (actionmapping actionmapping,
HttpServletRequest httpservletrequest) {
Actionerrors errors = new Actionerrors ();
Connection conn = null;
try {
conn = Dbconnection.getconnection ();
PreparedStatement PStat = conn.preparestatement (
"SELECT COUNT (*) count from T_book where book_id=?");
Pstat.setstring (1, this.bookid);
ResultSet rs = Pstat.executequery ();
if (Rs.next () && rs.getint (1) > 0) {
Errors.add ("BookID",
New Actionmessage ("Bookstore.duplicate.bookId",
23. "Book ID and database existing ID duplicate");

24.}
25.}
-catch (SQLException se) {
Se.printstacktrace ();
Errors.add ("BookID",
New Actionmessage ("Bookstore.dbaccess.error", "Error accessing database"));

30.}
finally {
try {
IF (conn!= null) {
Conn.close ();
35.}
36.}
catch (SQLException ex) {
Ex.printstacktrace ();
Errors.add ("BookID"),
New Actionmessage ("Bookstore.dbaccess.error",
41. "Error accessing database"));

42.}
43.}
errors return;
45.}
46.
public void Reset (Actionmapping actionmapping,
HttpServletRequest ServletRequest) {
This.createdate = Getcurrdatestr ();
50.}
51.
52.//Get current time character
private static String Getcurrdatestr () {
SimpleDateFormat SDF = new SimpleDateFormat ("YyyyMMdd");
Return Sdf.format (New Date ());
56.}
57.}


When the user submits the form, the Struts framework automatically populates the form data into Actionform, and the struts framework automatically invokes the Actionform validate () method for data validation. If the Validate () method returns actionerrors null or does not contain any Actionmessage objects, the Struts framework passes the Actionform and the HTTP request to execute () with the action, by validation. Otherwise, the Struts framework returns the HTTP request to the entered page, and the input page is displayed by displaying the actionerrors error message in the corresponding request field.

In addition, we set the CreateDate property to the current date in the Reset () method, because the property value is not provided through the page form.

  New book JSP page

1. Creating Bookadd.jsp with wizards

Create the bookadd.jsp page through the JSP Wizard, and in step 2nd of the wizard, choose to use the Struts-bean and struts-html tags of Struts1.1, as shown in Figure 19:


Figure 19 Specifies the Struts label selection
2. Building a JSP page using the JBuilder struts tag

You can add the Struts tab to the JSP page directly from the tag library on the left side of the JBuilder editor by dragging, as shown in Figure 20:


Figure 20 Adding a struts label in a drag-and-drop way
Struts's HTML tags can complete the same functionality as standard HTML elements, and struts advocates the use of the Struts HTML tag library because these tags can be tightly linked to other components of the struts framework. The Strtus Bean Tag Library has access to existing JavaBean and its properties, and some bean tags also have access to HTTP request header information and Web resource file information.

We would like to use the HTML tag Library of struts to create a form to add a book, and access the Web resource file through the Bean tag Library as the identity text before the form component.

The final code for bookadd.jsp is shown in Listing 11:

Code List One bookadd.jsp

1. <% @page contenttype= "text/html; CHARSET=GBK "%>
2. <% @taglib uri= "/web-inf/struts-bean.tld" prefix= "Bean"%>
3. <% @taglib uri= "/web-inf/struts-html.tld" prefix= "html"%>
4. The 5. The 6. <title> Bookinsert </title>
7. <script language= "JavaScript"
8. Function Mysubmit (form)
9. {
if (Form.isbn.value = null | | form.isbn.value = "")
11. {
Alert ("The book's ISBN is not allowed to be empty");
return false;
14.}
if (Form.bookName.value = null | | form.bookName.value = "")
16. {
Alert ("The book name is not allowed to be empty");
return false;
19.}
20.}
</script>.
<body bgcolor= "#ffffff"
A. . >
<table width= "100%%" border= "0"
<tr>
-<td>

-</td>
A. <td>
A. </td>
. <td>
<bean:message bundle= "Bookstore" key= "BOOKSTORE.ISBN"/>
Panax Notoginseng. </td>
<td>.
. </td>
A. </tr>
. <tr>
A. <td>
<bean:message bundle= "Bookstore" key= "Bookstore.bookname"/>
. </td>
A. <td>
A. </td>
A. <td>
<bean:message bundle= "Bookstore" key= "Bookstore.author"/>
A. </td>
<td>.
</td>.
</tr>.
<TR align= "Center"
<TD colspan= "4"
A. </td>
A. </tr>
. </table>
A. A. </body>
A.
The 25th to 63rd line is the definition code for the form, which specifies the
On line 26th, we specified a onsubmit client checksum function for
We have defined 4

Graphical interface diagram of bookadd.jsp design
Of course, you can write a specific identity directly before the form component, such as "book ID" instead of the <bean:message> label on line 30th, but the latter generates a specific identity through a resource file, which provides an internationalized feature as well as the identity of the resource file control directly.

Above, we simply refer to the resource file named Bookstore, and we need to create the resource file and describe it in the struts configuration file.

Under the >/SRC directory of the engineering directory, create a resource file named Bookstoreresource_zh_cn.properties, which reads as follows:

Bookstore.bookid=\u56fe\u4e66idbookstore.isbn=isbnbookstore.bookname=_
\u56fe\u4e66\u540dbookstore.author=\u4f5c\u8005bookstore.dbaccess.error=_
\u6570\u636e\u5e93\u8bbf\u95ee\u9519\u8befbookstore.duplicate.bookid=_
\u56fe\u4e66\u7f16\u53f7\u548c\u6570\u636e\u5e93\u4e2d\u5df2\u6709\u7684\u7f16\u53f7\u91cd\u590d


The Chinese text must be in the Unicode format and the corresponding Chinese document should read:

bookstore.bookid= book idbookstore.isbn=isbnbookstore.bookname= book name bookstore.author= author bookstore.dbaccess.error= Database access error bookstore.duplicate.bookid= the book number and the number in the database are duplicated


When compiling the project, JBuilder copies the resource files located under the project directory >/SRC to the web-inf/classes directory of the Web module.

  Tips:

The JDK provides a tool native2ascii.exe to convert Chinese to Unicode encoding format, which is located in the /bin/directory. In the DOS command window, through native2ascii-encoding GBK the source file >

The conversion can be completed in the target file.


Attention:

In the previous article, we mentioned a bug in JBuilder 2005, where classes or resources in a Web module are sometimes not synchronized and need to manually copy the classes and resources to the corresponding directories. If you find that the resource file is not synchronized to the Web-inf/classes directory, the bookstoreresource_zh_cn.properties needs to manually copy it to the directory after compiling the project, or struts will not be able to find the resources.


In the resource tree in the Engineering pane, find the Book-struts-config.xml double hit open its corresponding struts config Editor and switch to the Message Resources tab as shown in:


Figure 22 Defining a resource file
Through Add ... button to define a Bookstoreresource resource file with a key named bookstore. Clients of different locales will access different resource files, such as when the client is in the Chinese environment, will access bookstoreresource_ch_cn.properties if the English-speaking client will access the Bookstoreresource_ Cn.properties resource file, if no resource file is found for the corresponding language, the default resource file is accessed, where the default resource file is Bookstoreresource.properties. The boudle of the <bean:message> is the name defined by the parameter column.

Practical experience:

The author originally on the Struts label is relatively repulsive, because although it is intended to be the page display logic and procedural logic perfectly separate. The work of page design is done by the page designer in Dreamweaver, because Dreamweaver doesn't know the label of struts, the struts labels of form components like
Many struts developers have long dreamed of getting a Dreamweaver struts tag extension that allows page designers to design pages like standard HTML component tags. FWA Company's visual Tags for struts plugin has finally made our dreams come true. With this plug-in, you can combine the Dreamweaver perfectly with struts, and the JSP pages using struts tags can be visualized at design time with the same standard HTML tags. You can download the trial version of visual Tags for struts through http://www.fwasi.com/downloads/. The bookadd.jsp effect interface of Figure 21, which is the effect page after using the visual Tags for Struts plug-in in Dreamweaver 2004.

In addition, a little bit about the Struts tag must also be mentioned: Sun has developed JSF page tags, which are functionally overlapping with struts, and the future version of struts will move toward JSF, and the JSF label may eventually replace Struts's own label, In order to achieve the world's grand unification.

  Create Bookinsertaction

Next, we create Bookinsertaction, where the book records are added to the T_book table. If the operation is successfully directed to the Insertsuccess.htm Operation Success Page, if the SqlException is found when the database operation is performed, the Sqlfail.htm page is turned. We need to create these two HTML pages in advance, and in order to be simple, write the information about the success and failure of the report operation.

Create Bookinsertaction in a 3.2 similar way, record configuration information with Book-struts-config.xml, and in step 2nd of the wizard, designate Formbean name as bookactionform,scope as request , specify the input JSP as/bookadd.jsp, as shown in Figure 23:


Figure 23 indicates the configuration information for the Bookinsertaction
Creating Bookinsertaction,jbuilder directly by finish will open the Struts Config editor display/bookinsertaction process, as shown in Figure 24:


Figure Bookinsertaction Process
Add 1 exits, named success, and the path is/insertsuccess.htm. The final/bookinsertaction process is shown in Figure 5.

Code Listing 12 is the Bookinsertaction code that completes the book add, Export-controlled operation:

Code List Bookinsertaction.java

1. Package bookstore;
2.
3. Import javax.servlet.http.*;
4. Import org.apache.struts.action.*;
5. Import java.sql.*;
6.
7. public class Bookinsertaction
8. Extends Action {
9. Public Actionforward Execute (actionmapping actionmapping,
Actionform Actionform,
HttpServletRequest ServletRequest,
HttpServletResponse servletresponse)
throws Exception
14. {
Bookactionform bookactionform = (bookactionform) actionform;
Connection conn = null;
conn = Dbconnection.getconnection ();
PreparedStatement PStat = conn.preparestatement (
Insert into T_book1 (Book_id,isbn,book_name,author, "+
"Create_date) VALUES (?,?,?,?,?)");
Pstat.setstring (1, Bookactionform.getbookid ());
Pstat.setstring (2, BOOKACTIONFORM.GETISBN ());
Pstat.setstring (3, Bookactionform.getbookname ());
Pstat.setstring (4, Bookactionform.getauthor ());
Pstat.setstring (5, Bookactionform.getcreatedate ());
Pstat.executeupdate ();
Return Actionmapping.findforward ("Success");
28.
29.}
30.}


Bookinsertaction adds bookactionform data to the T_book table through JDBC, adding success to the Insertsuccess.htm page. Some observant readers may have noticed that the bookinsertaction execute () method does not deal directly with SqlException, but rather throws the exception, as shown in line 13th. Here, we're going to use Struts1.1 's new feature: Handling Exceptions in a configuration way.

Locate and double-click book-struts-config.xml file under Webmodule/deployment descriptors/<struts 1.1> in the Engineering pane, and pull up the Struts Config Editor configuration Editor. Switch to the Global Exceptions tab page, as shown in Figure 25:


Figure 25 Exception handling configuration
Click Add ... Define an exception handling configuration item named SqlException, handle java.sql.SQLException exception, after defining this configuration item, select this configuration item, click Edit ... Switch to the Detail Settings page for this configuration item, as shown in Figure 26:


Figure 26 Exception Handling Configuration window
In the lower part of the window, switch to the Source view page, and the configuration information for this exception configuration item is shown in Listing 13:

Exception handling configuration entry for code listing SqlException

1...
2. The
3...
4. The
5. 6. Path= "/sqlfail.htm"/>
7. The
8...
9. The


Line 5th to 6th/sqlfail.htm and java.sql.SQLException are "hooked up" so that the SQLException exception thrown by the Execute () method of any action in the program is handled by the SQLException configuration item.

Add a link to call bookadd.jsp on the welcome.jsp page, and after you log on to the system, pull the bookadd.jsp page through this outer link, as shown in Figure 27:


Figure 27 Adding a book page
Fill in the book record, click on the Save Submission form to the/bookinsertaction action, if the supplied book ID and T_book in the existing book_id repeat, then the struts controller will return directly to the Bookadd.jsp page, by
Tips:

If you use Tomcat for the Web server, if the book records will appear in Chinese garbled problem, you can use the above introduced a code filter, you can configure this filter in the Web.xml, garbled problem can be solved.



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.